user7492490
user7492490

Reputation:

Get RGB colors from color palette image and apply to binary image

I have a color palette image like this one and a binarized image in a numpy array, for example a square such as this:

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

(The real images are more complicated of course.)

I would like to do the following:

  1. Extract all RGB colors from the color palette image.

  2. For each color, save a copy of img in that color with a transparent background.

My code so far (see below) can save the img as a black object with transparent background. What I am struggling with is a good way of extracting the RGB colors so I can apply them to the image.

# 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) 

Upvotes: 0

Views: 1907

Answers (1)

WhoIsJack
WhoIsJack

Reputation: 1498

You can use a combination of a reshape and np.unique to extract the unique RGB values from your color palette image:

# 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)

(Note that the axis argument for np.unique was added in numpy version 1.13.0, so you may need to upgrade numpy for this to work.)

Once you have palette_colors, you can pretty much use the code you already have to save the image, except you now add the different RGB values instead of copies of ~img to your img_rgba array.

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)

(Note that you need to use np.uint8 as datatype for your image, since binary images obviously cannot represent different colors.)

Upvotes: 1

Related Questions