opencv查找已连接组件的周长 [英] opencv find perimeter of a connected component
问题描述
我正在使用opencv 2.4.13
I'm using opencv 2.4.13
我正在尝试查找连接的组件的外围,我在考虑使用 ConnectedComponentWithStats ,但不会返回周长,仅返回面积,宽度等... 有一种方法可以找到轮廓不大但相对的区域(我指的是一个分量,而不是整个图像).
I'm trying to find the perimeter of a connected component, I was thinking of using ConnectedComponentWithStats but it doesn't return the perimeter, only the area, width, etc... There is a method to find the area with the contour but not the opposite (with one component i mean, not the entire image).
方法 arcLength 效果不佳我不仅具有轮廓,而且具有组件的所有点.
The method arcLength doesn't work as well beause i have all the points of the component, not only the contour.
我知道有一种BF方法,可以通过遍历组件的每个像素并查看他是否具有不在同一组件中的邻居来找到它.但是我想要一个成本更低的函数. 否则,如果您知道将组件与方法findContours找到的轮廓链接的方法,那么它也很适合我.
I know there is a BF way to find it by iterating through each pixel of the component and see if he has neighbors which aren't in the same component. But I'd like a function which costs less. Otherwise, if you know a way to link a component with the contours found by the method findContours, it suits me as well.
谢谢
推荐答案
最简单的方法可能是使用findContours
.
The easiest thing is probably to use findContours
.
您可以在由connectedComponents(WithStats)
计算的第i个分量上计算轮廓,以使它们与标签对齐.使用CHAIN_APPROX_NONE
,您将获得轮廓中的所有点,因此向量的size()
已经是周长的量度.您最终可以使用arcLength(...)
获得更准确的结果:
You can compute the contour on the i-th component computed by connectedComponents(WithStats)
, so they are aligned with your labels. Using CHAIN_APPROX_NONE
you'll get all the points in the contour, so the size()
of the vector is already a measure of the perimeter. You can eventually use arcLength(...)
to get a more accurate result:
Mat1i labels;
int n_labels = connectedComponents(img, labels);
for (int i = 1; i < n_labels; ++i)
{
// Get the mask for the i-th contour
Mat1b mask_i = labels == i;
// Compute the contour
vector<vector<Point>> contours;
findContours(mask_i.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
if (!contours.empty())
{
// The first contour (and probably the only one)
// is the one you're looking for
// Compute the perimeter
double perimeter_i = contours[0].size();
}
}
这篇关于opencv查找已连接组件的周长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!