2016-01-09 96 views
2

我想通过使用蒙版图像去除背景。现在,我已经获得了蒙版图像。我试图让原始图像的背景值在0的地方变为0,但蒙版的结果非常糟糕。我怎么解决这个问题。谢谢如何使用蒙版去除Python中的背景

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

+0

它可能是一个想法,显示你的结果是什么样的。 –

回答

2

的问题是,你的面具是不是纯黑色和白色,即所有0或255改变了你掩盖二代到:在

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

结果:

Remasked

你既可以用面具或阈值数玩 - 我用200

+0

非常感谢。我尝试过这个。但结果不好。我想完全提取前景。 – user3960019

+0

然后你需要一个更好的面具。 –

0

在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