在OpenCV python中将白色像素转换为黑色

时间:2018-07-15 09:45:20

标签: python opencv

我正在尝试使用python OpenCV将输入图像的白色背景转换为黑色,但是所有白色像素并未完全转换为黑色。我已经附上了输入和输出图像。

输入图像:

Input Image in the window

输出图像:

Output Image in the Window

我使用以下代码进行转换:

img[np.where((img==[255,255,255]).all(axis=2))] = [0,0,0];

我该怎么办?

2 个答案:

答案 0 :(得分:3)

我知道这已经得到回答。我为您提供了一个编码的python解决方案。

首先我发现this thread解释了如何去除白色像素。

结果:

result

另一个测试img:

修改 这是一种更好,更短的方法。 @ZdaR对循环遍历图像矩阵发表评论后,我进行了调查。

[更新代码]

img = cv2.imread("Images/test.pnt")

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)

img[thresh == 255] = 0

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
erosion = cv2.erode(img, kernel, iterations = 1)

cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow("image", erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()

Source

[旧代码]

img = cv2.imread("Images/test.png")

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)

white_px = np.asarray([255, 255, 255])
black_px = np.asarray([0, 0, 0])

(row, col) = thresh.shape
img_array = np.array(img)

for r in range(row):
    for c in range(col):
        px = thresh[r][c]
        if all(px == white_px):
            img_array[r][c] = black_px

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
erosion = cv2.erode(img_array, kernel, iterations = 1)

cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow("image", erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()

使用的其他来源: OpenCV Morphological Transformations

答案 1 :(得分:0)

我认为图像中并非所有的“白色”像素都是[255,255,255]。相反,设定一个阈值。尝试[220,220,220]及更高版本,并将其转换为[0,0,0]。