高斯模糊是一种两维的卷积模糊操作,在图像完成高斯模糊相对于均值模糊来说,
计算量会增加,但是高斯模糊可以实现一些特殊效果,特别是在图像噪声(非椒盐
噪声)消去方面,更是有着非常好的效果。
一维高斯公式
其中x是指定密度分布[-n,n]范围的整数,sigma代表标准方差(如果在范围内做平均密度分布,sigma=n/3)。
一维高斯函数Java代码如下:
public static Kernel get(int radius, boolean horizontal){
if (radius < 1) {
throw new IllegalArgumentException("radius must be >= 1");
}
int size = radius * 2 +1;
float[] data = new float[size];
float sigma = radius/3.0f;
float twoSigmaSquare = 2.0f * sigma * sigma;
float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI);
float sum = 0.0f;
for (int i = -radius; i <= radius; i++) {
float distance = i * i;
int index = i + radius;
data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot;
sum += data[index];
}
for (int i = 0; i < data.length; i++) {
data[i] /= sum;
}
return horizontal? new Kernel(size, 1, data): new Kernel(1, size, data);
}
两维的高斯分布函数
对应的Java实现代码为:
public static Kernel get2D(int radius){
if (radius < 1) {
throw new IllegalArgumentException("radius must be >= 1");
}
float sum=0.0f;
int width= radius *2+1;
int size = (int)Math.pow((float)(width), 2);
float sigma=radius/3.0f;
float twoSigmaSquare = 2.0f*sigma*sigma;
float sigmaRoot = (float)Math.PI * twoSigmaSquare;
float[] data = new float[size];
int index = 0;
float x, y;
for(int i=-radius; i<= radius; i++) {
for(int j=-radius; j<= radius; j++) {
x = i*i;
y = j*j;
data[index] = (float)Math.exp(-(x + y)/twoSigmaSquare)/sigmaRoot;
sum+=data[index];
index++;
}
}
for(int k=0; k<size; k++){
data[k]=data[k]/sum;
}
return new Kernel(width, width, data);
}
一个2D高斯分布的图可以表示如下: