codelearn22
codelearn22

Reputation: 43

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.

Upvotes: 3

Views: 29428

Answers (3)

Cloud Cho
Cloud Cho

Reputation: 1774

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.

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207863

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

Upvotes: 4

Daniel Tremer
Daniel Tremer

Reputation: 200

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.

Upvotes: 7

Related Questions