Measuring Contrast of an Image using Python

Viewed 2152

I have a code for brightness, and im currently looking into measuring contrast

from PIL import Image
from math import sqrt
imag = Image.open("../Images/noise.jpg")

imag = imag.convert ('RGB')
imag.show()

X,Y = 0,0

pixelRGB = imag.getpixel((X,Y))
R,G,B = pixelRGB
brightness = sum([R,G,B])/3 ##0 is dark (black) and 255 is bright (white)
print(brightness)
print(R,G,B)

Surely contrast could be something similiar to this code, any ideas would be great, thanks

1 Answers

Different folks have different ideas of contrast... one method is to look at the difference between the brightest and darkest pixel in the image, another is to look at the standard deviation of the pixels away from the mean. There are other statistics too. Note that it requires looking at all the pixels in the image - not just the first.

The simplest way to look at the statistics of an image is to use PIL's ImageStat function:

#!/usr/bin/env python3

from PIL import Image, ImageStat

# Load image
im = Image.open('image.png')

# Calculate statistics
stats = ImageStat.Stat(im)                                                                 

for band,name in enumerate(im.getbands()): 
    print(f'Band: {name}, min/max: {stats.extrema[band]}, stddev: {stats.stddev[band]}')

So, if I create a greyscale image like this with ImageMagick:

magick -size 1024x768 gradient:"rgb(64,64,64)-rgb(200,200,200)" -depth 8 image.png

and run the above code, I get:

Band: L, min/max: (64, 200), stddev: 39.31443755161709

If I create a magenta-black gradient:

magick -size 1024x768 gradient:magenta-black -depth 8 image.png

and run the code, I get:

Band: R, min/max: (0, 255), stddev: 73.68457550034924
Band: G, min/max: (0, 0), stddev: 0.0
Band: B, min/max: (0, 255), stddev: 73.68457550034924

If the min and max are close, the contrast is low. If the min and max are widely spaced, the contrast is high. Likewise the standard deviation, as it measures how "spread out" the pixels are across the histogram.

Related