使用自定义调色板将numpy数组转换为RGB图像

5

我想要转换一个numpy.ndarray:

out = [[12 12 12 ..., 12 12 12]
     [12 12 12 ..., 12 12 12]
     [12 12 12 ..., 12 12 12]
     ...,
     [11 11 11 ..., 10 10 10]
     [11 11 11 ..., 10 10 10]
     [11 11 11 ..., 10 10 10]]

转为RGB图像。

颜色来自数组:

colors_pal = np.array(
           [0,0,128],      #ind 0
           [0,0,0],
           ....
           [255,255,255]], #ind 12
           dtype=np.float32)

因此,例如,索引为12的所有像素将是白色(255,255,255)。 我现在的做法非常慢(大约1.5秒/张图片):
        data = np.zeros((out.shape[0],out.shape[1],3), dtype=np.uint8 )
        for x in range(0,out.shape[0]):
            for y in range(0,out.shape[1]):
                data[x,y] = colors_pal[out[x][y]]
        img = Image.fromarray(data)
        img.save(...)

如何更高效地快速完成这项任务?

1个回答

2
你可以将完整的图像作为查找表的索引。 类似于data = colors_pal[out]这样的东西。
import numpy as np
import matplotlib.pyplot as plt
import skimage.data
import skimage.color

# sample image, grayscale 8 bits
img = skimage.color.rgb2gray(skimage.data.astronaut())
img = (img * 255).astype(np.uint8)
# sample LUT from matplotlib
lut = (plt.cm.jet(np.arange(256)) * 255).astype(np.uint8)

# apply LUT and display
plt.imshow(lut[img])
plt.show()

result


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接