2017-08-05 100 views
0

我有一個像this one調色板圖像,並在numpy的陣列的二值化圖像,例如一個正方形像這樣:獲得從調色板圖像RGB顏色和適用於二值圖像

img = np.zeros((100,100), dtype=np.bool) 
img[25:75,25:75] = 1 

(實圖像更復雜的課程)

我想做到以下幾點:

  1. 摘自調色板圖像所有RGB顏色。

  2. 對於每種顏色,請以透明背景保存該顏色的副本img

到目前爲止我的代碼(見下文)可以將img保存爲具有透明背景的黑色對象。我掙扎着的是提取RGB顏色的好方法,所以我可以將它們應用到圖像上。

# Create an MxNx4 array (RGBA) 
img_rgba = np.zeros((img.shape[0], img.shape[1], 4), dtype=np.bool) 

# Fill R, G and B with inverted copies of the image 
# Note: This creates a black object; instead of this, I need the colors from the palette. 
for c in range(3): 
    img_rgba[:,:,c] = ~img 

# For alpha just use the image again (makes background transparent) 
img_rgba[:,:,3] = img 

# Save image 
imsave('img.png', img_rgba) 

回答

2

可以使用的reshapenp.unique組合從你的調色板圖像中提取獨特的RGB值:

# Load the color palette 
from skimage import io 
palette = io.imread(os.path.join(os.getcwd(), 'color_palette.png')) 

# Use `np.unique` following a reshape to get the RGB values 
palette = palette.reshape(palette.shape[0]*palette.shape[1], palette.shape[2]) 
palette_colors = np.unique(palette, axis=0) 

(請注意,np.uniqueaxis論點在numpy的版本1.13.0添加,所以你可能需要升級numpy才能正常工作。)

一旦你有palette_colors,你幾乎可以使用你的代碼您必須保存圖像,除了您現在將不同的RGB值添加到您的img_rgba陣列中以代替~img的副本。

for p in range(palette_colors.shape[0]): 

    # Create an MxNx4 array (RGBA) 
    img_rgba = np.zeros((img.shape[0], img.shape[1], 4), dtype=np.uint8) 

    # Fill R, G and B with appropriate colors 
    for c in range(3): 
     img_rgba[:,:,c] = img.astype(np.uint8) * palette_colors[p,c] 

    # For alpha just use the image again (makes background transparent) 
    img_rgba[:,:,3] = img.astype(np.uint8) * 255 

    # Save image 
    imsave('img_col'+str(p)+'.png', img_rgba) 

(請注意,你需要使用np.uint8的數據類型爲你的形象,因爲二進制圖像顯然不能代表不同的顏色。)