Extract external contour or silhouette of image in Python

后端 未结 3 1714
清歌不尽
清歌不尽 2020-12-31 16:51

I want to extract the silhouette of an image, and I\'m trying to do it using the contour function of MatplotLib. This is my code:

from PIL import Image
from          


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 17:06

    For those who want the OpenCV solution, here it is:

    ret,thresh = cv2.threshold(image,245,255,0)
    contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
    
    tam = 0
    
    for contorno in contours:
        if len(contorno) > tam:
            contornoGrande = contorno
            tam = len(contorno)
    
    cv2.drawContours(image,contornoGrande.astype('int'),-1,(0,255,0),2)
    
    cv2.imshow('My image',image)
    
    cv2.waitKey()
    cv2.destroyAllWindows()
    

    In this example, I only draw the biggest contour. Remember that 'image' must be a single-channel array.

    You should change the parameters of the threshold function, the findContours function and the drawContours function to get what you want.

    • threshold Documentation
    • findContours Documentation
    • drawContours Documentation

    I do the conversion to 'int' in the drawContours function because there is a bug in the Open CV 2.4.3 version, and if you don't do this conversion, the program breaks. This is the bug.

提交回复
热议问题