2011-03-01 342 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(...);