Could someone show me here how to access all the pixels of an image in order to be able to build a histogram of that image ?
You can use
java.awt.image.BufferedImage image = ImageIO.read( "image.gif" );
int[] samples = image.getData().getPixel( x, y, null );
// or the pixel converted to the default RGB color model:
int rgb = image.getRGB( x, y )
I think the samples
you get from there are the RGB values, but you have to check that...
If you can use JAI it has options to generate Histograms.
Here's some example code that might help - please test this (it seems to work for me, but you never know!).
This histograms aren't equalized or anything here, just literally counting up the pixel of a particular value in each band.
I believe the bands (you would need to check) are R,G,B + Alpha in that order.
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import javax.imageio.ImageIO;
public class SimpleImageReader {
public static void main(String[] args) throws Exception {
// File f=new File(args[0]);
File f=new File("C:\\1.jpg");
BufferedImage img = ImageIO.read(f);
Raster r=img.getData();
int levels=256;
int bands=r.getNumBands();
int histogram[][]=new int[bands][levels];
for (int x=r.getMinX();x<r.getWidth();x++) {
for (int y=r.getMinY();y<r.getHeight();y++) {
for (int b=0;b<3;b++) {
int p=r.getSample(x, y, b);
histogram[b][p]++;
}
}
}
for (int b=0;b<histogram.length;b++) {
System.out.println("Band:"+b);
for (int i=0;i<histogram[b].length;i++) {
System.out.println("\t"+i+"="+histogram[b][i]);
}
}
}
}
精彩评论