Calculating sum of a subset of Mat OpenCV

4.3k views Asked by At

Can we calculate directly without using any loops the sum of a subset of Mat element in OpenCV (C++)?

Example: Mat b_hist, has 1 column and 256 rows. How can I calculate the sum of rows from 0 to 105 rows or from 106 to 150 rows?

I know sum(b_hist) would give the sum of entire Mat. How can I get some of a subset? Is there any similar method? Can someone please tell about it?

1

There are 1 answers

0
herohuyongtao On

You can first use cv::Range to get sub-mats that you want and then sum on them:

cv::Mat sub_mat_1 = mat(cv::Range(0, 106),   cv::Range::all());
cv::Mat sub_mat_2 = mat(cv::Range(106, 151), cv::Range::all());

std::cout << cv::sum(sub_mat_1).val[0] << std::endl;
std::cout << cv::sum(sub_mat_2).val[0] << std::endl;