计算图像的颜色数量

Jes*_*ssy 6 java image colors

我有三个不同的图像(jpeg或bmp).我试图根据每个图像的颜色数来预测每个图像的复杂程度.我怎么能用Java实现它呢?谢谢.

更新: 这些代码不起作用..输出显示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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 7

代码基本上是正确的,而过于复杂.您可以简单地使用a Set并将int值添加到它,因为忽略现有值.您也不需要计算每种颜色的RGB值,因为int返回的值getRGB本身是唯一的:

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");
Run Code Online (Sandbox Code Playgroud)

您获得的"奇怪"颜色数量归因于图像压缩(在您的示例中为JPEG)以及其他原因,如图像编辑软件的抗锯齿.即使您仅以红色和白色进行绘制,生成的图像也可能在边缘上的这两个值之间包含大量颜色.

这意味着代码将返回特定图像中使用的实际颜色数.您可能还想了解不同的图像文件格式以及无损和有损压缩算法.