### Median Filter

I've spent quite a lot of time looking for an example code for performing median filtering and finally I made it by myself with some concepts from the book. It's quite funny to see that it's very difficult to find an example, is it because Median Filter is too simple?

I use vector for storing data inside the window. This is due to the reason that I want to use the algorithm that has been written in STL instead of writing my own algorithms for sorting the data. The code is very simple.

In order to understand this code, you need to know STL and OpenCV.

`#include < vector >`

#include < algorithm >

for(int row = 0; row < srcMat-> rows;row++)

{

for(int col=0;col < srcMat-> cols;col++)

{

double count = 0;

double sum = 0;

vector data;

for (int y=row-1;y<=row+1;y++)

{

for (int x=col-1;x<=col+1;x++)

{

if ((x >=0)&&(x< srcMat->cols)&&(y>=0)&&(y< srcMat->rows))

{

count+=1;

sum = cvmGet(sourceMat, y, x);

data.push_back(sum);

}

}

}

sort (data.begin(), data.end(), myfunction);

double val = data.at(data.size()/2);

cvmSet(filteredMat, row, col, val);

}

}

sourceMat is the original data and filteredMat is the data after median filtering myfunction is a simple sorting function:

`bool myfunction (double i,double j)`

{

return (i < j);

}

and sort() is one of the algorithm from the stl::algorithm.

Hope it helps.

Labels: c++, median filter, stl