普通的高斯滤波会将图像的边缘模糊掉,而双边滤波器具有保边特性。
#define MAX_IMAGE_SIZE 1024 double d[MAX_IMAGE_SIZE][MAX_IMAGE_SIZE];//d[i][j]表示入图像,fi][j]表示出图像。 double f[MAX_IMAGE_SIZE][MAX_IMAGE_SIZE]; void CImageColorProcess::Bilateral(LPBYTE lpSrc, LPBYTE lpDst, int nSrcCount, int nW, int nH) { int i, j, k, l; int p = 5;//p决定模板大小。当p=1时,模板为3*3;当p=2时,模板为5*5;当p=n时,模板为(2n+1)*(2n+1)。 short m, n; double a1 = 0.02, b1 = 0.002; double aa1, bb1;//aa1,bb1为滤波模板中的各权重。 //gguiyi高斯滤波的归一化系数,bguiyi双边滤波的归一化系数,gsum高斯滤波像素的加权和,bsum双边滤波像素的加权和。 double gguiyi = 0.0, bguiyi = 0.0, gsum = 0.0, bsum = 0.0; int x_size2 = nW;//x_size1; int y_size2 = nH;//y_size1; LPBYTE lpSrc1 = new byte[nW*nH]; RGB2Gray(lpSrc, lpSrc1, 24, nW, nH); //将读取的噪声图像赋给入力图像 for (i = 0; i < nH; i++) { for (j = 0; j < nW; j++) { d[i][j] = lpSrc1[i*nW + j]; } } //高斯滤波,双边滤波处理噪声图像 for (i = 0; i < nH; i++) { for (j = 0; j < nW; j++) { for (k = -p; k <= p; k++) { for (l = -p; l <= p; l++) { m = i + k; n = j + l; //abs()返回指定数字的绝对值 if (m<0) { m = abs(i + k) - 1; }
<span style="font-size: 12px;"> </span><span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"> if (m>nH - 1) { m = 2 * nH - i - k - 1; }</span>
if (n<0) { n = abs(j + l) - 1; } if (n>nW - 1) { n = 2 * nW - j - l - 1; } aa1 = exp(-a1*(l*l + k*k)); bb1 = exp(-b1*(d[i][j] - d[m][n])*(d[i][j] - d[m][n])); bsum += aa1*bb1*d[m][n]; bguiyi += aa1*bb1; } } f[i][j] = bsum / bguiyi; gguiyi = 0.0, bguiyi = 0.0, gsum = 0.0, bsum = 0.0; } } //将滤波后的像素赋给新的图像 for (i = 0; i < nH; i++) { for (j = 0; j < nW; j++) { lpDst[i*nW + j] = (unsigned char)(f[i][j] + 0.5); } } }
原文地址:http://blog.csdn.net/u014568921/article/details/44307199