到目前为止,我的方法-(python代码):
预期输出-
闭合循环数= 6,沿循环的像素总和或沿闭合曲线边缘的所有(x,y)点,如[[RED中突出显示]
预期输出-
findContours()
即可获取内部轮廓。请记住,要使用findContours()
轻松进入孔:
检索所有轮廓并将它们组织为两级层次结构。在顶层,组件具有外部边界。在第二层,有孔的边界。如果连接的组件的孔内还有其他轮廓,则该轮廓仍放在顶层。
应该只是简单地将国家的长度记在第二层(洞)上的问题
cv2.RETR_CCOMP
as the Countour Retrieval Mode
cv2.RETR_CCOMP
产生的轮廓:Count:
import cv2 import numpy as np # read image as grayscale img = cv2.imread('loops.png', cv2.IMREAD_GRAYSCALE) hh, ww = img.shape # blacken right columns that are white img[0:hh, ww-3:ww] = 0 # threshold thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)[1] # get contours contours = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) hierarchy = contours[1] if len(contours) == 2 else contours[2] contours = contours[0] if len(contours) == 2 else contours[1] # get the actual inner list of hierarchy descriptions hierarchy = hierarchy[0] # count inner contours count = 0 result = img.copy() result = cv2.merge([result,result,result]) for component in zip(contours, hierarchy): cntr = component[0] hier = component[1] # discard outermost no parent contours and keep innermost no child contours # hier = indices for next, previous, child, parent # no parent or no child indicated by negative values if (hier[3] > -1) & (hier[2] < 0): count = count + 1 cv2.drawContours(result, [cntr], 0, (0,0,255), 2) # print count print("count:",count) # save result cv2.imwrite("loops_result.png",result) # show result cv2.imshow("result", result) cv2.waitKey(0) cv2.destroyAllWindows()