2015-11-04 120 views
1

我想在非黑色像素上的cv::mat上執行cv::mean。這很容易做到這一點,使用掩蓋如:cv ::非黑色像素的平均值

cv::threshold(image, thresholded, 0, 255, cv::THRESH_BINARY); 
return cv::mean(image,thresholded); 

但是,有沒有更快的方式?也許某種OpenCV中的內置遮色技術?

P.S.黑色我的意思是(0)(0,0,0);不應該發生舍入。

回答

2

更緊湊的形式是:

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; 
} 
+0

謝謝回答,請注意;) –

+0

和許多感謝Bench-marking –

+0

@HumamHelfawi很高興幫助 – Miki