绘制OpenCV轮廓并将其另存为透明图像

时间:2020-08-02 23:33:47

标签: python numpy opencv

我正在尝试绘制使用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)的图像并在其上绘制轮廓,同时保持透明背景?

谢谢

3 个答案:

答案 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)

INput

输入要绘制轮廓的图像。

result

结果

答案 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)

这在Python / OpenCV中对我有效。由于没有轮廓图像,我在黑色背景上使用白色斑点进行输入。轮廓图像必须是灰度的。

输入:

enter image description here

(1,1)

透明结果(由于透明背景为白色,请下载以查看):

enter image description here

相关问题