2017-06-16 624 views
0

我想制作一个透明图像并在其上绘制,然后在基础图像上添加加权。在opencv python中创建透明图像

如何在openCV python中用width和hight初始化完全透明的图像?

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

+1

这是非常宽泛的。只需使用一个新图像(例如白色),绘制它并以某种方式标记您正在绘制的位置(如果您不绘制白色,则不需要,因为您可以检查所有像素!=白色)。然后,当您合并这两幅图像时,所有未绘制的权重都为零。 (我不是opencv用户,我对addWeighted的工作原理做了一些假设)。 – sascha

+1

OpenCV支持alpha通道,但不支持渲染它们。 – Micka

回答

1

如果你想画几个“层”,然后将图纸叠加在一起,那么如何来创建这个:

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) 

enter image description here

2

要创建透明图像,您需要一个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) 
+0

谢谢,我试图在你提出的图像上画一些东西,但它不起作用。图像是真正创建的,但我无法在其上绘制一个简单的矩形。操作完成,但保存图像时,无法看到矩形。 –

+2

其实它解决了当我添加矩形与4个通道,与阿尔法255值...谢谢 –