rgb_img = cv2.cvtColor(binary_img, cv.CV_GRAY2RGB)
我称它们为“虚拟”,因为在这些图像中,红色、绿色和蓝色的值都是相同的。类似这样的情况,但是您的遮罩大小不正确(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')
我更新了Daniel Tremer的答案:
import cv2
opencv_rgb_img = cv2.cvtColor(opencv_image, cv2.COLOR_GRAY2RGB)
opencv_image
是一个二维矩阵,其维度为 [宽度, 高度],因为它是二进制的。
opencv_rgb_img
是一个三维矩阵,其维度为 [宽度, 高度, 颜色通道],因为它是 RGB 格式。