【问题标题】:Get RGB colors from color palette image and apply to binary image从调色板图像中获取 RGB 颜色并应用于二进制图像
【发布时间】:2018-01-13 08:39:13
【问题描述】:

我有一个像 this one 这样的调色板图像和一个 numpy 数组中的二值化图像,例如像这样的正方形:

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) 

【问题讨论】:

    标签: python numpy image-processing scikit-image


    【解决方案1】:

    您可以结合使用 reshape 和 np.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.unique 的 axis 参数是在 numpy 版本 1.13.0 中添加的,因此您可能需要升级 numpy 才能使其正常工作。)

    拥有palette_colors 后,您几乎可以使用已有的代码来保存图像,只是现在将不同的RGB 值而不是~img 的副本添加到img_rgba 数组中。

    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 作为图像的数据类型,因为二进制图像显然不能代表不同的颜色。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-04
      相关资源
      最近更新 更多