I have to write a program that replaces each pixel with the median value of it and its 8 neighbors. What I have will compile but when i try to create a new image im getting multiple errors. Help is appreciated.
Here's the stacktrace:
Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:290)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:171)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at ImageProcessing.median(ImageProcessing.java:25
And here's my code:
public static int [] [] median(int [] [] image) {
int height = image.length;
int width = image[0].length;
int [] [] result = new int [height] [width];
for (int col = 0 ; col < image.length ; col++) {
result[0][col] = image[0][col];
result[height - 1][col] = image[height - 1][col];
}
for (int row = 0 ; row < image[0].length ; row++) {
result[row][0] = image[row][0];
result[row][width - 1] = image[row][width - 1];
}
for (int row = 1 ; row < height - 1 ; row++) {
for (int col = 1 ; col < width - 1 ; col++) {
Arrays.sort(image);
result[row][col] = image[row][col] / 2;
}
}
return result;
}
The error you are getting is because in the last pair of loops, your call to Arrays.sort(image)
is attempting to sort the rows of the image.
Instead of calling Arrays.sort(image)
, you'll need to build up a list of the nine pixel values you want to look at (the pixel itself and its eight neighbors). Then sort that, and write the median value to result
.