How to Convert a Binary Image to Grayscale and Rgb Using Python?

I am working on hair removal from skin lesion images. Is there any way to convert binary back to rgb?

Original Image:

Mask Image:

I just want to restore the black area with the original image.

5

3 Answers

As I know binary images are stored in grayscale in opencv values 1-->255.

To create „dummy“ RGB images you can do: rgb_img = cv2.cvtColor(binary_img, cv.CV_GRAY2RGB)

I call them „dummy“ since in these images the red, green and blue values are just the same.

1

Something like this, but your mask is the wrong size (200x200 px) so it doesn't match your image (600x450 px):

#!/usr/local/bin/python3
from PIL import Image
import numpy as np

# Open the input image as numpy array
npImage=np.array(Image.open("image.jpg"))
# Open the mask image as numpy array
npMask=np.array(Image.open("mask2.jpg").convert("RGB"))

# Make a binary array identifying where the mask is black
cond = npMask<128

# Select image or mask according to condition array
pixels=np.where(cond, npImage, npMask)

# Save resulting image
result=Image.fromarray(pixels)
result.save('result.png')
2

I updated the Daniel Tremer's answer:

import cv2
opencv_rgb_img = cv2.cvtColor(opencv_image, cv2.COLOR_GRAY2RGB)

opencv_image would be two dimension matrix like [width, height] because of binary.
opencv_rgb_img would be three dimension matrix like [width, height, color channel] because of RGB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest