在opencv python中创建透明图像

新手上路,请多包涵

我正在尝试制作一个透明图像并在其上绘制,然后我将在基础图像上添加加权。

如何在 openCV python 中初始化具有宽度和高度的完全透明图像?

编辑:我想像在 Photoshop 中一样制作效果,具有堆叠的图层,所有堆叠的图层最初都是透明的,并且在完全透明的图层上执行绘图。最后我将合并所有图层以获得最终图像

原文由 Michael Presečan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 981
2 个回答

如果你想在几个“图层”上绘图,然后将绘图堆叠在一起,那么如何:

 import cv2
import numpy as np

#create 3 separate BGRA images as our "layers"
layer1 = np.zeros((500, 500, 4))
layer2 = np.zeros((500, 500, 4))
layer3 = np.zeros((500, 500, 4))

#draw a red circle on the first "layer",
#a green rectangle on the second "layer",
#a blue line on the third "layer"
red_color = (0, 0, 255, 255)
green_color = (0, 255, 0, 255)
blue_color = (255, 0, 0, 255)
cv2.circle(layer1, (255, 255), 100, red_color, 5)
cv2.rectangle(layer2, (175, 175), (335, 335), green_color, 5)
cv2.line(layer3, (170, 170), (340, 340), blue_color, 5)

res = layer1[:] #copy the first layer into the resulting image

#copy only the pixels we were drawing on from the 2nd and 3rd layers
#(if you don't do this, the black background will also be copied)
cnd = layer2[:, :, 3] > 0
res[cnd] = layer2[cnd]
cnd = layer3[:, :, 3] > 0
res[cnd] = layer3[cnd]

cv2.imwrite("out.png", res)

在此处输入图像描述

原文由 Headcrab 发布,翻译遵循 CC BY-SA 3.0 许可协议

要创建透明图像,您需要一个 4 通道矩阵,其中 3 个代表 RGB 颜色,第 4 个通道代表 Alpha 通道,要创建透明图像,您可以忽略 RGB 值并直接将 Alpha 通道设置为 0 。在 Python 中,OpenCV 使用 numpy 来操作矩阵,因此透明图像可以创建为

import numpy as np
import cv2

img_height, img_width = 300, 300
n_channels = 4
transparent_img = np.zeros((img_height, img_width, n_channels), dtype=np.uint8)

# Save the image for visualization
cv2.imwrite("./transparent_img.png", transparent_img)

原文由 ZdaR 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题