2011-03-01 85 views
6

我有三個不同的圖像(JPEG或BMP)。 我試圖根據每個圖像的顏色數來預測每個圖像的複雜程度。 我怎樣才能使Java成爲可能? 謝謝。計算圖像的顏色數

UPDATE: 這些代碼不工作..輸出顯示1312點的顏色甚至只純紅色和白色

import java.awt.*; 
import java.awt.image.BufferedImage; 
import java.io.*; 
import java.util.ArrayList; 

import javax.imageio.ImageIO; 

public class clutters { 
    public static void main(String[] args) throws IOException { 

     ArrayList<Color> colors = new ArrayList<Color>(); 

     BufferedImage image = ImageIO.read(new File("1L.jpg"));  
     int w = image.getWidth(); 
     int h = image.getHeight(); 
     for(int y = 0; y < h; y++) { 
      for(int x = 0; x < w; x++) { 
       int pixel = image.getRGB(x, y);  
       int red = (pixel & 0x00ff0000) >> 16; 
       int green = (pixel & 0x0000ff00) >> 8; 
       int blue = pixel & 0x000000ff;      
       Color color = new Color(red,green,blue);  

       //add the first color on array 
       if(colors.size()==0)     
        colors.add(color);   
       //check for redudancy 
       else { 
        if(!(colors.contains(color))) 
         colors.add(color); 
       } 
      } 
     } 
system.out.printly("There are "+colors.size()+"colors"); 
    } 
} 
+0

灰度圖像(只有256色)固有地比具有多達65,536色的彩色圖像圖像複雜度低? – 2011-03-09 15:45:08

+0

你想要構建的東西叫做直方圖。 – djdanlib 2011-04-20 14:31:02

回答

7

該代碼基本上是正確的,但太複雜。您可以簡單地使用Set並將int值添加到該值,因爲現有值將被忽略。你也不需要計算每種顏色的RGB值,由getRGB返回int值是唯一的本身:

Set<Integer> colors = new HashSet<Integer>(); 
    BufferedImage image = ImageIO.read(new File("test.png"));  
    int w = image.getWidth(); 
    int h = image.getHeight(); 
    for(int y = 0; y < h; y++) { 
     for(int x = 0; x < w; x++) { 
      int pixel = image.getRGB(x, y);  
      colors.add(pixel); 
     } 
    } 
    System.out.println("There are "+colors.size()+" colors"); 

的「奇怪」一些你得到是欠圖像壓縮顏色(在你的例子中JPEG),也可能是其他原因,如圖像編輯軟件的消除鋸齒。即使只用紅色和白色進行繪製,生成的圖像在邊緣上的這兩個值之間可能會包含很多顏色。

這意味着代碼將返回真實在特定圖像中使用的顏色數。您可能還想看看不同的圖像文件格式以及無損和有損壓縮算法。

+0

謝謝克裏克:) – Jessy 2011-03-10 00:46:52

0
BufferedImage bi=ImageIO.read(...); 
bi.getColorModel().getRGB(...);