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

Gau*_*ant 2 python opencv

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

输入图像:

在窗口中输入图像

输出图像:

在窗口中输出图像

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

img[np.where((img==[255,255,255]).all(axis=2))] = [0,0,0];
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

Ben*_*iko 6

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

首先,我发现这个线程解释了如何删除白色像素。

结果:

结果

另一个测试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()
Run Code Online (Sandbox Code Playgroud)

来源

[旧代码]

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()
Run Code Online (Sandbox Code Playgroud)

使用的其他来源: OpenCV 形态转换