Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of colors of images

Tags:

java

image

colors

I have three different images (jpeg or bmp). I'm trying to predict the complexity of each image based on the number of color of each. How could I make it possible with Java? Thank you.

UPDATE: These codes doesn't work .. the output shows 1312 colors even it only plain red and white

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");
    }
}
like image 581
Jessy Avatar asked Mar 01 '11 10:03

Jessy


1 Answers

The code is basically right, whereas too complicated. You could simply use a Set and add the int value to it, as existing values are ignored. You also don't need to calculate the RGB values for each color, as the int value returned by getRGB is unique by itself:

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");

The "strange" number of colors you are getting is owed to image compression (JPEG in your example) and maybe other reasons like anti-aliasing of your image editing software. Even if you paint only in red and white, the resulting image may contain a lot of colors in between of these two values on the edges.

That means the code will return the real count of colors used in a particular image. You might also want to have a look on the different image file formats and lossless and lossy compression algorithms.

like image 169
Chris Avatar answered Sep 29 '22 11:09

Chris