gpt4 book ai didi

python - 如何使用 OpenCV 平滑并变薄这些非常粗糙的图像?

转载 作者:行者123 更新时间:2023-11-30 21:52:40 25 4
gpt4 key购买 nike

我有一些单个数字的黑白图像。我正在使用在 MNIST 上训练的 NN 模型来对它们进行分类。然而,与 MNIST 数据集相比,这些数字过于粗糙和厚重。例如:

enter image description here

TLDR:我需要使用 OpenCV 平滑图像并可能使整体形状更薄。

最佳答案

您可以在 Python/OpenCV 中使用形态学闭合、开放和侵 eclipse (以及可选的骨架化和扩张)组合,如下所示:

输入:

enter image description here

import cv2
import numpy as np
from skimage.morphology import skeletonize

# load image
img = cv2.imread("5.png")

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold image
thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY)[1]

# apply morphology close
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# apply morphology open
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# apply morphology erode
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (21,21))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_ERODE, kernel)

# write result to disk
cv2.imwrite("5_thinned.png", thresh)

# skeletonize image and dilate
skeleton = cv2.threshold(thresh,0,1,cv2.THRESH_BINARY)[1]
skeleton = (255*skeletonize(skeleton)).astype(np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15,15))
skeleton_dilated = cv2.morphologyEx(skeleton, cv2.MORPH_DILATE, kernel)

# write result to disk
cv2.imwrite("5_skeleton_dilated.png", skeleton_dilated)

cv2.imshow("IMAGE", img)
cv2.imshow("RESULT1", thresh)
cv2.imshow("RESULT2", skeleton_dilated)
cv2.waitKey(0)
cv2.destroyAllWindows()


结果1(关闭、打开、侵 eclipse ):

enter image description here

结果2(关闭、打开、侵 eclipse 、骨架化、扩张):

enter image description here

关于python - 如何使用 OpenCV 平滑并变薄这些非常粗糙的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59850410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com