计算二进制图像中的对象 [英] Counting objects in binary images

查看:56
本文介绍了计算二进制图像中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理二进制图像,其中有很多小斑点.我想计算斑点的数量,并且发现轮廓通常用于执行此操作.但是,我获得的信息不允许我测量某些参数,例如这些斑点的面积和周长.有人对使用Python执行此操作有任何建议吗?

I am working with binary images in which there are a lot of small blobs. I would like to count the number of blobs and have found out that contours are commonly used to do that. However, the information I get does not allow me to measure certain parameters such as the area and the perimeter of these blobs. Does anybody have any recommendations how to do this with Python?

import cv2
from skimage.measure import regionprops

img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)

image, contours, hierarchy = cv2.findContours(img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)`

推荐答案

一旦有了轮廓,就可以使用cv2.contourArea()和cv2.arclength()函数分别获取面积和周长.例如,假设您要查找第一个轮廓的面积和周长.该代码将是这样的:

Once you have the contours, you can use cv2.contourArea() and cv2.arclength() functions to get area and perimeter respectively. For example, let us say you want to find the area and perimeter of the first contour. The code will be something like this:

contour_area = cv2.contourArea(contours[0])
cont_perimeter = cv2.arcLength(contours[0], True)

您也可以使用这些功能对找到的轮廓进行排序.例如,要根据面积对轮廓进行排序,

You can also use these functions to sort the found contours. For example, to sort your contours based on area,

sorted_contours = sorted(contours, key=cv2.contourArea, reverse=True)

在这里,"reverse = True"进行排序并以降序排列-从最大到最小.现在,当您访问sorted_contours [0]时,即找到了最大的轮廓.您还可以使用其他参数对它们进行排序.请参阅此处,以获取有关某些轮廓特征(例如弯矩,面积)的文档,周长等您可以提取的内容.希望这会有所帮助!

Here, 'reverse=True' sorts and puts it in a descending order -from largest to smallest. Now when you access sorted_contours[0], that is your largest contour found. You can also use other parameters to sort them. Refer here for documentation on some contour features like moments, area, perimeter, etc. that you can extract. Hope this helps!

这篇关于计算二进制图像中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆