1

我是 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);
    }

错误:

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)
4

2 回答 2

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;
于 2012-11-09T15:24:21.053 回答
0

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

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

根据这个答案,这里是如何使用这种方法获取像素数据:

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));
    }
}
于 2012-11-08T05:29:35.190 回答