简体   繁体   English

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

[英]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?有没有办法将二进制转换回rgb?

Original Image:原图:

在此处输入图像描述

Mask Image:蒙版图片:

在此处输入图像描述

I just want to restore the black area with the original image.我只想用原始图像恢复黑色区域。

Something like this, but your mask is the wrong size (200x200 px) so it doesn't match your image (600x450 px): 像这样的东西,但是您的蒙版大小错误(200x200 px),因此与您的图片(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')

在此处输入图片说明

As I know binary images are stored in grayscale in opencv values 1-->255. 据我所知,二进制图像以灰度形式存储在opencv值1-> 255中。

To create „dummy“ RGB images you can do: rgb_img = cv2.cvtColor(binary_img, cv.CV_GRAY2RGB) 要创建“虚拟” RGB图像,您可以执行以下操作: 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. 我称它们为“虚拟”,因为在这些图像中,红色,绿色和蓝色值是相同的。

I updated the Daniel Tremer's answer :我更新了 Daniel Tremer 的回答

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_image将是像 [width, height] 这样的二维矩阵。
opencv_rgb_img would be three dimension matrix like [width, height, color channel] because of RGB.由于 RGB, opencv_rgb_img将是像 [width, height, color channel] 的三维矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM