Sum of columns of Opencv matrix elements

I need to calculate the sum of the elements in all columns separately.

Now I use:

The cross_corr matrix must be summed.

Mat cross_corr_summed; for (int i=0;i<cross_corr.cols;i++) { double column_sum=0; for (int k=0;k<cross_corr.rows;k++) { column_sum +=cross_corr.at<float>(k,i); } cross_corr_summed.push_back(column_sum); } 

The problem is that my program takes a lot of time. This is one of the reasons for suspicion. Can you advise any possible quick implementation?

Thanks!!!

+7
source share
3 answers

You need cv :: reduce :

 cv::reduce(cross_corr, cross_corr_summed, 0, CV_REDUCE_SUM, CV_32S); 
+24
source

If you know that your data is continuous and single-channel, you can directly access matrix data:

 int width = cross_corr.cols; float* data = (float*)cross_corr.data; Mat cross_corr_summed; for (int i=0;i<cross_corr.cols;i++) { double column_sum=0; for (int k=0;k<cross_corr.rows;k++) { column_sum += data[i + k*width]; } cross_corr_summed.push_back(column_sum); } 

which will be faster than using .at_<float>() . In general, I avoid using .at() whenever possible, because it is slower than direct access.

In addition, although cv::reduce() (proposed by Andrey) is much more readable, I found that it is slower than even your implementation in some cases.

+1
source
 Mat originalMatrix; Mat columnSum; for (int i = 0; i<originalMatrix.cols; i++) columnSum.push_back(cv::sum(originalMatrix.col(i))[0]); 
0
source

All Articles