cv::mean 非黑色像素 [英] cv::mean for non black pixel

查看:53
本文介绍了cv::mean 非黑色像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对非黑色像素的 cv::mat 执行 cv::mean.使用掩码很容易做到:

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

但是,有没有更快的方法?也许是 OpenCV 中的某种内置颜色屏蔽技术?

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

附言黑色是指 (0)(0,0,0) ;不应发生四舍五入.

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

推荐答案

更紧凑的形式是:

Scalar mm = mean(img, img > 0);

还要注意的是:

threshold(image, thresholded, 1, 255, cv::THRESH_BINARY);

您要屏蔽所有大于 1 的像素,即 0 和 1 都将设置为 0.您需要:

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

屏蔽所有非零像素.

性能

这个方法也快一点:

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

这篇关于cv::mean 非黑色像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆