NumPy Histogram For Pixel Intensity

  • Read
  • Discuss

A histogram is a graphical representation of the distribution of a dataset. In image processing, histograms are often used to analyze the distribution of pixel intensity values within an image. We can understand the overall brightness, contrast, and color balance by analyzing an image’s histogram.

In this article, we will explore how to create a histogram for pixel intensity values using the NumPy library in Python.

Display an image

First, let’s start by reading an image using the OpenCV library and displaying it using matplotlib:

import cv2
import matplotlib.pyplot as plt

# Read the image
img = cv2.imread("garden.jpeg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Display the image

The following will be the output:


we can use the numpy.histogram() function to create a histogram of pixel intensity values.

The numpy.histogram() function takes in two arguments: the first is the image data, and the second is the number of bins to use in the histogram. The function returns two arrays: the first is the histogram values, and the second is the bin edges.

Flatten the Image

we use the ravel() function to flatten the image data into a 1D array, and we use 256 bins with a range of 0 to 256 for the pixel intensity values:

hist, bins = np.histogram(gray_img.ravel(), bins=256, range=(0,256))

Once we have the histogram values, we can use the  function to create a bar chart of the histogram.[:-1], hist, width = 1)
plt.xlim(min(bins), max(bins))

The following will be the output:

Leave a Reply

Leave a Reply

Scroll to Top