Skip to content Skip to sidebar Skip to footer

How To Calculate The Contrast Of An Image?

Let's say I have an opencv BGR image img, how to calculate the contrast of that image?

Solution 1:

One definition of contrast is RMS Contrast, it can be calculated as follows:

First, transform the BGR image img to greyscale:

img_grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Lastly, calculate the standard deviation of the greyed image pixel intensities:

contrast = img_grey.std()

Solution 2:

Here is one measure of contrast: Michelson contrast and how to compute it in Python/OpenCV/Numpy. Low contrast is near zero and high contrast is near one. Use the Y (intensity) channel from YUV or YCbCr or alternately the L channel from LAB or even just convert the image to grayscale and use that.

Input:

enter image description here

import cv2
import numpy as np

# load image as YUV (or YCbCR) and select Y (intensity)# or convert to grayscale, which should be the same.# Alternately, use L (luminance) from LAB.
img = cv2.imread("barn.jpg")
Y = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)[:,:,0]

# compute min and max of Ymin = np.min(Y)
max = np.max(Y)

# compute contrast
contrast = (max-min)/(max+min)
print(min,max,contrast)
Returns:

0 255 1.0

The contrast will be between 0 and 1.

Post a Comment for "How To Calculate The Contrast Of An Image?"