2016-01-09 94 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