Search code examples
cmatlabmedian

Median filter implementation testing


I implemented a 2D median filter in C. For an image of size 1440X1440, floating point values. For starting, I tried it with a simple 3X3 kernel size. Here's the code.

#define     kernelSize      3

void sort(float *array2sort, int n)
{
    float       temp;
    for(int i=0; i < n-1; i++)
        for(int j=0; j < n-1-i; j++)
            if(array2sort[j] > array2sort[j+1])
            {
                temp = array2sort[j];
                array2sort[j] = array2sort[j+1];
                array2sort[j+1] = temp;
            }
}


void medianFilter(float *input, float *output)
{
    int     halfKernelSize = kernelSize/2;

    float   neighbourhood[kernelSize*kernelSize];

    for(int i=0+halfKernelSize; i<(1440-halfKernelSize); i++)
        for(int j=0+halfKernelSize; j<(1440-halfKernelSize); j++)
        {
            for(int ii=-halfKernelSize; ii<halfKernelSize+1; ii++)
                for(int jj=-halfKernelSize; jj<halfKernelSize+1; jj++)
                    neighbourhood[(ii+halfKernelSize)*kernelSize+(jj+halfKernelSize)] = input[(i+ii)*1440+(j+jj)];
            sort(neighbourhood, kernelSize*kernelSize);
            output[(i)*1440+(j)] = neighbourhood[(kernelSize*kernelSize)/2+1];
        }

}

Now, in order to verify if the code is fine, I took an image, added salt & pepper noise to it using MATLAB. Then tried the above code on it. I can see the noise getting reduced ALMOST completely with a few dots remaining. If I increase the kernel size to 5X5, noise does get filtered completely. But the worrying fact for me is ,the MATLAB ,median filter code is able to remove the noise completely even with a kernel of size 3X3. That leaves me in doubt. Please have a look at the code and let me know if there is some fault in the filter implementation or the MATLAB code is taking some additional steps.


Solution

  • I think the median value calculated from neighbourhood buffer is wrong. It should have been neighbourhood[(kernelSize*kernelSize)/2]. Can you try with this correction?