OpenCV Python - 设置背景颜色

7
我将尝试从一张照片中去除灰色背景,并用白色背景替换它。
目前我有以下代码:
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

5个回答

9
您可以使用掩码来索引数组,并将掩码中的白色部分赋值给白色:
coloured = resized.copy()
coloured[mask == 255] = (255, 255, 255)

Screenshot


1
你能否写一个完整的程序? - Govinda Raju

8

我强烈建议您坚持使用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

2

首先,你需要获取背景。为此,必须使用掩膜图像从原始图像中减去。然后将黑色背景更改为白色(或任何颜色)。最后再将掩膜图像与图像相加。

请参考这里


0

2
我遇到了错误 AttributeError: 'numpy.ndarray' 对象没有属性 'setTo'。这对你有什么意义吗?谢谢。 - user404345

0
首先将图像转换为灰度,然后使用cv2.threshold进行阈值处理,最后使用numpy掩膜...
ret, thresh = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 220, 255, cv2.THRESH_BINARY)
img[thresh == 255] = 255

如果需要黑色背景,请将RHS设置为零,而不是255。

您好,实际上它正在降低 DPI,我该如何保持相同的 DPI,例如 150? - Govinda Raju

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接