Search code examples
pythonopencvgoogle-colaboratory

Drawing a line on PNG image OpenCV2 Python


How to add colored line on rgba (.png) image using opencv?

I tried following but line drawn is transparent.

import cv2
image = cv2.imread("/content/drive/My Drive/universe-fg.png",-1)
from google.colab.patches import cv2_imshow

image2 = cv2.resize(image,(150,150))
cv2.line(image2, (20, 30), (100, 80), (255, 255, 0), 10)
cv2_imshow(image2)

The result:

Output Image

using cv2 version 4.1.2


Solution

  • Your mistake is that you need to specify an opaque alpha value in your line color. So use (255, 255, 0, 255) rather than (255, 255, 0). The latter assumes a value of 0 (transparent) when not specified.

    So here is how to do that in Python/OpenCV.

    Input:

    enter image description here

    import cv2
    import numpy as np
    
    # load transparent image
    img = cv2.imread('blue_circle.png', cv2.IMREAD_UNCHANGED)
    hh, ww = img.shape[:2]
    
    # draw colored line as opaque
    result = img.copy()
    cv2.line(result, (20, 30), (100, 80), (255, 255, 0, 255), 10)
    
    # save result
    cv2.imwrite('blue_circle_line.png', result)
    
    # display result, though it won't show transparency
    cv2.imshow("IMAGE", img)
    cv2.imshow("RESULT", result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    enter image description here