繁体   English   中英

Java直方图均衡 - 无法从图像光栅获取像素

[英]Java Histogram Equalisation - Can't get Pixel from Image Raster

我一直在做直方图均衡化方法。 我已经用这个问题作为基础来构建。 但是我无法运行此代码,Google在帮助我找到问题方面没有太大帮助。 我传入一个JPG BufferedImage对象。 我首先显示图像,以便看到我正在使用的内容然后处理它。 然而它始终在行int valueBefore=img.getRaster().getPixel(x, y,iarray)[0]; 而且我不确定为什么。 我得到的错误是Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1但是我看不出为什么会出现这个错误,图片就在那里并且充满了像素!

public BufferedImage hisrogramNormatlisation(BufferedImage img) {
        // To view image we're working on
        JFrame frame = new JFrame();
        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(new JLabel(new ImageIcon(img)));
        frame.pack();
        frame.setVisible(true);

        int width =img.getWidth();
        int height =img.getHeight();
        int anzpixel= width*height;
        int[] histogram = new int[255];
        int[] iarray = new int[1];
        int i =0;

        // Create histogram
        for (int x = 50; x < width; x++) {
            for (int y = 50; y < height; y++) {
                int valueBefore=img.getRaster().getPixel(x, y,iarray)[0];
                histogram[valueBefore]++;
                System.out.println("here");
            }
        }

         int sum = 0;

         float[] lut = new float[anzpixel];
         for ( i=0; i < 255; ++i )
         {
             sum += histogram[i];
             lut[i] = sum * 255 / anzpixel;
         }

         i=0;
         for (int x = 1; x < width; x++) {
             for (int y = 1; y < height; y++) {
                 int valueBefore=img.getRaster().getPixel(x, y,iarray)[0];
                 int valueAfter= (int) lut[valueBefore];
                 iarray[0]=valueAfter;
                  img.getRaster().setPixel(x, y, iarray); 
                  i=i+1;
             }
         }
         return img;
    }

错误说明:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at java.awt.image.ComponentSampleModel.getPixel(ComponentSampleModel.java:n)
    at java.awt.image.Raster.getPixel(Raster.java:n)
    at MainApp.hisrogramNormatlisation(MainApp.java: * line described *)
    at MainApp.picture(MainApp.java:n)
    at MainApp.<init>(Main.java:n)
    at MainApp.main(Main.java:n)

您发布的堆栈跟踪表明您的超出范围索引为1.在您认为的情况下,不会抛出异常。 getPixel(int x,int y,int [] iarray)使用像素的强度值填充iarray。 如果您使用的是rgb图像,则每个通道至少会有三个强度值,如果您使用带有alpha的rgb,则会有4个强度值。 你的iarray只有1,所以当raster想要访问更多元素来存储附加值时,会抛出IndexOutOfBoundsException。 增加iarray的大小,异常就会消失。

不要使用getPixel(),而是使用getSample()。

所以你的代码是: final int valueBefore = img.getRaster().getSample(x, y, 0) ; 甚至histogram[img.getRaster().getSample(x, y, 0)]++ ;

顺便说一下,您可能需要先检查图像类型,以确定通道/波段的数量,并为每个通道执行此过程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM