通过 OpenCV 应用分割掩码

时间:2021-02-08 03:48:38

标签: python numpy opencv image-segmentation

我目前有一个 np.ndarray 位掩码格式,其中掩码的像素值为 1,没有掩码的像素值为 0。

我想将其“应用”到另一个 np.ndarray 图像(3 个通道:RGB),其中蒙版存在的区域稍微突出显示为突出显示的颜色。例如,如果我希望用绿色表示人体面具的区域,我会想要如下所示的内容。我想知道如何使用 opencvnumpy 做到这一点。

enter image description here

1 个答案:

答案 0 :(得分:2)

让我们试试cv2.addWeighted

# sample data
img = np.full((10,10,3), 128, np.uint8)

# sample mask
mask = np.zeros((10,10), np.uint8)
mask[3:6, 3:6] = 1

# color to fill
color = np.array([0,255,0], dtype='uint8')

# equal color where mask, else image
# this would paint your object silhouette entirely with `color`
masked_img = np.where(mask[...,None], color, img)

# use `addWeighted` to blend the two images
# the object will be tinted toward `color`
out = cv2.addWeighted(img, 0.8, masked_img, 0.2,0)

输出:

enter image description here