OpenCV 2 Centroid

问题描述 投票:9回答:4

我试图找到轮廓的质心,但在C ++(OpenCV 2.3.1)中实现示例代码时遇到了问题。谁能帮我吗?

c++ opencv image-processing centroid
4个回答
15
投票

要查找轮廓的质心,可以使用矩量法。并且功能是OpenCV实现的。

看看这些时刻功能(central and spatial moments)。

下面的代码来自OpenCV 2.3 docs教程。 Full code here.


/// Find contours
findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

/// Get the moments
vector<Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
 { mu[i] = moments( contours[i], false ); }

///  Get the mass centers:
vector<Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
 { mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); } 

check out this SOF,虽然它是在Python中,但它会很有用。它找到轮廓的所有参数。


5
投票

如果您有轮廓区域的蒙版,则可以按如下方式找到质心位置:

cv::Point computeCentroid(const cv::Mat &mask) {
    cv::Moments m = moments(mask, true);
    cv::Point center(m.m10/m.m00, m.m01/m.m00);
    return center;
}

当一个人有面具而不是轮廓时,这种方法很有用。在这种情况下,与使用cv::findContours(...)然后找到质量中心相比,上述方法在计算上更有效。

Here's the source


1
投票

您还可以使用以下算法查找质心:

sumX = 0; sumY = 0;
size = array_points.size;
if(size > 0){

    foreach(point in array_points){
        sumX += point.x;
        sumY += point.y;
    }

 centroid.x = sumX/size;
 centroid.y = sumY/size;
}

或者在Opencv的boundingRect的帮助下:

//pseudo-code:

Rect bRect = Imgproc.boundingRect(array_points);

centroid.x = bRect.x + (bRect.width / 2);
centroid.y = bRect.y + (bRect.height / 2);

0
投票

给定轮廓点和Wikipedia的公式,可以有效地计算质心,如下所示:

template <typename T> 
cv::Point_<T> computeCentroid(const std::vector<cv::Point_<T> >& in) {
    if (in.size() > 2) {
         T doubleArea = 0;
         cv::Point_<T> p(0,0);
         cv::Point_<T> p0 = in->back();
         for (const cv::Point_<T>& p1 : in) {//C++11
             T a = p0.x * p1.y - p0.y * p1.x; //cross product, (signed) double area of triangle of vertices (origin,p0,p1)
             p += (p0 + p1) * a;
             doubleArea += a;
             p0 = p1;
         }

         if (doubleArea != 0)
             return p * (1 / (3 * doubleArea) ); //Operator / does not exist for cv::Point
    }

    ///If we get here,
    ///All points lies on one line, you can compute a fallback value,
    ///e.g. the average of the input vertices
    [...]
}

注意:

  • 此公式适用于以顺时针和逆时针顺序给出的顶点。
  • 如果点具有整数坐标,则可以方便地将p的类型和返回值的类型调整为Point2fPoint2d,并将floatdouble的强制转换添加到return语句中的分母。
© www.soinside.com 2019 - 2024. All rights reserved.