【问题标题】:How to add transparency to a line with OpenCV python?如何使用 OpenCV python 为一行添加透明度?
【发布时间】:2023-03-03 09:57:01
【问题描述】:

我可以用 OpenCV Python 画一条线,但我不能使这条线透明

def draw_from_pitch_to_image(image, reverse_output_points):
    for i in range(0, len(reverse_output_points), 2):
       x1, y1 = reverse_output_points[i]
       x2, y2 = reverse_output_points[i + 1]

       x1 = int(x1)
       y1 = int(y1)
       x2 = int(x2)
       y2 = int(y2)

       color = [255, 0, 0] if i < 1 else [0, 0, 255]
       cv2.line(image, (x1, y1), (x2, y2), color, 2)

我更改了代码,但该行仍然不透明。我不知道为什么,有人可以帮我解决这个问题吗?

  def draw_from_pitch_to_image(image, reverse_output_points):
      for i in range(0, len(reverse_output_points), 2):
       x1, y1 = reverse_output_points[i]
       x2, y2 = reverse_output_points[i + 1]

       alpha = 0.4  # Transparency factor.
       overlay = image.copy()
       x1 = int(x1)
       y1 = int(y1)
       x2 = int(x2)
       y2 = int(y2)

       color = [255, 0, 0] if i < 1 else [0, 0, 255]
       cv2.line(overlay, (x1, y1), (x2, y2), color, 2)
       cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output)

【问题讨论】:

    标签: python image opencv image-processing drawing


    【解决方案1】:

    一种方法是创建一个蒙版“叠加”图像(输入图像的副本),在此叠加图像上画一条线,然后使用cv2.addWeighted() 对两个图像执行加权相加,以模拟 Alpha 通道。这是一个例子:

    不透明的线条-&gt; 结果为alpha=0.5

    结果为@​​987654337@


    这种应用透明度的方法可以推广到与任何其他绘图功能一起使用。这是一个使用 alpha=0.5 透明度值的 cv2.rectangle()cv2.circle() 示例。

    不透明-&gt; 结果为alpha=0.5

    代码

    import cv2
    
    # Load image and create a "overlay" image (copy of input image)
    image = cv2.imread('2.jpg')
    overlay = image.copy()
    original = image.copy() # To show no transparency
    
    # Test coordinates to draw a line
    x, y, w, h = 108, 107, 193, 204
    
    # Draw line on overlay and original input image to show difference
    cv2.line(overlay, (x, y), (x + w, x + h), (36, 255, 12), 6)
    cv2.line(original, (x, y), (x + w, x + h), (36, 255, 12), 6)
    
    # Could also work with any other drawing function
    # cv2.rectangle(overlay, (x, y), (x + w, y + h), (36, 255, 12), -1)
    # cv2.rectangle(original, (x, y), (x + w, y + h), (36, 255, 12), -1)
    # cv2.circle(overlay, (x, y), 80, (36, 255, 12), -1)
    # cv2.circle(original, (x, y), 80, (36, 255, 12), -1)
    
    # Transparency value
    alpha = 0.50
    
    # Perform weighted addition of the input image and the overlay
    result = cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0)
    
    cv2.imshow('result', result)
    cv2.imshow('original', original)
    cv2.waitKey()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 2016-06-03
      • 2012-12-31
      • 2022-01-25
      • 2018-05-27
      • 1970-01-01
      • 2017-05-21
      相关资源
      最近更新 更多