在 Java 中怎么实现高斯模糊?
作者:互联网
如何对加载的图像应用高斯模糊的示例代码:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class GaussianBlurExample {
public static void main(String[] args) {
try {
// 读取图像
BufferedImage image = ImageIO.read(new File("path/to/your/image.jpg")); // 替换为您的图像路径
// 应用高斯模糊
BufferedImage blurredImage = applyGaussianBlur(image, 15); // 15是模糊的程度
// 保存模糊后的图像
ImageIO.write(blurredImage, "jpg", new File("path/to/save/blurred_image.jpg")); // 替换为保存路径
} catch (IOException e) {
e.printStackTrace();
}
}
public static BufferedImage applyGaussianBlur(BufferedImage image, int radius) {
// 创建高斯模糊矩阵
float[] matrix = createGaussianKernel(radius);
kernel = new Kernel(matrix.length, matrix.length, matrix);
ConvolveOp convolveOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
// 应用高斯模糊
return convolveOp.filter(image, null);
}
private static float[] createGaussianKernel(int radius) {
int size = radius * 2 + 1;
float[] kernel = new float[size * size];
float sigma = radius / 3f;
float sum = 0;
for (int x = -radius; x <= radius; x++) {
for (int y = -radius; y <= radius; y++) {
float value = (float) Math.exp(-(x * x + y * y) / (2 * sigma * sigma));
kernel[(x + radius) * size + (y + radius)] = value;
sum += value;
}
}
// 归一化
for (int i = 0; i < kernel.length; i++) {
kernel[i] /= sum;
}
return kernel;
}
}
Java
代码说明
- 读取图像:使用
ImageIO.read()
从指定路径读取图像。 - 创建高斯模糊矩阵:
createGaussianKernel
方法生成一个高斯模糊内核。 - 应用高斯模糊:使用
ConvolveOp
对图像应用模糊效果。 - 保存模糊后的图像:将模糊处理后的图像保存到指定路径。
标签: 来源: