我正在执行中值滤波器的程序。所有我试图完成的是取一个像素值,找到它的相邻像素,并将它们存储在一个数组中,对该数组进行排序,并取中间值(对于大小为9的中间值数组为索引位置4)。并在与考虑中的像素完全相同的坐标处代替该值。在WritableRaster中设置值时坐标不在边界
如果我删除它的内容并只输出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
& y
)循环遍历[i][j]
个像素的所有8个邻居。
我使用的图像有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?我在哪里错了?
在内部循环中,您可能会使用“x <= Math.min(i + 1,imageRaster.getWidth())”而不是“... x <=”来搜索图像的边缘。 imageRaster.getWidth() - 1“。 – Rethunk
@Rethunk我试图这样做,问题仍然存在 – md1hunox
糟糕,那根本就不是。不过,我认为我发现了这个问题。 – Rethunk