Saturday, November 2, 2024

How do you visualize the histogram of an image?

A picture is worth a thousand words is always true. A one dimensional array does not make a great deal of impact but a visual will do. 

In the previous post on histograms we saw that PIL and OpenCV can be used to provide a 1-dimensional array representing the frequency of each pixel value in the image. We can use the library matplotlib to visualize this array using the following code.

---------------------------

import cv2

import matplotlib.pyplot as plt

image=cv2.imread(r'C:\Users\hoden\PycharmProjects\exploreImage\Images_3\white.png')

histogram = cv2.calcHist([image], [0], None, [256], [0, 256])


# Plot the histogram

plt.plot(histogram)

plt.title('Histogram of an all-white image')

plt.xlabel('Pixel Intensity')

plt.ylabel('Frequency')

plt.show()

------------------------

When we run this code in PyCharm, the a graphic of the Histogram will be displayed. Here is the result of running the above code twice in PyCharm. Matplotlib is pretty flexible and allows us to illustrate the plots with labels.







No comments: