java实现中值滤波(附完整源码)
时间: 2023-11-09 09:05:34 浏览: 37
以下是Java实现中值滤波的完整源代码:
```java
import java.awt.image.BufferedImage;
public class MedianFilter {
public static BufferedImage apply(BufferedImage image) {
int w = image.getWidth();
int h = image.getHeight();
int[] pixels = new int[w * h];
image.getRGB(0, 0, w, h, pixels, 0, w);
int[] newPixels = new int[w * h];
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
int i = y * w + x;
int[] neighbors = getNeighbors(pixels, w, h, x, y);
int median = getMedian(neighbors);
newPixels[i] = (pixels[i] & 0xff000000) | (median << 16) | (median << 8) | median;
}
}
BufferedImage result = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
result.setRGB(0, 0, w, h, newPixels, 0, w);
return result;
}
private static int[] getNeighbors(int[] pixels, int w, int h, int x, int y) {
int[] neighbors = new int[9];
int i = 0;
for (int dy = -1; dy <= 1; dy++) {
for (int dx = -1; dx <= 1; dx++) {
int nx = x + dx;
int ny = y + dy;
if (nx >= 0 && nx < w && ny >= 0 && ny < h) {
int ni = ny * w + nx;
neighbors[i++] = pixels[ni] & 0xff;
}
}
}
return neighbors;
}
private static int getMedian(int[] values) {
int[] sorted = values.clone();
Arrays.sort(sorted);
return sorted[sorted.length / 2];
}
}
```
这个类有一个静态方法`apply`,可以将中值滤波应用于给定的`BufferedImage`对象。算法的核心是`getNeighbors`和`getMedian`方法,它们分别找到给定像素周围的像素和它们的中值。`apply`方法迭代图像的每个像素,并用中值替换它。最后,结果图像作为`BufferedImage`对象返回。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)