我想拍摄一张图像,并仅将其叠加为轮廓,而无需背景/填充。我有一个图像是 PNG 格式的轮廓,它的背景以及轮廓内的内容都被删除了,所以当打开时,除了轮廓外,所有内容都是透明的,类似于此图像:
但是,当我打开图像并尝试在 OpenCV 中对其进行叠加时,轮廓内的背景和区域显示为全白,显示图像尺寸的完整矩形并遮挡了背景图像。
但是,我想要做的是以下内容,其中只有轮廓覆盖在背景图像上,如下所示:
如果你能帮助我改变轮廓的颜色,那就加分。
我不想处理任何与 alpha 的混合,因为我需要背景完整显示,并且希望轮廓非常清晰。
答案 0 :(得分:1)
在这种特殊情况下,您的图像有一些可以使用的 Alpha 通道。使用 Boolean array indexing,您可以访问 alpha 通道中的所有值 255
。剩下要做的是“背景”图像中的 setting up some region of interest (ROI) w.r.t.某个位置,在该 ROI 中,您再次使用布尔数组索引将所有像素设置为某种颜色,即红色。
这是一些代码:
import cv2
# Open overlay image, and its dimensions
overlay_img = cv2.imread('1W7HZ.png', cv2.IMREAD_UNCHANGED)
h, w = overlay_img.shape[:2]
# In this special case, take the alpha channel of the overlay image, and
# check for value 255; idx is a Boolean array
idx = overlay_img[:, :, 3] == 255
# Open image to work on
img = cv2.imread('path/to/your/image.jpg')
# Position for overlay image
top, left = (50, 50)
# Access region of interest with overlay image's dimensions at position
# img[top:top+h, left:left+w] and there, use Boolean array indexing
# to set the color to red (for example)
img[top:top+h, left:left+w, :][idx] = (0, 0, 255)
# Save image
cv2.imwrite('output.png', img)
这是一些随机“背景”图像的输出:
对于一般情况,即没有合适的 Alpha 通道,您可以设置叠加图像的阈值,以便为布尔数组索引设置合适的掩码。
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.5
OpenCV: 4.5.1
----------------------------------------