Get area within contours Opencv Python?

前端 未结 2 1379
挽巷
挽巷 2020-12-24 03:13

I have used an adaptive thresholding technique to create a picture like the one below:

\"enter

2条回答
  •  失恋的感觉
    2020-12-24 03:57

    A simple approach would be to close the holes in the foreground to form a single contour with cv2.morphologyEx() and cv2.MORPH_CLOSE

    Now that the external contour is filled, we can find the outer contour with cv2.findContours() and use cv2.fillPoly() to fill in all pixels with white

    import cv2
    
    # Load in image, convert to grayscale, and threshold
    image = cv2.imread('1.png')
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    
    # Close contour
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7,7))
    close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=1)
    
    # Find outer contour and fill with white
    cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    cv2.fillPoly(close, cnts, [255,255,255])
    
    cv2.imshow('close', close)
    cv2.waitKey()
    

提交回复
热议问题