Mic*_*čan 3 python opencv image-processing
我试图制作一个透明图像并在其上绘制,然后在基础图像上添加加权。
如何在openCV python中初始化具有宽度和高度的完全透明的图像?
编辑:我想像在Photoshop中那样,具有层的堆叠,所有堆叠的层最初都是透明的,并且绘制是在完全透明的层上进行的。最后,我将合并所有图层以获得最终图像
Hea*_*rab 11
如果你想在几个“层”上绘制,然后把这些图叠在一起,那么这个怎么样:
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)
Run Code Online (Sandbox Code Playgroud)
要创建透明图像,您需要一个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)
Run Code Online (Sandbox Code Playgroud)
要将图像的白色部分转换为透明:
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)
Run Code Online (Sandbox Code Playgroud)