简体   繁体   中英

Grayscale Average Filter Opencv

I am just starting with programming in Opencv, I am trying to implement a simple average filter. I understand that there is a in built function in OpenCv but I don't want to use this yet, I am looking to understand the spatial domain filtering mechanism and its similarity with convolution. Below is a function I have written that takes in Input and Output

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

This doesn't perform the averaging, could you please tell me what I am doing wrong ?

Thank you

You are probably getting overflow by doing everything with unsigned char , so try something like this

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

Also, I think your previous and next row pixels are wrong - you need to be mutplying the row number by the width. Similar with output .

EDIT correction, I just checked the OpenCV documentation and ptr is a row pointer, so ignore my last comment!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM