【问题标题】:Imitating Photoshop's layer mask模仿Photoshop的图层蒙版
【发布时间】:2019-11-25 23:13:21
【问题描述】:

我正在尝试使用像素的 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)

我想这可能无关紧要,因为图层掩码可能不需要阈值。

【问题讨论】:

  • 请澄清您所说的“使 alpha 成比例”是什么意思。当您正确二值化时,您可以摆脱褪色区域。你想发生什么。请举个例子。

标签: python opencv opencv3.0


【解决方案1】:

我不确定这是否是您想要的,但您可以通过从图像中减去蒙版的值来获得比例效果。这意味着您必须反转蒙版,因此您要删除的 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    相关资源
    最近更新 更多