更緊湊的形式是:
Scalar mm = mean(img, img > 0);
還要注意的是這樣做的:
threshold(image, thresholded, 1, 255, cv::THRESH_BINARY);
將屏蔽是> 1的所有像素,即0和1將被設置爲0。您需要:
threshold(image, thresholded, 0, 255, cv::THRESH_BINARY);
掩蓋所有非零像素。
性能
這種方法也更快一點:
With threshold: 6.98269
With > 0 : 4.75043
測試代碼:
#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;
}
謝謝回答,請注意;) –
和許多感謝Bench-marking –
@HumamHelfawi很高興幫助 – Miki