我正在尝试绘制使用findContours找到的轮廓。
如果我这样绘制,我会得到一个黑色背景,上面绘制了轮廓。
out = np.zeros_like(someimage)
cv2.drawContours(out, contours, -1, 255, 1)
cv2.imwrite('contours.png',out)
如果我这样绘制,我会得到一个完全透明的图像,没有绘制轮廓。
out = np.zeros((55, 55, 4), dtype=np.uint8)
cv2.drawContours(out, contours, -1, 255, 1)
cv2.imwrite('contours.png',out)
如何制作尺寸(55,55)的图像并在其上绘制轮廓,同时保持透明背景?
谢谢
答案 0 :(得分:3)
要在OpenCV中处理透明图像,您需要使用BGR之后的第四个通道,即alpha控件。因此,与其创建一个三通道图像,不如创建一个包含四个通道的图像,并且在绘制时还要确保将第四通道分配给255。
mask = np.zeros((55, 55, 4), dtype=np.uint8)
cv2.drawContours(mask, cnts, -1, (255, 255, 255, 255), 1) #change first three channels to any color you want.
cv2.imwrite('res.png', mask)
输入要绘制轮廓的图像。
结果
答案 1 :(得分:2)
在Python / OpenCV中,将黑白图像用作Alpha通道,并将其用于3通道BGR图像。
cntr_img = np.zeros((55, 55, 4), dtype=np.uint8)
cv2.drawContours(cntr_img, contours, -1, 255, 1)
out = cv2.cvtColor(cntr_img, cv2.COLOR_GRAY2BGRA)
out[:,:,3] = cntr_img
cv2.imwrite('contours.png',out)
答案 2 :(得分:2)