我正在尝试使用Python OpenCV将输入图像的白色背景转换为黑色。但是,所有白色像素并没有完全变成黑色。我已经附上了输入和输出图像。
输入图像:
输出图像:
我使用了以下代码进行转换:
输入图像:
![Input Image in the window](https://istack.dev59.com/MgiNL.webp)
![Output Image in the Window](https://istack.dev59.com/aJOat.webp)
img[np.where((img==[255,255,255]).all(axis=2))] = [0,0,0];
我该怎么办?
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()
[Old Code]
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形态学变换
我认为图像中并非所有的“白色”像素都是 [255,255,255]。相反,应该设置一个阈值。尝试将 [220,220,220] 及以上的像素转换为 [0,0,0]。