python中如何使用mask删除背景

2024-10-01 15:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用蒙版图像去除背景。现在,我已经得到了蒙版图像,我试着让原始图像的背景值变为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版

enter image description here

GT03.png

enter image description here

这将导致: enter image description here

我想得到这样的前景:

enter image description here


Tags: fromio图像importimgpngnpmask
2条回答

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

image1是用原始遮罩遮住的图像,image2是用倒置遮罩遮住的背景图像,image3是组合图像。重要image1、image2和image3的大小和类型必须相同。遮罩必须是灰度级的。foreground and background masked then combined

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

问题是你的面具不是纯黑白的,也就是说,所有的0或255都会把你的面具改成:

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

结果:

Remasked

你可以玩面具或者阈值-我用了200。在

相关问题 更多 >

    热门问题