我正在尝试制作一个透明图像并在其上绘制,之后我会在基础图像上添加addWeighted。如何在openCV python中初始化完全透明的宽度和高度图像?编辑:我想制作一种像Photoshop中那样的效果,具有图层堆栈,所有堆叠的图层最初都是透明的,并且在完全透明的图层上执行绘制。最后,我将合并所有图层以获得最终图像。
要创建一个透明图像,需要一个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)
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)
将图片中的白色部分转换为透明:
import cv2
import numpy as np
img = cv2.imread("image.png", cv2.IMREAD_UNCHANGED)
img[np.where(np.all(img[..., :3] == 255, -1))] = 0
cv2.imwrite("transparent.png", img)