【问题标题】:Grayscale Average Filter Opencv灰度平均滤波器 Opencv
【发布时间】:2013-05-05 08:15:00
【问题描述】:

我刚开始在 Opencv 中编程,我正在尝试实现一个简单的平均滤波器。我知道 OpenCv 中有一个内置函数,但我还不想使用它,我希望了解空间域过滤机制及其与卷积的相似性。下面是我编写的一个接受输入和输出的函数

void averageFilter(Mat& Input,Mat& Output)
{
    int row=Input.rows;
    int col=Input.cols;
    //uchar *input_data=Input.data;
    //uchar *output_data=Output.data;
    int size=1;
    uchar count=0;
    uchar sum=0;

    //int nChannels=1;

     for(int j = 1 ; j < Input.rows-1; ++j)
    {
        const uchar* previous = Input.ptr<uchar>(j - 1);
        const uchar* current  = Input.ptr<uchar>(j    );
        const uchar* next     = Input.ptr<uchar>(j + 1);

        uchar* output = Output.ptr<uchar>(j);

        for(int i= 1;i < (Output.cols-1); ++i)
        {
            *output++ = (current[i]
                         +current[i-1] + current[i+1] + previous[i] +next[i]+previous[i-1]+previous[i+1]+next[i-1]+next[i+1])/9;
        }
    }
}

这不执行平均,你能告诉我我做错了什么吗?

谢谢

【问题讨论】:

    标签: c++ opencv average grayscale smoothing


    【解决方案1】:

    使用unsigned char 做所有事情可能会导致溢出,所以试试这样的方法

    for(int i= 1;i < (Output.cols-1); ++i)
    {
        double dResult = (current[i] +current[i-1] + current[i+1] + 
                          previous[i] +next[i]+previous[i-1]+previous[i+1]+
                          next[i-1]+next[i+1])/9.0;
        *output++ = (unsigned char)dResult;
    }
    

    另外,我认为您的 previousnext 行像素是错误的 - 您需要将行号乘以宽度。与output类似。

    EDIT更正,我刚查了OpenCV文档,ptr是一个行指针,所以忽略我最后的评论!

    【讨论】:

    • 我想我明白你的意思,我会尝试更改谢谢
    猜你喜欢
    • 2018-11-03
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多