2015-04-22 93 views
1

我想從照片刪除灰色背景和一個白色的OpenCV的Python的 - 設置背景顏色

取代它到目前爲止,我有這樣的代碼:

image = cv2.imread(args["image"]) 
r = 150.0/image.shape[1] 
dim = (150, int(image.shape[0] * r)) 
resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA) 
lower_white = np.array([220, 220, 220], dtype=np.uint8) 
upper_white = np.array([255, 255, 255], dtype=np.uint8) 
mask = cv2.inRange(resized, lower_white, upper_white) # could also use threshold 
res = cv2.bitwise_not(resized, resized, mask) 
cv2.imshow('res', res) # gives black background 

的問題是,圖像現在有一個黑色的背景,因爲我已經掩蓋了灰色。我怎樣才能用白色的替換空像素?

Before After

回答

4

您可以使用面膜索引數組,並指定只是面具的白色部分爲白色:

coloured = resized.copy() 
coloured[mask == 255] = (255, 255, 255) 

Screenshot

1

我真的建議你堅持用OpenCV的,它是很好的優化。訣竅是反轉蒙版並將其應用於某些背景,您將獲得蒙版圖像和蒙版背景,然後將兩者結合。 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\\zAJLd.jpg'), 
        cv2.COLOR_BGR2RGB) 
lower_white = np.array([220, 220, 220], dtype=np.uint8) 
upper_white = np.array([255, 255, 255], dtype=np.uint8) 
mask = cv2.inRange(img, lower_white, upper_white) # could also use threshold 
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))) # "erase" the small white points in the resulting mask 
mask = cv2.bitwise_not(mask) # invert mask 

# load background (could be an image too) 
bk = np.full(img.shape, 255, dtype=np.uint8) # white bk 

# 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