C++ 使用 OpenCV 计算对象的面积
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11631533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate the area of an object with OpenCV
提问by Temer
I need to calculate the area of a blob/an object in a grayscale picture (loading it as Mat, not as IplImage) using OpenCV.
I thought it would be a good idea to get the coordinates of the edges (number of edges change form object to object) or to get all coordinates of the contour and then use contourArea()
to calculate the area of my object.
我需要使用OpenCV计算灰度图片中 blob/对象的面积(将其加载为 Mat,而不是 IplImage)。我认为获取边缘坐标(边缘数量从对象到对象的变化)或获取轮廓的所有坐标然后用于contourArea()
计算对象的面积是个好主意。
I deleted all noise and got some nice and satisfying contours by using findContours()
(programming in C++).
我删除了所有噪音,并通过使用findContours()
(在C++ 中编程)获得了一些漂亮且令人满意的轮廓。
findContours(InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy,int mode, int method, Point offset=Point());
Now I got to understand that param contours
already owns the coordinates of all contours of my object. Did I get that right?
现在我明白了 paramcontours
已经拥有我对象的所有轮廓的坐标。我做对了吗?
If yes, it there a way to access them?
如果是,有没有办法访问它们?
And if no, how do I get the coordinates of the contour anyway?
如果不是,我如何获得轮廓的坐标?
回答by Sam
contours
is actually defined as
contours
实际上定义为
vector<vector<Point> > contours;
And now I think it's clear how to access its points.
现在我认为很清楚如何访问它的点。
The contour area is calculated by a function nicely called contourArea()
:
轮廓区域由一个很好地调用的函数计算contourArea()
:
for (unsigned int i = 0; i < contours.size(); i++)
{
std::cout << "# of contour points: " << contours[i].size() << std::endl;
for (unsigned int j=0; j<contours[i].size(); j++)
{
std::cout << "Point(x,y)=" << contours[i][j] << std::endl;
}
std::cout << " Area: " << contourArea(contours[i]) << std::endl;
}