kadu
kadu

Reputation: 513

Sum of elements in a matrix in OpenCV?

I need to sum all the elements in a matrix. I used the function

  sum(sum(A)); 

in matlab. Where A is a matrix of size 300*360. I want to implement the same function in OpenCV. I used something like this.

  double s=cv::sum(cv::sum(A));

But there is error showing cannot convert scalar to double. How to fix this problem?

Upvotes: 31

Views: 77226

Answers (3)

Antonio
Antonio

Reputation: 20296

Scalar cv::sum(InputArray src) returns a Scalar where each channel has been summed separately (input image must have between 1 to 4 channels). If what we are looking for is the sum of all the values across all channels, one further step is needed summing all elements of the returned Scalar. A one-liner solution could be using the dot product with a scalar filled with ones:

cv::sum(A).dot(cv::Scalar::ones());

This works universally also for single channel images, without adding significant extra computation.

Upvotes: 1

Shai
Shai

Reputation: 114866

Unlike Matlab, in opencv, cv::sum(A) sums along ALL dimensions and returns a single number (scalar) that is equal to Matlab's sum(sum(A)).
So, what you need is

double s = cv::sum(A)[0];

Upvotes: 57

eiki
eiki

Reputation: 510

In addition with @Shai you can use;

double sum = cv::sum(A).val(0);

Upvotes: 10

Related Questions