cv::mean for non black pixel

前端 未结 1 1389
青春惊慌失措
青春惊慌失措 2020-12-22 04:34

I want to perform cv::mean on a cv::mat on non-black pixel. It\'s easy to do it using masking like:

cv::threshold(image, thresholde         


        
相关标签:
1条回答
  • 2020-12-22 05:18

    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;
    }
    
    0 讨论(0)
提交回复
热议问题