java实现卷积(附完整源码)
时间: 2023-11-09 08:06:47 浏览: 44
以下是Java实现卷积的完整源码,包含了常规卷积和边缘扩展卷积:
```java
import java.awt.image.BufferedImage;
public class Convolution {
public static BufferedImage convolve(BufferedImage img, double[][] kernel) {
int width = img.getWidth();
int height = img.getHeight();
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int kWidth = kernel.length;
int kHeight = kernel[0].length;
int kCenterX = kWidth / 2;
int kCenterY = kHeight / 2;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double r = 0, g = 0, b = 0;
for (int j = 0; j < kHeight; j++) {
for (int i = 0; i < kWidth; i++) {
int pixelX = x + i - kCenterX;
int pixelY = y + j - kCenterY;
if (pixelX >= 0 && pixelX < width && pixelY >= 0 && pixelY < height) {
int rgb = img.getRGB(pixelX, pixelY);
double k = kernel[i][j];
r += ((rgb >> 16) & 0xFF) * k;
g += ((rgb >> 8) & 0xFF) * k;
b += (rgb & 0xFF) * k;
}
}
}
int resultRGB = ((int) r << 16) | ((int) g << 8) | (int) b;
result.setRGB(x, y, resultRGB);
}
}
return result;
}
public static BufferedImage convolveWithEdgeExtension(BufferedImage img, double[][] kernel) {
int width = img.getWidth();
int height = img.getHeight();
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int kWidth = kernel.length;
int kHeight = kernel[0].length;
int kCenterX = kWidth / 2;
int kCenterY = kHeight / 2;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double r = 0, g = 0, b = 0;
for (int j = 0; j < kHeight; j++) {
for (int i = 0; i < kWidth; i++) {
int pixelX = x + i - kCenterX;
int pixelY = y + j - kCenterY;
if (pixelX < 0) {
pixelX = 0;
} else if (pixelX >= width) {
pixelX = width - 1;
}
if (pixelY < 0) {
pixelY = 0;
} else if (pixelY >= height) {
pixelY = height - 1;
}
int rgb = img.getRGB(pixelX, pixelY);
double k = kernel[i][j];
r += ((rgb >> 16) & 0xFF) * k;
g += ((rgb >> 8) & 0xFF) * k;
b += (rgb & 0xFF) * k;
}
}
int resultRGB = ((int) r << 16) | ((int) g << 8) | (int) b;
result.setRGB(x, y, resultRGB);
}
}
return result;
}
}
```
其中,`convolve` 函数实现了常规的卷积操作,`convolveWithEdgeExtension` 函数实现了边缘扩展卷积操作。两个函数的参数均为输入图像和卷积核,返回值为经过卷积处理后的图像。