今天忽然想做摳圖和圖形繪製,那這裏就涉及到一個透明底的問題
OpenCV是很強大的,但是網上大多教程並沒有講清楚 alpha 通道的參數怎麼設置
首先我們來看最簡單的非 alpha 通道代碼:
import numpy as np
import cv2
# 初始化一塊400*400的畫布,注意這裏的畫布是三通道的,也就是彩色圖像
image = np.zeros((400, 400, 3), dtype="uint8")
# 畫一條綠線
green = (0, 255, 0)
# 起點(0, 0)至終點(400, 400),顏色綠色,線寬默認爲1個像素
cv2.line(image, (0, 0), (400, 400), green)
cv2.imwrite("image.png", image)
效果如下:
然後我們加上 alpha 通道
import numpy as np
import cv2
# 初始化一塊400*400的畫布,注意這裏的畫布是4通道的,多了 alpha 通道
image = np.zeros((400, 400, 4), dtype="uint8")
# 畫一條綠線,這裏第4個就是 alpha 通道的值,0 爲完全透明,255 爲不透明
green = (0, 255, 0, 255)
green_light = (0, 255, 0, 100)
# 起點(0, 0)至終點(400, 400),顏色綠色,線寬設置爲5看得清楚些
cv2.line(image, (0, 0), (400, 400), green,5)
cv2.line(image, (200, 0), (200, 400), green_light,5)
cv2.imwrite("image_light.png", image)
效果如下: