Making a RGB Histogram

More Topics

Applets and Native Methods.

Java Javascript interaction.

Undo / Redo for image processing

A histogram provides information about the statistical distribution of color in an image. Creating a three color histogram with JAI (Java Advanced Imaging is simple enough. If you are stuck with just Java 2D, you need to extract the histogram data from the image on your own, but as we shall see that's not too difficult either.

Before anything else, we need to select a file, for that we will use the familar old JFileChooser. Once a file is selected, there are virtually a hundred different ways in which it can be read into memory. You will see one of them below, feel free to use another approach if you feel like it.


        ImageInputStream is = ImageIO.createImageInputStream(file);
        Iterator iter = ImageIO.getImageReaders(is);
        
        if (!iter.hasNext())
        {
            System.out.println("Cannot load the specified file "+ file);
            System.exit(1);
        }
        ImageReader imageReader = (ImageReader)iter.next();
        imageReader.setInput(is);
        image = imageReader.read(0);


The BufferedImage class has a getRGB() method, but it returns just one integer and not three, so it cannot be used to build a three color histogram. The BufferedImage has a Raster and that Raster has a getSample() method which can return three separate values for Red, Green and Blue for any pixel. We can interate over the set of pixel to create a two dimensional array which we can use in our plot.


        height = image.getHeight();
        width = image.getWidth();
        
        Raster raster = image.getRaster();
        for(int i=0; i < width ; i++)
        {
            for(int j=0; j < height ; j++)
            {
                if(gray)
                {
                    bins[0][ raster.getSample(i,j, 0) ] ++;
                }
                else
                {
                    bins[0][ raster.getSample(i,j, 0) ] ++;
                    bins[1][ raster.getSample(i,j, 1) ] ++;
                    bins[2][ raster.getSample(i,j, 2) ] ++;
                }
            }
        }


Usually a color is represented by 8 bits, the above code records how often each value occurs with in the image. The two dimensional array that is produced is not different from what is produced by the histogram operator in Java advanced imaging. So let's plot it.

Digg!

Copyright © Raditha Dissanayake 2013