【问题标题】:Create transparent image in opencv python在opencv python中创建透明图像
【发布时间】:2017-06-16 17:45:34
【问题描述】:

我正在尝试制作透明图像并在其上绘制,然后在基础图像上添加加权。

如何在 openCV python 中初始化具有宽度和高度的全透明图像?

编辑:我想制作像 Photoshop 中的效果,堆叠层,所有堆叠的层最初都是透明的,并且在完全透明的层上执行绘图。最后,我将合并所有图层以获得最终图像

【问题讨论】:

  • 这个范围很广。只需使用新图像(例如白色),在其上绘制并以某种方式标记您正在绘制的位置(如果您不绘制白色则不需要,因为您可以检查所有像素!= 白色)。然后,当您组合这两个图像时,所有未绘制的权重都为零。 (我不是 opencv 用户,我对 addWeighted 的工作原理做了一些假设)。
  • OpenCV 支持 alpha 通道但不支持渲染它们。

标签: python opencv image-processing


【解决方案1】:

要创建透明图像,您需要一个 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)

【讨论】:

  • 谢谢您,我已经尝试在您提出的图像上画一些东西,但它不起作用。图像是真正创建的,但我无法在其上绘制一个简单的矩形。操作完成,但是保存图片时看不到矩形。
  • 实际上,当我添加具有 4 个通道、alpha 255 值的矩形时,它解决了...谢谢
  • @MichaelPresečan 您能否编辑答案并添加矩形,以便示例更广泛。
  • @MichaelPresečan 请编辑答案并为其他人添加矩形
【解决方案2】:

将图像的白色部分转换为透明:

import cv2
import numpy as np

img = cv2.imread("image.png", cv2.IMREAD_UNCHANGED)
img[np.where(np.all(img[..., :3] == 255, -1))] = 0
cv2.imwrite("transparent.png", img)

【讨论】:

    【解决方案3】:

    如果你想在几个“层”上绘制,然后将这些图形堆叠在一起,那么这样怎么样:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 2014-06-01
      • 1970-01-01
      • 2017-05-21
      • 2018-10-11
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多