【问题标题】:Convert numpy array to RGB img with custom pallete使用自定义调色板将 numpy 数组转换为 RGB 图像
【发布时间】:2018-10-23 19:33:59
【问题描述】:

我想转换一个 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秒/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(...)

加快速度的有效方法是什么?

【问题讨论】:

    标签: python image python-2.7 numpy


    【解决方案1】:

    您可以只使用完整图像作为查找表的索引。

    类似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()
    

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 2021-04-02
      • 2018-09-28
      • 2018-04-09
      相关资源
      最近更新 更多