A more compact form is:
Scalar mm = mean(img, img > 0);
Also note that doing:
threshold(image, thresholded, 1, 255, cv::THRESH_BINARY);
you are masking all pixels that are > 1, i.e. both 0 and 1 will be set to 0. You need:
threshold(image, thresholded, 0, 255, cv::THRESH_BINARY);
to mask all non-zero pixels.
Performance
This method is also a little faster:
With threshold: 6.98269
With > 0 : 4.75043
Test code:
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int main(int, char**)
{
Mat1b img(1000, 1000);
randu(img, 0, 3);
{
double tic = double(getTickCount());
Mat1b thresholded;
threshold(img, thresholded, 0, 255, cv::THRESH_BINARY);
Scalar m = cv::mean(img, thresholded);
double toc = (double(getTickCount()) - tic) * 1000.0 / getTickFrequency();
cout << "With threshold: " << toc << endl;
}
{
double tic = double(getTickCount());
Scalar m = mean(img, img > 0);
double toc = (double(getTickCount()) - tic) * 1000.0 / getTickFrequency();
cout << "With > 0 : " << toc << endl;
}
getchar();
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…