2017-06-16 395 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值...謝謝 –