python OpenCV-将alpha通道添加到RGB imag

2024-05-13 06:56:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中使用opencv将RGB图像转换为RGBA的最佳方法是什么?

假设我有一个带形状的数组

(185, 198, 3) - it is RGB

另一个是形状为(185, 198)的alpha掩码

如何合并并保存到文件?


Tags: 文件方法图像alphaisitrgb数组
3条回答

下面是另一个使用Grabcut的简单示例,它有助于在将图像保存到磁盘vspyplot时获得正确的通道顺序。

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()

使用opencv3,应该可以:

Python

# First create the image with alpha channel
rgba = cv2.cvtColor(rgb_data, cv2.COLOR_RGB2RGBA)

# Then assign the mask to the last channel of the image
rgba[:, :, 3] = alpha_data

C++ +<

# First create the image with alpha channel
cv::cvtColor(rgb_data, rgba , cv::COLOR_RGB2RGBA);

# Split the image for access to alpha channel
std::vector<cv::Mat>channels(4);
cv::split(rgba, channels);

# Assign the mask to the last channel of the image
channels[3] = alpha_data;

# Finally concat channels for rgba image
cv::merge(channels, 4, rgba);

可以使用^{}将alpha通道添加到给定的RGB图像,但首先需要按照documentation将RGB图像分割到R, G and B通道:

Python: cv2.merge(mv[, dst])

  • mv – input array or vector of matrices to be merged; all the matrices in mv must have the same size and the same depth.

可以这样做:

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))

相关问题 更多 >