2012-11-08 63 views
1

我是Java中圖像處理的新手。我試圖將兩張圖片與下面的代碼進行比較,然後根據代碼獲取消息。任何幫助是極大的讚賞。謝謝。java.lang.IllegalArgumentException:每像素多於一個組件

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) 

回答

0

看起來這個錯誤被拋出,因爲你的ColorSpace有超過1種成分,但你只能傳遞一個值來檢查。

要使用ColorComponentModel的getGreen()方法接受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)); 
    } 
} 
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; 
相關問題