简体   繁体   English

如何使用opencv python将图像的alpha通道转换为白色?

[英]how to convert alpha channel of the image to white color using opencv python?

I want to convert PNG and GIF images to JPEG using openCV, the alpha channel should be converted to white color.我想使用 openCV 将 PNG 和 GIF 图像转换为 JPEG,应该将 alpha 通道转换为白色。 is there any way to achive this ?有什么办法可以做到这一点吗?

Using Open CV, you can open the image in RGB format, ie, when you are doing an cv2.imread give the second parameter as 1 instead of -1.使用 Open CV,您可以打开 RGB 格式的图像,即,当您执行 cv2.imread 时,将第二个参数设为 1 而不是 -1。 -1 opens the image in whatever be the original format of the image , ie, it would retain the transparency. -1 以任何图像的原始格式打开图像,即它会保留透明度。 Keeping that parameter as 1 you can open it in RGB format.将该参数保持为 1,您可以以 RGB 格式打开它。 After that you can do an cv2.imwrite to save the RGB image without transparency.之后,您可以执行 cv2.imwrite 来保存没有透明度的 RGB 图像。 You can mention the file format as .jpg您可以提及文件格式为 .jpg

in RGBA images, alpha channel represent how background will effect in image.在 RGBA 图像中,alpha 通道表示背景对图像的影响。 so you have an equation (not code) like this:所以你有一个这样的方程(不是代码):

out = (bg * (1 - alpha)) + (image * alpha)

where out is final image and image is R,G and B channel of our RGBA image and bg is background image.其中 out 是最终图像,图像是我们 RGBA 图像的 R、G 和 B 通道,bg 是背景图像。 here we have 0 <= alpha <= 1.这里我们有 0 <= alpha <= 1。

for your case, you want your background to be a plane white image so the calculation is very simple from this point.对于您的情况,您希望您的背景是平面白色图像,因此从这一点上计算非常简单。 you can do something like this:你可以这样做:

B, G, R, A = cv2.split(image)
alpha = A / 255

R = (255 * (1 - alpha) + R * alpha).astype(np.uint8)
G = (255 * (1 - alpha) + G * alpha).astype(np.uint8)
B = (255 * (1 - alpha) + B * alpha).astype(np.uint8)

image = cv2.merge((B, G, R))

and if you don't like this split and merge stuff (like me) you can use this implimentation:如果你不喜欢这种拆分和合并的东西(像我一样),你可以使用这个实现:

bg = np.array([255, 255, 255])
alpha = (image[:, :, 3] / 255).reshape(image.shape[:2] + (1,))
image = ((bg * (1 - alpha)) + (image[:, :, :3] * alpha)).astype(np.uint8)

in first line i make background image, in second line i compute the alpha value between 0 and 1 and reshape it to make it 3-D array (it is necessary for multiplication) and the last line is the formula of alpha.在第一行我制作背景图像,在第二行我计算 0 和 1 之间的 alpha 值并将其重塑以使其成为 3-D 数组(乘法需要),最后一行是 alpha 的公式。

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

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