OpenCV’s drawing functions for geometric primitives like lines and circles regrettably do not support alpha-transparency. As workaround, the documentation remarks that one should paint to a separate buffer and then blend this buffer with the main image. But how does this work in practise?
A convenient way to blend images is via the
(there is an explanation of image overlays on AI Shack that
addWeighted by hand). To get standard transparency,
simply make sure the weights add up to 1. Here’s the code I used to create
the image above:
#!/usr/bin/env python import cv2 img = cv2.imread('lena.png') # (1) create a copy of the original: overlay = img.copy() # (2) draw shapes: cv2.circle(overlay, (133, 132), 12, (0, 255, 0), -1) cv2.circle(overlay, (166, 132), 12, (0, 255, 0), -1) # (3) blend with the original: opacity = 0.4 cv2.addWeighted(overlay, opacity, img, 1 - opacity, 0, img) # display result (press 'q' to quit): cv2.namedWindow('Transparency') cv2.imshow('Transparency', img) while (cv2.waitKey() & 0xff) != ord('q'): pass cv2.destroyAllWindows()
What’s important about this method is to start the overlay buffer with a copy of the original, not with a blank image. With this neat little trick, all points that are not affected by the drawing operations will retain their color. Otherwise, they are blended with the background color of the overlay buffer.