← back

Grayscale Image Contrast Calculator

#82 · Computer Vision · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the contrast of a grayscale image. Given a 2D array of pixel values, compute the contrast as the difference between the maximum and minimum pixel intensities (range), or using RMS contrast.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import numpy as np

def image_contrast(image):
    image = np.array(image, dtype=float)

    # Michelson contrast or simple range contrast
    min_val = np.min(image)
    max_val = np.max(image)

    # RMS contrast
    mean_val = np.mean(image)
    rms_contrast = np.sqrt(np.mean((image - mean_val) ** 2))

    return round(float(rms_contrast), 4)

Explanation

  1. Convert the image to a float array for precise computation.
  2. Compute the mean pixel intensity across the entire image.
  3. RMS contrast = sqrt(mean((pixel - mean)^2)), which is the standard deviation of pixel values.
  4. Higher values indicate greater spread of intensities (more contrast).
  5. RMS contrast is preferred over simple range because it considers the full distribution of pixel values.

Complexity

  • Time: O(H * W) where H is height and W is width
  • Space: O(H * W) for the float conversion