如何使用Python将二进制图像转换为灰度和RGB?

3

我正在处理皮损图像的毛发去除。有没有办法将二进制转换回RGB?

原始图像:

enter image description here

遮罩图像:

enter image description here

我只想用原始图像恢复黑色区域。

你为什么要这样做呢? - ZdaR
我想从皮肤病变图像中去除毛发,我进行了一定的模糊和滤波,并将图像转换为二进制。因此,我想加载没有毛发的原始图像。 - codelearn22
你能上传二进制图像和原始图像吗?很多事情都取决于你的二进制图像格式,前景是白色还是背景是白色,或者反过来。 - ZdaR
听起来你不想“转换”任何东西,而是想使用一张图片来“掩盖”另一张图片。 - hobbs
我想获取二值图像黑色区域中原始的区域。 - codelearn22
3个回答

7
据我所知,在OpenCV中,二进制图像以灰度形式存储,值为1-255。
要创建“虚拟”RGB图像,可以执行以下操作: rgb_img = cv2.cvtColor(binary_img, cv.CV_GRAY2RGB) 我称它们为“虚拟”,因为在这些图像中,红色、绿色和蓝色的值都是相同的。

我使用了PIL进行二值化处理,同时使用opencv进行滤波。 - codelearn22

4

类似这样的情况,但是您的遮罩大小不正确(200x200像素),因此与您的图像(600x450像素)不匹配:

#!/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


是的,就像这样,但我想把头发去掉。 - codelearn22
嗯...如果你正在使用OpenCV进行所有的重型图像处理(而不是像我一样使用NumPy),我建议你改进那里的掩模,以便它遮盖住头发,然后使用我的代码。 - Mark Setchell

1

我更新了Daniel Tremer的答案:

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

opencv_image 是一个二维矩阵,其维度为 [宽度, 高度],因为它是二进制的。
opencv_rgb_img 是一个三维矩阵,其维度为 [宽度, 高度, 颜色通道],因为它是 RGB 格式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接