我正在尝试使用蒙版去除图像的背景,其中像素的alpha值与黑色强度成比例。例如,给定以下输入图像和蒙版,结果将包含“淡入淡出”区域:
结果:
注意淡入淡出的区域。基本上我是在模仿Photoshop中的图层蒙版功能。
我可以使用二进制阈值将遮罩转换为alpha,但我想知道如何使alpha成比例。二进制阈值的代码如下:
mask = cv2.imread(mask_path, 0)
mask2 = np.where(mask<50, 0, 1).astype('uint8')
img = img * mask2[:, :, np.newaxis]
_, alpha = cv2.threshold(mask2, 0, 255, cv2.THRESH_BINARY)
png = np.dstack((img, alpha))
cv2.imwrite(dest_path, png)
我认为这可能是无关紧要的,因为层掩码可能不需要阈值。
发布于 2019-07-17 13:10:09
我不确定这是否是你想要的,但你可以通过从图像中减去蒙版的值来获得比例效果。这意味着你必须反转蒙版,所以你想要移除的alpha的数量是白色的。对于subtract()
,输入数组需要具有相同的大小,因此将反转的蒙版转换为3个颜色通道。如果蒙版的大小不等于背景图像,则必须首先创建子图像。
import cv2
import numpy as np
# load background image
img = cv2.imread('grass.jpg')
# load alpha mask as grayscale
mask = cv2.imread('a_mask.jpg',0)
# invert mask and convert to 3 color channels
mask = cv2.bitwise_not(mask)
fullmask = cv2.cvtColor(mask,cv2.COLOR_GRAY2BGR)
# create a subimage with the size of the mask
xOffset = 30
yOffset = 30
height, width = mask.shape[:2]
subimg = img[yOffset:yOffset+height,xOffset:xOffset+width]
#subtract mask values from subimage
res = cv2.subtract(subimg,fullmask)
# put subimage back in background
img[yOffset:yOffset+height,xOffset:xOffset+width] = res
#display result
cv2.imshow('Result',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
https://stackoverflow.com/questions/57070430
复制相似问题