python - 如何获取文件夹中多个图像的轮廓
问题描述
我在一个文件夹中有很多图像,我试图检测文件夹中每个图像中的第二大轮廓以及该轮廓的面积和半径。这是我写的代码,但我只得到最后一张图像的半径。但是,当我打印出轮廓长度时,我会得到文件夹中每个图像的轮廓长度。有人可以就如何获取文件夹中所有图像中检测到的轮廓的所有半径以及如何显示每张图像提出建议。
# 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
解决方案
您只能获得最后一张图像的半径,因为您在每个 for 循环中都重新分配了 second_largest_cnt。您需要second_largest_cnt
在 for 循环之外创建一个数组来存储轮廓。例如:
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
推荐阅读
- finite-automata - 证明语言不是上下文无关的?
- amazon-web-services - 最小任务数,ECS
- java - 将 ImageView 的大小调整为另一个 ImageView 的大小的动画
- javascript - 如何仅在现有节点项目的一部分(购物车页面)中添加/使用 React 组件?
- php - Laravel 在“存储/日志”中没有现有目录
- .net - 创建具有多种页面大小的 XPS 文档
- go - gorm 查询 OR
- android - 无法通过 VPN 调用 Retrofit 服务
- docker - 将文件复制到 JAVA 中 docker 容器中的文件夹
- xamarin.forms - 无法分配属性“转换器”:属性不存在,或不可分配,或值和属性之间的类型不匹配