图像处理之中值滤波原理及C++实现
1. 中值滤波原理
中值滤波算法以某像素的领域图像区域中的像素值的排序为基础,将像素领域内灰度的中值代替该像素的值[1];
如:以3*3的领域为例求中值滤波中像素5的值
- int pixel[9]中存储像素1,像素2...像素9的值;
- 对数组pixel[9]进行排序操作;
- 像素5的值即为数组pixel[9]的中值pixel[4]。
中值滤波对处理椒盐噪声非常有效。
2. C++代码实现
void medianFilter (unsigned char* corrupted, unsigned char* smooth, int width, int height)
{
memcpy ( smooth, corrupted, width*height*sizeof(unsigned char) );
for (int j=1;j<height-1;j++)
{
for (int i=1;i<width-1;i++)
{
int k = 0;
unsigned char window[9];
for (int jj = j - 1; jj < j + 2; ++jj)
for (int ii = i - 1; ii < i + 2; ++ii)
window[k++] = corrupted[jj * width + ii];
// Order elements (only half of them)
for (int m = 0; m < 5; ++m)
{
int min = m;
for (int n = m + 1; n < 9; ++n)
if (window[n] < window[min])
min = n;
// Put found minimum element in its place
unsigned char temp = window[m];
window[m] = window[min];
window[min] = temp;
}
smooth[ j*width+i ] = window[4];
}
}
}