我正在尝试制作透明图像并在其上绘图,之后我将在基本图像上添加加权。
如何在openCV python中初始化宽度和高度的完全透明图像?
编辑:我想在Photoshop中创建一个效果,有层叠,所有堆叠的图层最初都是透明的,并且在完全透明的图层上执行绘制。最后,我将合并所有图层以获得最终图像答案 0 :(得分:3)
要创建透明图像,您需要一个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)
答案 1 :(得分: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)