Add transparency to the whole image except one element

Viewed 91

i had added transparency to the whole image, but later i also added rectangle and aligned it by center. How to delete transparency in rectangle area?

Image

Code:

import cv2

image = cv2.imread('test.jpeg')
overlay = image.copy()
print(image.shape)




x, y, w, h = 0, 0, image.shape[1], image.shape[0]  # Rectangle parameters
cv2.rectangle(overlay, (x, y), (x+w, y+h), (500, 500, 500), -1)  # A filled rectangle

Y, X = overlay.shape[0], overlay.shape[1]
print(X, Y)
cv2.rectangle(overlay, pt1=((X // 2) - 150,(Y // 2) - 150), pt2=((X // 2) + 150,(Y // 2) + 150), color=(0,0,0), thickness=5)



alpha = 0.5  # Transparency factor.

# Following line overlays transparent rectangle over the image
image_new = cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0)
cv2.imshow('frame', image_new)
cv2.waitKey(0) # waits until a key is pressed
cv2.destroyAllWindows()
1 Answers

You can simply index with the rectangle to copy the original pixels values into the new image:

import cv2

image = cv2.imread('test.jpeg')
overlay = image.copy()
print(image.shape)




x, y, w, h = 0, 0, image.shape[1], image.shape[0]  # Rectangle parameters
cv2.rectangle(overlay, (x, y), (x+w, y+h), (500, 500, 500), -1)  # A filled rectangle

Y, X = overlay.shape[0], overlay.shape[1]
# HERE: Save your points
pt1=((X // 2) - 150,(Y // 2) - 150)
pt2=((X // 2) + 150,(Y // 2) + 150)
cv2.rectangle(overlay, pt1=pt1, pt2=pt2, color=(0,0,0), thickness=5)


alpha = 0.5  # Transparency factor.

# Following line overlays transparent rectangle over the image
image_new = cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0)
# HERE: Put the pixels inside the rectangle back
image_new[pt1[1]:pt2[1], pt1[0]:pt2[0]] = image[pt1[1]:pt2[1], pt1[0]:pt2[0]]
cv2.imshow('frame', image_new)
cv2.waitKey(0) # waits until a key is pressed
cv2.destroyAllWindows()
Related