java.lang.IllegalArgumentException:每个像素有多个组件

时间:2012-11-08 04:22:43

标签: java image-processing illegalargumentexception

我是Java新手。我正在尝试将两个图像与下面的代码进行比较,并在代码后面获取消息。任何帮助是极大的赞赏。感谢。

    BufferedImage imgOrig = ImageIO.read(new URL(imgOrigUrl));
    BufferedImage imgComp = ImageIO.read(new URL(imgCompUrl));                

    byte[] pixelsOrig = ((DataBufferByte) imgOrig.getRaster().getDataBuffer()).getData();
    byte[] pixelsComp = ((DataBufferByte) imgComp.getRaster().getDataBuffer()).getData();

    //System.out.println("Number of pixels orig:"+pixelsOrig.length);
    //System.out.println("Number of pixels comp:"+pixelsComp.length);

    ColorModel cmImgOrig = imgOrig.getColorModel();
    ColorModel cmImgComp = imgComp.getColorModel();

    int sum1 = 0;
    int sum2 = 0;
    for(int i:pixelsOrig){
        System.out.println(cmImgOrig.getGreen(i));  //ERROR OCCURS HERE
        //System.out.println(i);
    }

ERROR:

Testcase: testCompareImages(com.myapp.img.compare.service.CompareServiceTest):  Caused an ERROR
More than one component per pixel
java.lang.IllegalArgumentException: More than one component per pixel
    at java.awt.image.ComponentColorModel.getRGBComponent(ComponentColorModel.java:594)
    at java.awt.image.ComponentColorModel.getGreen(ComponentColorModel.java:675)
    at com.scottmacri.img.compare.service.CompareService.compareImages(CompareService.java:42)
    at com.scottmacri.img.compare.service.CompareServiceTest.testCompareImages(CompareServiceTest.java:45)

2 个答案:

答案 0 :(得分:1)

就像@Nathan Villaescusa所说,你正在使用的方法是期待单一频道。你需要字节数组还是颜色通道?如果您只需要颜色组件,则可以执行以下操作:

BufferedImage imgOrig = ImageIO.read(new URL(imgOrigUrl));
BufferedImage imgComp = ImageIO.read(new URL(imgCompUrl));

for (int y = 0; y < imgOrig.getHeight(); y++)
{
   for (int x = 0; x < imgOrig.getWidth(); x++)
   {
      System.out.println(imgOrig.getRGB(x, y) >> 8 & 0xff);
   }
}

其中getRGB(x,y)返回的int可以移位以获取RGB和alpha组件,如下所示:

int a = rgb >> 32 & 0xff;
int r = rgb >> 16 & 0xff;
int g = rgb >> 8 & 0xff;
int b = rgb & 0xff;

答案 1 :(得分:0)

看起来错误正在抛出,因为ColorSpace有超过1个组件,但您只传递一个值进行检查。

您希望使用接受getGreen()的ColorComponentModel的Object方法,而不是接受int的方法。我认为接受int的方法是用于灰度。

根据this answer,以下是使用此方法获取像素数据的方法:

Raster r = imgOrig.getData();    
SampleModel sm = r.getSampleModel();
int width = sm.getWidth();
int height = sm.getHeight();
for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        Object pixel = sm.getPixel(x, u, (int[])null, r.getDataBuffer());        
        System.out.println(cmImgOrig.getGreen(pixel));
    }
}