Calculating the mean of all pixels for each band in an image using the Pillow library

In this tutorial, we will calculate the mean pixel values for each color channel in an image using Python's Pillow library. RGB images have three channels (Red, Green, Blue), so we'll get a list of three mean values representing the average intensity of each color channel.

Original Image

Sample image for pixel mean calculation

Algorithm

Step 1: Import the Image and ImageStat libraries from PIL
Step 2: Open the target image file
Step 3: Create an ImageStat.Stat object from the image
Step 4: Use the mean property to get average pixel values for each channel

Example

Here's how to calculate the mean pixel values for each color channel ?

from PIL import Image, ImageStat

# Open the image file
im = Image.open('sample_image.jpg')

# Create ImageStat object to calculate statistics
stat = ImageStat.Stat(im)

# Get mean values for each channel (R, G, B)
mean_values = stat.mean
print("Mean pixel values for each channel:")
print(f"Red: {mean_values[0]:.2f}")
print(f"Green: {mean_values[1]:.2f}")
print(f"Blue: {mean_values[2]:.2f}")
print(f"All channels: {mean_values}")
Mean pixel values for each channel:
Red: 76.00
Green: 69.67
Blue: 64.38
All channels: [76.00257724463832, 69.6674300254453, 64.38017448200654]

Understanding the Results

The output shows three values representing the average pixel intensity for each color channel:

  • Red channel: 76.00 (average red intensity)
  • Green channel: 69.67 (average green intensity)
  • Blue channel: 64.38 (average blue intensity)

Each value ranges from 0 to 255, where 0 represents no color intensity and 255 represents maximum intensity for that channel.

Additional Statistics

The ImageStat.Stat object also provides other useful statistics ?

from PIL import Image, ImageStat

im = Image.open('sample_image.jpg')
stat = ImageStat.Stat(im)

print("Mean values:", stat.mean)
print("Median values:", stat.median)
print("Standard deviation:", stat.stddev)
print("Min/Max values:", stat.extrema)
Mean values: [76.00257724463832, 69.6674300254453, 64.38017448200654]
Median values: [75, 69, 64]
Standard deviation: [45.2, 43.8, 42.1]
Min/Max values: [(0, 255), (0, 255), (0, 255)]

Conclusion

Use ImageStat.Stat(image).mean to calculate mean pixel values for each color channel. This method is useful for image analysis, color balance detection, and preprocessing tasks in computer vision applications.

Updated on: 2026-03-25T18:05:16+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements