中值滤波对椒盐噪声有很好的滤出效果,下面以3x3滤波器为例,实现中值滤波。
排序,采用选择排序。
void Sort(int data[9])
{
int i;
int j;
int minv;
int index;
index = 0;
for (i = 0; i < 9; i++)
{
minv = data[i];
index = i;
for (j = i+1; j < 9; j++)
{
if (minv > data[j])
{
minv = data[j];
index = j;
}
}
data[index] = data[i];
data[i] = minv;
}
}
中值滤波:
void RGB32MedianFilting(uint8_t* src, uint8_t* dst, int width, int height)
{
int i,j;
int m,n;
int d;
uint32_t row_bytes;
uint32_t color;
int r_data[9];
int g_data[9];
int b_data[9];
uint32_t* img;
uint32_t* ptr;
uint32_t* dimg;
uint32_t off;
row_bytes = width * 4;
off = row_bytes + 4;
for (i = 1; i < height - 1; i++)
{
img = (uint32_t*)(src + off);
dimg = (uint32_t*)(dst + off);
for (j = 1; j < width - 1; j++)
{
ptr = img;
d = 0;
for (m = -1; m <= 1; m++)
{
ptr = img + m * width;
for (n = -1; n <= 1; n++)
{
ptr += n;
color = *ptr;
r_data[d] = color & 0x000000FF;
g_data[d] = (color >> 8) & 0x000000FF;
b_data[d] = (color >> 16) & 0x000000FF;
d++;
}
}
Sort(r_data);
Sort(g_data);
Sort(b_data);
color &= 0xFF000000;
color |= r_data[4] + (g_data[4] << 8) + (b_data[4] << 16);
*dimg = color;
dimg++;
img++;
}
off += row_bytes;
}
}
要拓展到5x5,7x7等,也很容易。另外,对边界采取忽略的处理方式。