Digital Image Processing is a significant aspect of data science. It is used in image modification and enhancement so we can acquire image attributes that lead to a greater understanding of data.
An image is made up of elements called pixels; the smallest pieces of information.
Pixels are arranged in a two-dimensional manner and are represented using squares.
An image histogram is a representation of the range of tonal values that is present in an image.
The y-axis represents the gray level intensities, while the x-axis represents the frequency that corresponds to those respective intensities.
The x-axis depends on the number of bits used to store the image.
If 8 bits are used, the range will be from 0 to 255, making up a total of 256 intensity levels. This is usually the case with modern-day images.
We can determine a multitude of attributes of an image by looking at its histogram. If the bars are concentrated towards the left side of the histogram, it means that the image is on the darker side. Likewise, bars concentrated on the right side mean that the image is lighter.
Another attribute we can determine is the overall contrast of the image. If the bars are closer together over a low range of pixel values, the image contrast is low. If they are spread out over the x-axis, the contrast is high. The histogram below depicts a low contrast image:
A histogram of an image is plotted by making two lists:
The
matplotlib
library is used to plot the histogram.
Let’s look at the following code snippet:
#import librariesimport PILfrom PIL import Imageimport matplotlib.pyplot as plt#function to plot histogramdef histogram(img):pixels=[]#create list of values 0-255for x in range(256):pixels.append(x)#initialize width and height of imagewidth,height=img.sizecounts=[]#for each intensity valuefor i in pixels:#set counter to 0temp=0#traverse through the pixelsfor x in range(width):for y in range(height):#if pixel intensity equal to intensity level#increment counterif (img.getpixel((x,y))==i):temp=temp+1#append frequency of intensity levelcounts.append(temp)#plot histogramplt.bar(pixels,counts)plt.show()
In the example above, we have a function named histogram(img)
. This function takes an image as a parameter and plots a histogram for that image. It does so using the two lists corresponding to pixels (pixels
) and the intensity (count
) of those pixels.