Home > front end >  How to color a grayscale image based on a mask?
How to color a grayscale image based on a mask?

Time:05-08

I have two images: A grayscale image, and a binary mask with the same dimensions. How do I color the image on the mask, while the rest of the image remains grayscale?

Here's and example:

enter image description here

CodePudding user response:

Expressing your grey image pixel values across 3-channels gives you a color image. The result would look the same but when you check the dimensions it would be 3.

gray_3_channel = cv2.merge((gray, gray, gray))

gray.shape
>>> (158, 99)
gray_3_channel.shape
>>> (158, 99, 3)

For every white (255) pixel in the mask, assign the color (255, 255, 0) in gray_3_channel:

gray_3_channel[mask==255]=(255, 255, 0)

enter image description here

  • Related