How could I make the discontinuous contour of an image consistant?

后端 未结 6 1260
孤街浪徒
孤街浪徒 2021-02-04 15:32

In the task, I got an discontinuous edge image, how could make it closed? in other word make the curve continuous. And the shape could be any kind, cause this the coutour shadow

6条回答
  •  清歌不尽
    2021-02-04 16:23

    Mark Setchell's answer is a fun way to learn new stuff along the way. My approach is rather simple and straight-forward.

    I got the following solution off the top of my head. It involves a simple blurring operation sandwiched between two morphological operations

    I have explained what I have done alongside the code:

    #---- I converted the image to gray scale and then performed inverted binary threshold on it. ----
    
    img = cv2.imread('leaf.jpg')
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray, 127, 255, 1)  
    

    #---- Next I performed morphological erosion for a rectangular structuring element of kernel size 7 ----
    
    kernel = np.ones((7, 7),np.uint8)
    erosion = cv2.morphologyEx(thresh, cv2.MORPH_ERODE, kernel, iterations = 2)
    cv2.imshow('erosion', erosion )
    

    #---- I then inverted this image and blurred it with a kernel size of 15. The reason for such a huge kernel is to obtain a smooth leaf edge ----
    
    ret, thresh1 = cv2.threshold(erosion, 127, 255, 1)
    blur = cv2.blur(thresh1, (15, 15))
    cv2.imshow('blur', blur)
    

    #---- I again performed another threshold on this image to get the central portion of the edge ----
    
    ret, thresh2 = cv2.threshold(blur, 145, 255, 0)
    
    #---- And then performed morphological erosion to thin the edge. For this I used an ellipse structuring element of kernel size 5 ----
    
    kernel1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
    final = cv2.morphologyEx(thresh2, cv2.MORPH_ERODE, kernel1, iterations = 2)
    cv2.imshow(final', final)
    

    Hope this helps :)

提交回复
热议问题