簡體   English   中英

如何使用 python 中的 opencv 消除小的不規則形狀正方形並僅保留圖像中的線條和曲線?

[英]How to eliminate small irregular shaped squares and to retain only lines and curves in an image using opencv in python?

在下圖中,我只需要提取直線和曲線並消除所有其他多余的框,如下所示。 我是 OpenCV 的新手。 有人可以幫我弄這個嗎?

輸入圖像:

預期 Output 圖像:

不完美,但您可以通過按此順序執行操作來開始思考。

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()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM