Reputation: 103
I can draw a line with OpenCV Python but I can't make the line transparent
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)
I changed the code but the line is still not transparent. I don't know why, could someone please help me to solve this problem?
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)
Upvotes: 6
Views: 10655
Reputation: 46610
One approach is to create a mask "overlay" image (copy of input image), draw a line onto this overlay image, and then perform the weighted addition of the two images using cv2.addWeighted()
to mimic an alpha channel. Here's an example:
Line with no transparency ->
Result with alpha=0.5
Result with alpha=0.25
This method to apply transparency could be generalized to work with any other drawing function. Here's an example with cv2.rectangle()
and cv2.circle()
using an alpha=0.5
transparency value.
No transparency ->
Result with alpha=0.5
Code
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()
Upvotes: 11