python 如何使用蒙版去除背景

how to use mask to remove the background in python

我想使用遮罩图像去除背景。现在,我已经得到mask image.I 尝试让mask 值为0 的原始图像的背景值变为0。但结果很糟糕。我怎么解决这个问题。谢谢

from skimage import io
import numpy as np
img = io.imread("GT06.jpg")
mask = io.imread("GT03.png")
mask2 = np.where((mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]
io.imshow(img)
io.show()

GT06.jpg

GT03.png

这导致:

我想得到这样的前景:

问题是你的蒙版不是纯黑和白的,即所有 0 或 255 将你的蒙版两代更改为:

mask2 = np.where((mask<200),0,1).astype('uint8')

结果:

你可以玩掩码或阈值数字 - 我用的是 200。

在 Python 中,您可以使用 OpenCV。如果您的系统中没有,这里是 instructions to install OpenCV in Python。我想你可以对其他库做同样的事情,过程是一样的,诀窍是反转蒙版并将其应用于某些背景,你将拥有蒙版图像和蒙版背景,然后将两者结合起来。

image1 是用原始蒙版遮盖的图像,image2 是用倒置蒙版遮盖的背景图像,image3 是组合图像。 重要image1、image2 和 image3 的尺寸和类型必须相同。蒙版必须是灰度的。

import cv2
import numpy as np

# opencv loads the image in BGR, convert it to RGB
img = cv2.cvtColor(cv2.imread('E:\FOTOS\opencv\iT5q1.png'),
                   cv2.COLOR_BGR2RGB)

# load mask and make sure is black&white
_, mask = cv2.threshold(cv2.imread('E:\FOTOS\opencv\SH9jL.png', 0),
                        0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# load background (could be an image too)
bk = np.full(img.shape, 255, dtype=np.uint8)  # white bk, same size and type of image
bk = cv2.rectangle(bk, (0, 0), (int(img.shape[1] / 2), int(img.shape[0] / 2)), 0, -1)  # rectangles
bk = cv2.rectangle(bk, (int(img.shape[1] / 2), int(img.shape[0] / 2)), (img.shape[1], img.shape[0]), 0, -1)

# get masked foreground
fg_masked = cv2.bitwise_and(img, img, mask=mask)

# get masked background, mask must be inverted 
mask = cv2.bitwise_not(mask)
bk_masked = cv2.bitwise_and(bk, bk, mask=mask)

# combine masked foreground and masked background 
final = cv2.bitwise_or(fg_masked, bk_masked)
mask = cv2.bitwise_not(mask)  # revert mask to original