簡體   English   中英

使用自定義托盤將numpy數組轉換為RGB img

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

我想轉換一個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 img。

顏色取自數組:

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

更快速地做到這一點的有效方法是什么?

您可以使用完整圖像作為查找表的索引。

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