Search code examples
pythonopencvimage-processingcomputer-visionimage-thresholding

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


In the below image, I need to extract only the straight and curved lines and eliminate all other extra boxes as shown below. I am a newbie to OpenCV. Can someone help me with this?

Input Image :

Expected Output Image:


Solution

  • Not perfect but you can start thinking by doing operations in this sequence.

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

    enter image description here