我知道这已经得到了回答。我有一个编码的 Python 解决方案给你。
首先我找到this thread 解释如何去除白色像素。
结果:
另一个测试图像:
编辑
这是一种更好更短的方法。在@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