0 votes
in Python Imaging Library by
Explain how to use PIL to create a histogram of an image.

1 Answer

0 votes
by
To create a histogram of an image using PIL, first import the Image module from PIL. Then load your image file by calling Image.open() with the path to your image as argument. Convert the image to grayscale for simplicity using convert(‘L’). Now, call .histogram() on the image object which returns a list representing the frequency distribution of pixel values in the image. This can be plotted using matplotlib’s pyplot.hist(). Here is a code example:

from PIL import Image

import matplotlib.pyplot as plt

# Load and convert image

img = Image.open('image.jpg').convert('L')

# Create histogram

hist_data = img.histogram()

# Plot histogram

plt.hist(hist_data, bins=256, color='gray', alpha=0.7)

plt.show()
...