首页 > 解决方案 > OpenCV画线不适用于透明图像

问题描述

我正在制作一个绘图程序,您可以稍后将更改保存并导出为图像。不透明图像选项可以完美运行,但透明选项不能。我现在拥有的代码是基于这篇文章的

每当我在透明选项中画一条线时,图像上什么都不会显示。它是完全透明的。

print("Transparent:", str(transparent))
    if not transparent:
        image = np.zeros((height, width, 3), np.uint8) # initialize image for saving preferences
        image[:] = backgroundColorBGR # change background color

        for drawing in drawings: # loop through each drawing
            cv2.line(image, drawing[0], drawing[1], drawing[2], thickness = drawing[3]) # create line that user drew
        cv2.imwrite("yourimage.png", image)
    else:
        
        image = np.zeros((height, width, 4), dtype = np.uint8) # 4 channels instead of 3, for transparent images

        for drawing in drawings: # loop through each drawing
            cv2.line(image, drawing[0], drawing[1], drawing[2], thickness = drawing[3])
        cv2.imwrite("yourimage.png", image)

标签: pythonopencvimage-processingtransparency

解决方案


感谢 Mark Setchell,我找到了一个可行的解决方案。在 in 的color参数中cv2.line(),传递一个元组,其中前三个值是 BGR 颜色。第四个值用于透明度/alpha。cv2.line(color=(0, 0, 200, 255)) # etc因此,如果您想在透明图像上绘图,您的代码应该看起来像。


推荐阅读