我试图从照片中删除灰色背景,并用白色替换它
到目前为止我有这个代码:
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
Run Code Online (Sandbox Code Playgroud)
问题是图像现在有黑色背景,因为我掩盖了灰色.如何用白色像素替换空像素?

您可以使用蒙版索引数组,并仅将蒙版的白色部分指定为白色:
coloured = resized.copy()
coloured[mask == 255] = (255, 255, 255)
Run Code Online (Sandbox Code Playgroud)
我真的建议你坚持使用 OpenCV,它优化得很好。诀窍是反转蒙版并将其应用于某些背景,您将拥有蒙版图像和蒙版背景,然后将两者结合起来。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\\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
Run Code Online (Sandbox Code Playgroud)
小智 0
我不使用 bitwise_not,而是使用
resized.setTo([255, 255, 255], mask)
Run Code Online (Sandbox Code Playgroud)
在此之前,我还会腐蚀和膨胀蒙版,以消除蒙版中作为您想要保留的图像一部分的规格。 http://docs.opencv.org/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html