如何在 python 中使用 opencv 消除小的不规则形状的正方形并仅保留图像中的直线和曲线?
How to eliminate small irregular shaped squares and to retain only lines and curves in an image using opencv in python?
在下图中,我只需要提取直线和曲线,并消除所有其他多余的框,如下所示。我是 OpenCV 的新手。有人可以帮我解决这个问题吗?
输入图片:
预期输出图像:
不完美,但你可以按照这个顺序操作开始思考。
import cv2
import numpy as np
from skimage.morphology import skeletonize
def get_skeleton_iamge(threshold_image):
skeleton = skeletonize(threshold_image / 255)
skeleton = skeleton.astype(np.uint8)
skeleton *= 255
return skeleton
image = cv2.imread("image.png")
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, threshold_image = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
cv2.imshow("threshold_image", threshold_image)
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
dilate_image = cv2.dilate(threshold_image, kernel=kernel, iterations=2)
erode_image = cv2.erode(dilate_image, kernel=kernel, iterations=1)
cv2.imshow("erode_image", erode_image)
# Sclect max contour only
contours, hierarchy = cv2.findContours(erode_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
max_cnt = max(contours, key=lambda x: cv2.arcLength(x, closed=True))
max_cnt_image = np.zeros_like(erode_image)
cv2.drawContours(max_cnt_image, [max_cnt], -1, 255, -1)
cv2.imshow("max_cnt_image", max_cnt_image)
skeleton_iamge = get_skeleton_iamge(max_cnt_image)
cv2.imshow("skeleton_iamge", skeleton_iamge)
cv2.waitKey(0)
cv2.destroyAllWindows()
在下图中,我只需要提取直线和曲线,并消除所有其他多余的框,如下所示。我是 OpenCV 的新手。有人可以帮我解决这个问题吗?
输入图片:
预期输出图像:
不完美,但你可以按照这个顺序操作开始思考。
import cv2
import numpy as np
from skimage.morphology import skeletonize
def get_skeleton_iamge(threshold_image):
skeleton = skeletonize(threshold_image / 255)
skeleton = skeleton.astype(np.uint8)
skeleton *= 255
return skeleton
image = cv2.imread("image.png")
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, threshold_image = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
cv2.imshow("threshold_image", threshold_image)
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
dilate_image = cv2.dilate(threshold_image, kernel=kernel, iterations=2)
erode_image = cv2.erode(dilate_image, kernel=kernel, iterations=1)
cv2.imshow("erode_image", erode_image)
# Sclect max contour only
contours, hierarchy = cv2.findContours(erode_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
max_cnt = max(contours, key=lambda x: cv2.arcLength(x, closed=True))
max_cnt_image = np.zeros_like(erode_image)
cv2.drawContours(max_cnt_image, [max_cnt], -1, 255, -1)
cv2.imshow("max_cnt_image", max_cnt_image)
skeleton_iamge = get_skeleton_iamge(max_cnt_image)
cv2.imshow("skeleton_iamge", skeleton_iamge)
cv2.waitKey(0)
cv2.destroyAllWindows()