灰度图像中值滤波
中值滤波是一种非线性型号处理方法,将每个像素的灰度值用其领域的中值代替。中值是指领域内奇数个数据按大小排序后处于中心位置的那个数。中值滤波能够在去除椒盐噪声的同时保持边缘清晰。
中值滤波是一个比较耗时的算法,为了提高速度,在程序设计时,并不需要对领域内所有点排序,只需要找到中值即可,因此这里只对前5个点进行了排序。
// 中值滤波
// 1. pImageData 图像数据
// 2. nWidth 图像宽度
// 3. nHeight 图像高度
// 4. nWidthStep 图像行大小
bool SmoothMedian(unsigned char *pImageData, int nWidth, int nHeight, int nWidthStep)
{
int i = 0;
int j = 0;
int m = 0;
int n = 0;
int nValue = 0;
unsigned char *pLine[3] = { NULL, NULL, NULL };
unsigned char chTempValue = 0;
unsigned char chTempArray[9];
for (j = 1; j < nHeight - 1; j++)
{
pLine[0] = pImageData + nWidthStep * (j - 1);
pLine[1] = pImageData + nWidthStep * j;
pLine[2] = pImageData + nWidthStep * (j + 1);
for (i = 1; i < nWidth - 1; i++)
{
chTempArray[0] = pLine[0][i-1];
chTempArray[1] = pLine[0][i];
chTempArray[2] = pLine[0][i+1];
chTempArray[3] = pLine[1][i-1];
chTempArray[4] = pLine[1][i];
chTempArray[5] = pLine[1][i+1];
chTempArray[6] = pLine[2][i-1];
chTempArray[7] = pLine[2][i];
chTempArray[8] = pLine[2][i+1];
// 取中值
for (m = 0; m < 5; m++)
{
for (n = m + 1; n < 9; n++)
{
if (chTempArray[m] > chTempArray[n])
{
chTempValue = chTempArray[m];
chTempArray[m] = chTempArray[n];
chTempArray[n] = chTempValue;
}
}
}
pLine[0][i-1] = chTempArray[4];
}
}
return true;
}