如何在一个文件夹中获取多个图像的轮廓

时间:2019-02-28 01:43:03

标签: python opencv image-processing

我的文件夹中有很多图像,我试图检测该文件夹中每张图像中第二大的轮廓以及该轮廓的面积和半径。这是我编写的代码,但我仅获得最后一张图像的半径。但是,当我打印出轮廓长度时,会得到文件夹中每个图像的轮廓长度。有人可以建议如何在文件夹中的所有图像中获取检测到的轮廓的所有半径,以及如何显示每个图像。

# looping and reading all images in the folder
for fn in glob.glob('E:\mf150414\*.tif'):
    im = cv2.imread(fn)
    blur = cv2.GaussianBlur(im,(5,5),cv2.BORDER_DEFAULT)
    img = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) 
    ret, thresh = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    _, contours,_ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    second_largest_cnt = sorted(contours, key = cv2.contourArea, reverse = True)[1:2]
    cv2.drawContours(img,second_largest_cnt,-1,(255,255,255),-1)  

# detecting the area of the second largest contour
for i in second_largest_cnt:
    area = cv2.contourArea(i)*0.264583333    # Area of the detected contour (circle)                                                    
    equi_radius = np.sqrt(area/np.pi)        # radius of the contour

1 个答案:

答案 0 :(得分:0)

您仅获得最后一张图像的半径,因为您为每个for循环重新分配了second_largest_cnt。您需要在for循环外创建一个second_largest_cnt数组来存储轮廓。例如:

second_largest_cnts = []

for fn in glob.glob('E:\mf150414\*.tif'):
    im = cv2.imread(fn)
    blur = cv2.GaussianBlur(im,(5,5),cv2.BORDER_DEFAULT)
    img = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY) 
    ret, thresh = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    _, contours,_ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    second_largest_cnt = sorted(contours, key = cv2.contourArea, reverse = True)[1] # don't need slicing
    # store the contour
    second_largest_cnts.append(second_largest_cnt)
    cv2.drawContours(img,[second_largest_cnt],-1,(255,255,255),-1)  

#do the same with radius
radius = []
# detecting the area of the second largest contour
for i in second_largest_cnts:
    area = cv2.contourArea(i)*0.264583333    # Area of the detected contour (circle)                                                    
    radius.append(np.sqrt(area/np.pi))       # radius of the contour