图像处理KNN算法

KNN处理算法

  • 算法思想:

    使用待处理像素周围元素集合中数值最接近待处理元素的元素替换待处理元素

  • 数学表达式:

    image[i][j] = (imgae[i-1][j-1] , image[i][j-1] , image[i+1][j-1] ,
    image[i-1][j] , image[i+1][j] ,
    image[i-1][j+1] , image[i][j+1] , image[i+1][j+1]).closedValue()

  • 代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    private static int knnfilter(int[][] image) {
try {
Scanner sc = new Scanner(System.in);
System.out.println("请输入图片的m,n值:");
int m = sc.nextInt();
int n = sc.nextInt();
image = new int[m][n];
newImage = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
image[i][j] = sc.nextInt();
}
}
System.out.println("原图片的数值为:");
System.out.println(Arrays.deepToString(image));
for (int i = 1; i < m - 1; i++) {
for (int j = 1; j < n - 1; j++) {
int[] array = new int[]{image[i - 1][j - 1], image[i][j - 1], image[i + 1][j - 1],
image[i - 1][j], image[i + 1][j],
image[i - 1][j + 1], image[i][j + 1], image[i + 1][j + 1]};
int index = 0;
int temp = Integer.MAX_VALUE;
for (int k = 0; k < array.length; k++) {
int abs = Math.abs(image[i][j] - array[k]);
if (abs < temp) {
index = k;
temp = abs;
}
}
newImage[i][j] = array[index];
}
}
System.out.println("经过K近邻滤波后的图片为:");
System.out.println(Arrays.deepToString(newImage));
return 0;

} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}