Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate mean for vector of points

Tags:

c++

opencv

I have a vector of a 2-dimensional points in OpenCV

std::vector<cv::Point2f> points;

I would like to calculate the mean values for x and y coordinates in points. Something like:

cv::Point2f mean_point; //will contain mean values for x and y coordinates
mean_point = some_function(points); 

This would be simple in Matlab. But I'm not sure if I can utilize some high level OpenCV functions to accomplish the same. Any suggestions?

like image 884
Alexey Avatar asked Jul 19 '12 18:07

Alexey


People also ask

How do you find the mean of a vector in R?

In R, the mean of a vector is calculated using the mean() function. The function accepts a vector as input, and returns the average as a numeric.


2 Answers

InputArray does a good job here. You can simply call

cv::Mat mean_;
cv::reduce(points, mean_, 01, CV_REDUCE_AVG);
// convert from Mat to Point - there may be even a simpler conversion, 
// but I do not know about it.
cv::Point2f mean(mean_.at<float>(0,0), mean_.at<float>(0,1)); 

Details:

In the newer OpenCV versions, the InputArray data type is introduced. This way, one can send as parameters to an OpenCV function either matrices (cv::Mat) either vectors. A vector<Vec3f> will be interpreted as a float matrix with three channels, one row, and the number of columns equal to the vector size. Because no data is copied, this transparent conversion is very fast.

The advantage is that you can work with whatever data type fits better in your app, while you can still use OpenCV functions to ease mathematical operations on it.

like image 85
Sam Avatar answered Sep 28 '22 04:09

Sam


You can use stl's std::accumulate as follows:

cv::Point2f sum = std::accumulate(
    points.begin(), points.end(), // Run from begin to end
    cv::Point2f(0.0f,0.0f),       // Initialize with a zero point
    std::plus<cv::Point2f>()      // Use addition for each point (default)
);
cv::Point2f mean = sum / points.size(); // Divide by count to get mean
like image 30
smocking Avatar answered Sep 28 '22 03:09

smocking