为除一个元素外的整个图像添加透明度

Add transparency to the whole image except one element

我已经为整个图像添加了透明度,但后来我还添加了矩形并居中对齐。如何删除矩形区域的透明度?

代码:

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()

您可以简单地用矩形索引将原始像素值复制到新图像中:

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()