我正在做一个关于中值滤波器的程序。我想要完成的只是获取一个像素值,找到它的相邻像素,并将它们存储在一个数组中,对该数组进行排序,然后取中间值(对于大小为 9 的数组,中间值是索引位置 4)。并将该值替换为与所考虑的像素完全相同的坐标。
如果我删除其内容并仅打印i,j,x,y
. 在我添加我做的语句的那一刻,我neighborhoodVal.add(imageRaster.getSample(x, y, 0));
得到了一个java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
错误。
根据我的观察,我发现当值j
变为1
时i
变为值264
,这很奇怪,因为我只循环图像内的所有像素,外部两个循环(i 和 j)循环除边缘之外的所有像素的图像。内部循环 ( x
& ) 循环遍历第 th 个像素y
的所有 8 个邻居。[i][j]
我使用的图像有width = 265
和height=269
。代码如下:
public class MedianFilter {
public static void main(String[] args) throws IOException {
int i, j, x, y;
ArrayList<Integer> neighborhoodVal = new ArrayList<Integer>();
;
String imagePath = "images/assignment10/noisyShapes.jpg";
BufferedImage inputImage = convertToGrayScale(ImageIO.read(new File(
imagePath)));
WritableRaster imageRaster = inputImage.getRaster();
BufferedImage filteredImage = new BufferedImage(inputImage.getWidth(),
inputImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
WritableRaster newWRaster = filteredImage.getRaster();
for (i = 1; i < imageRaster.getHeight()-1; i++) {
for (j = 1; j < imageRaster.getWidth()-1; j++) {
for (x = Math.max(0, i - 1); x <= Math.min(i + 1,imageRaster.getWidth()); x++) {
for (y = Math.max(0, j - 1); y <= Math.min(j + 1,imageRaster.getHeight()); y++) {
System.out.println(i+","+j+"------->"+x+","+y);
neighborhoodVal.add(imageRaster.getSample(x, y, 0));
Collections.sort(neighborhoodVal);
}
}
newWRaster.setSample(i, j, 0, (neighborhoodVal
.get((neighborhoodVal.size() / 2) + 1)));
neighborhoodVal.clear();
}
}
File f = new File("images/assignment10/medianFilterOutput.jpg");
ImageIO.write(filteredImage, "JPG", f);
}
public static BufferedImage convertToGrayScale(BufferedImage givenImage)
throws IOException {
// TODO Auto-generated method stub
BufferedImage image = new BufferedImage(givenImage.getWidth(),
givenImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics grp = image.getGraphics();
grp.drawImage(givenImage, 0, 0, null);
return image;
}
}
我正在使用这张图片:
怎么j
变成1了?我在哪里错了?