Python

# Programmingempire

In this article on Image Contrast Enhancement using Histogram Equalization, I will explain the significance of Histogram Equalization. Basically, Histogram Equalization is an image processing technique.

A histogram represents the intensity distribution of an image graphically. Therefore, it contains the quantified value of the number of pixels representing each intensity value.

Accordingly, Histogram Equalization (HE) broadens the intensity range. Therefore, it maps one intensity distribution to another, thereby making intensity values evenly distributed. In other words, it spreads out the most frequent intensity values. As a result, it improves the contrast in the image.

### Applications of Histogram Equalization

Since, histogram equalization is an image processing technique to improve the image contrast, it has many applications. In fact, we use it before further processing of an image. For instance, it is used widely in medical image processing. For instance, the visibility of many X-ray images are increased after histogram equalization. Because, the resulting image has better contrast. Besides X-rays, it is also used to enhance the quality of images from MRIs and CT-Scans.

Moreover, we can use histogram equalization as a pre-processing step in a Deep Learning application. For instance, we can use it in plant disease prediction. Because, it adds more visibility to the details of the image, the learning becomes faster. Additionally, many surveillance applications also require better contrast. Hence, we can use histogram equalization in a variety of image processing and deep learning applications.

### Performing Image Contrast Enhancement using Histogram Equalization with OpenCV

In order to perform histogram equalization on an image, we need certain functions from the python library. The following section discusses these functions in brief.

#### histogram() Function in NumPy Package

Since we need to visualize the frequency distribution in data we use this function. In this example, the data is an image for which we wish to plot the frequency distribution. Further, the class intervals are called bins. For instance, in our example, we provide the image as data, the number of bins as 256, and the range of bins from 0 to 255. Because, the range of intensity fall between 0 and 255 in case of a grey image. As a result of this function call, it returns two values – an array of values and bin edges. However, for the graphical display of the histogram, we can use the hist() function of matplotlib package.

#### flatten()

Since the flattening operation transforms a multi-dimensional array into a single-dimensional array, it reduces the memory requirement.

#### cumsum()

Basically, the above function computes the cumulative sum of elements of the histogram array. After that, we normalize the cumulative distribution graph. Once the data is normalized, we can plot the histogram using the hist() function of matplotlib.

#### hist()

Apart from the histogram() function of the NumPy package, we also need a hist() function to draw the plot. While, histogram() function returns an array of values corresponding to the histogram, the hist() function draws a plot. Further, the hist() function is available in pyplot module of the matplotlib package.

#### equalizeHist()

This function allows us to equalize the intensity values of the given image. Hence, by applying the equalizeHist() function on a given in=mage, we get another with with uniform intensity distribution.

### Example of Histogram Equalization

Now that, the histogram equalization is explained, let us write a program to show how does it work. At first, we import the necessary packages as shown below.

``````#importing the required packages
import cv2 as c1
import numpy as np
import matplotlib.pyplot as plt``````

After that, we read an image file and convert it into a greyscale image. The following code shows it.

``````#read an display the image file
x = c1.imread('j5.jpg')
c1.imshow('Original image', x)

#Convert into greyscale image
x = c1.cvtColor(x, c1.COLOR_BGR2GRAY)``````

Once we have the given image in memory, we can create a histogram and display it as shown below. As can be seen, before creating the histogram, we need to flatten the image so that it is transformed into a one-dimensional array. Further, we compute a cumulative sum of histogram array. Also, we normalize the cumulative sum.

``````#Create a histogram array
hist1, bins1=np.histogram(x.flatten(), 256, [0, 256])
print(hist1)
#find the cumulative sum
cms=hist1.cumsum()
print(cms)
#Normalize the cumulative sum
cms_n=cms*float(hist1.max())/cms.max()
print(cms_n)``````

After that we can plot the histogram as shown below.

``````
#Plotting the histogram
plt.plot(cms_n, color='b')
plt.hist(x.flatten(), 256, [0, 256], color='r')
plt.show()``````

#### Code for Equalization

Subsequently, we apply the equalizeHist() function on our greyscale image. As a result, we get an image with better contrast. Further, we also create a histogram and plot it for the resulting image. The following code shows it.

``````#Histogram Equalization and its plot
y = c1.equalizeHist(x)
hist1, bins1=np.histogram(y.flatten(), 256, [0, 256])
cms=hist1.cumsum()
cms_n=cms*float(hist1.max())/cms.max()
plt.plot(cms_n, color='b')
plt.hist(y.flatten(), 256, [0, 256], color='r')
plt.show()``````

Once, we apply the histogram equalization, we can display the resulting image with enhanced contrast. The complete code is shown below.

``````#importing the required packages
import cv2 as c1
import numpy as np
import matplotlib.pyplot as plt

#read an display the image file
z = c1.imread('j4.jpg')

#Convert into greyscale image
x = c1.cvtColor(z, c1.COLOR_BGR2GRAY)

#Create a histogram array
hist1, bins1=np.histogram(x.flatten(), 256, [0, 256])
print('Histogram array...')
print(hist1)
#find the cumulative sum
cms=hist1.cumsum()
print('Cumulative Sum...')
print(cms)
#Normalize the cumulative sum
cms_n=cms*float(hist1.max())/cms.max()
print('Normalized sum...')
print(cms_n)

#Plotting the histogram
plt.plot(cms_n, color='b')
plt.hist(x.flatten(), 256, [0, 256], color='r')
plt.show()

#Histogram Equalization and its plot
y = c1.equalizeHist(x)
hist1, bins1=np.histogram(y.flatten(), 256, [0, 256])
print('Histogram array...')
print(hist1)
cms=hist1.cumsum()
print('Cumulative Sum...')
print(cms)
cms_n=cms*float(hist1.max())/cms.max()
print('Normalized sum...')
print(cms_n)
plt.plot(cms_n, color='b')
plt.hist(y.flatten(), 256, [0, 256], color='r')
plt.show()

#stacking images
w=np.hstack((x, y))
c1.imshow('Original Image', z)
c1.imshow('Transformed Images', w)
c1.waitKey()``````

Output

Evidently, the final output images have more contrast as it is clearly visible.

As can be seen in the output, both the original and equalized histograms look as given below.

Furthermore, the output also shows how intensity values are evenly distributed after the equalization.

To sum up, the histogram equalization is an important technique in image processing. In general, it improves the global contrast of an image. Hence, to improve the image contrast, it transforms the intensity values of the image. In fact, it creates uniform distribution of intensity values of the image. As a result, we get an improved image with better contrast. Besides, the basic method of histogram equalization, we have many other improved techniques. Soon, I will discuss these other techniques.

### Further Reading

Deep Learning Tutorial

Text Summarization Techniques

How to Implement Inheritance in Python

Find Prime Numbers in Given Range in Python

Running Instructions in an Interactive Interpreter in Python

Deep Learning Practice Exercise

Python Practice Exercise

Deep Learning Methods for Object Detection

Understanding YOLO Algorithm

What is Image Segmentation?

ImageNet and its Applications

Image Contrast Enhancement using Histogram Equalization

Transfer Learning and its Applications

Examples of OpenCV Library in Python

Examples of Tuples in Python

Python List Practice Exercise

Understanding Blockchain Concepts

Edge Detection Using OpenCV

Predicting with Time Series

Example of Multi-layer Perceptron Classifier in Python

Measuring Performance of Classification using Confusion Matrix

Artificial Neural Network (ANN) Model using Scikit-Learn

Popular Machine Learning Algorithms for Prediction

Long Short Term Memory – An Artificial Recurrent Neural Network Architecture

Python Project Ideas for Undergraduate Students

Creating Basic Charts using Plotly

Visualizing Regression Models with lmplot() and residplot() in Seaborn

Data Visualization with Pandas

A Brief Introduction of Pandas Library in Python

A Brief Tutorial on NumPy in Python

Python

Python