Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

c++ - cv::mean for non black pixel

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, thresholded, 0, 255, cv::THRESH_BINARY);
return cv::mean(image,thresholded);

However, is there any faster way? Perhaps some kind of built-in color-masking technique in OpenCV?

P.S. by black I mean (0) or (0,0,0) exactly; no rounding should be happening.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...