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:

enter image description here

Mask Image:

enter image description here

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

enter image description here

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like