# Image Processing and Computer vision in java (Point Operators part 2)Histogram Equalization

Histogram Equalization: Histogram equalization is used to enhance the contrast of an image. to do this  first we have to know about histogram. Histogram is a representation of the distribution of data. So the histogram of an image represents how the pixel values are distributed. take a look at the image array below

here we can see pixel value 170 appears 4 times and 68 appears 3 times and so on. To get the histogram of an image we have to calculate which value appears how many times in the image. to calculate histogram we can use the code snippet below

```public int[] CalculateHist(BufferedImage img) {
int k;
int pixel[];
//array represents the intecity values of the pixels
int levels[] = new int[256];
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
pixel = img.getRaster().getPixel(i, j, new int[3]);
//increase if same pixel appears
levels[pixel[0]]++;
}
}
//return the histogram array
return levels;
}```

In the right side of the image is a graphical representation of its histogram. In the X-direction of the graph is the intensity values of the image and in the Y-direction of the image is the number of repetition of the values. We can see most of the pixel values are concentrated in brighter region for that the darker region is not clear. In histogram equalization basically what we do is to distribute the values uniformly. To do this we first calculate the PMF(probability mass function) from the histogram and then calculate the CDF(cumulative distribution function) and multiply it with (I-1) where I is the maximum intensity value. We can use the following formulas

So the first formula calculate the cumulative distribution of the histogram and second formula calculate equalization. If we apply this to the first image we will get

The java code for Histogreme equalization is given below

```public void histEqualize(BufferedImage img) {
//call CalculateHist method to get the histogram
int[] h = CalculateHist(img);
//calculate total number of pixel
int mass = img.getWidth() * img.getHeight();
int k = 0;
long sum = 0;
int pixel[];
//calculate the scale factor
float scale = (float) 255.0 / mass;
//calculte cdf
for (int x = 0; x < h.length; x++) {
sum += h[x];
int value = (int) (scale * sum);
if (value > 255) {
value = 255;
}
h[x] = value;
}
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
pixel = img.getRaster().getPixel(i, j, new int[3]);
//set the new value
k = h[pixel[0]];
Color color = new Color(k, k, k);
int rgb = color.getRGB();
img.setRGB(i, j, rgb);
}
}
}```

Input Image:

Output Image:

Phew we are done with point operators next we will talk about pixel neighborhood and filtering.

## 2 thoughts on “Image Processing and Computer vision in java (Point Operators part 2)Histogram Equalization”

1. well written. Looking forward to next write-ups.