Recognize open and closed shapes opencv

前端 未结 4 1010
终归单人心
终归单人心 2020-12-04 17:17

how to detect open and closed shapes in opencv.

\"enter

These are simple sampl

4条回答
  •  广开言路
    2020-12-04 17:32

    Python implementation of the same as below.

    import cv2
    
    
    src = cv2.imread('test.png', cv2.IMREAD_COLOR)
    
    #Transform source image to gray if it is not already
    if len(src.shape) != 2:
        gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    else:
        gray = src
    
    ret, thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    hierarchy = hierarchy[0]
    
    for i, c in enumerate(contours):
        if hierarchy[i][2] < 0 and hierarchy[i][3] < 0:
            cv2.drawContours(src, contours, i, (0, 0, 255), 2)
        else:
            cv2.drawContours(src, contours, i, (0, 255, 0), 2)
    #write to the same directory
    cv2.imwrite("result.png", src)
    

提交回复
热议问题