简体   繁体   English

使用自定义托盘将numpy数组转换为RGB img

[英]Convert numpy array to RGB img with custom pallete

I want to convert a numpy.ndarray: 我想转换一个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]]

to RGB img. 到RGB img。

The colors are taken from an array: 颜色取自数组:

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

So, for example, all the pixels with index 12 will be white (255,255,255). 因此,例如,索引为12的所有像素都将为白色(255,255,255)。
The way I do it now is very slow (about 1.5 sec/img): 我现在这样做的方式非常慢(约1.5秒/ img):

        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(...)

what is the efficient way to do it faster? 更快速地做到这一点的有效方法是什么?

You can just use the full image as index for the look-up table. 您可以使用完整图像作为查找表的索引。

Something like data = colors_pal[out] 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()

结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM