什么是在Python中使用opencv将RGB图像转换为RGBA的最佳方式?python OpenCV - 将alpha通道添加到RGB图像
比方说,我有一个数组形状
(185, 198, 3) - it is RGB
,另一个是阿尔法遮掩与形状(185, 198)
如何合并它们并保存到文件?
什么是在Python中使用opencv将RGB图像转换为RGBA的最佳方式?python OpenCV - 将alpha通道添加到RGB图像
比方说,我有一个数组形状
(185, 198, 3) - it is RGB
,另一个是阿尔法遮掩与形状(185, 198)
如何合并它们并保存到文件?
您可以使用cv2.merge()
添加alpha通道给定的RGB图像,但首先你需要的RGB图像分割到R, G and B
渠道,按照documentation:
的Python:cv2.merge(MV [,dst])
- mv - 要合并的矩阵的输入数组或向量; mv中的所有矩阵必须具有相同的大小和相同的深度。
这是可以做到:
b_channel, g_channel, r_channel = cv2.split(img)
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 50 #creating a dummy alpha channel image.
img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
下面是一个使用Grabcut另一个简单的例子,它可以帮助节省磁盘上的图像VS pyplot
什么时候能得到正确的渠道秩序。
from matplotlib import pyplot as plt
import numpy as np
import cv2
img = cv2.imread('image.jpg')
mask = np.zeros(img.shape[:2], np.uint8)
bgdModel = np.zeros((1,65), np.float64)
fgdModel = np.zeros((1,65), np.float64)
rect = (50, 50, 450, 290)
# Grabcut
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
r_channel, g_channel, b_channel = cv2.split(img)
a_channel = np.where((mask==2)|(mask==0), 0, 255).astype('uint8')
img_RGBA = cv2.merge((r_channel, g_channel, b_channel, a_channel))
cv2.imwrite("test.png", img_RGBA)
# Now for plot correct colors :
img_BGRA = cv2.merge((b_channel, g_channel, r_channel, a_channel))
plt.imshow(img_BGRA), plt.colorbar(),plt.show()
我试图与使用python 2和OpenCV 3.1.0-dev的RGB图像,并且因为'alpha_channel'不具有方法'深度它提出了断言错误()'。它似乎明确地想要一个矩阵矢量,但'np.ones'生成一个规则的numpy nd-array。 – spanishgum
有人可能想要做'alpha_channel = alpha_channel.astype(np.uint8)',即确保所有通道具有相同的dtype。 –
编辑您的宝贵建议。 – ZdaR