v9.1.1
Menu

Image Histogram Equalization

mediumFREEWhat is Computer Vision?Image ProcessingCV: Introduction to Computer Vision

Implement histogram equalization to enhance image contrast using NumPy.

Histogram equalization redistributes pixel intensities to achieve a more uniform histogram, improving contrast in images with concentrated intensity ranges.

Algorithm:

  1. Compute histogram h[i]h[i] = count of pixels with intensity ii
  2. Compute cumulative distribution function: CDF[i]=∑j=0ih[j]CDF[i] = \sum_{j=0}^{i} h[j]
  3. Normalize CDF to range [0, 255]: CDFnorm[i]=CDF[i]−CDFmin(M×N)−CDFmin×255CDF_{norm}[i] = \frac{CDF[i] - CDF_{min}}{(M \times N) - CDF_{min}} \times 255
  4. Map each pixel: output[x,y]=CDFnorm[input[x,y]]output[x,y] = CDF_{norm}[input[x,y]]

Where M×NM \times N is the total number of pixels and CDFminCDF_{min} is the minimum non-zero CDF value.

Edge cases:

  • If every pixel has the same intensity, the denominator (M×N)−CDFmin(M \times N) - CDF_{min} is 0; in that case return an image of the same shape filled with 255.
  • Fractional normalized values are truncated (rounded down) to integers.

Example

Input
image = [[50, 50], [50, 50]]
Output
[[255, 255], [255, 255]]
Reasoning
  • Input: image is a 2×22 \times 2 grayscale image, each entry an intensity in [0,255][0, 255]. Here all four pixels are 50, so M×N=4M \times N = 4.
  • Histogram: only intensity 50 occurs, so h[50]=4h[50] = 4 and h[i]=0h[i] = 0 for every other ii.
  • CDF: CDF[i]=0CDF[i] = 0 for i<50i < 50 and CDF[i]=4CDF[i] = 4 for i≥50i \ge 50. The smallest non-zero value is CDFmin=4CDF_{min} = 4.
  • Normalize: CDFnorm[50]=4−44−4×255=00CDF_{norm}[50] = \frac{4 - 4}{4 - 4} \times 255 = \frac{0}{0}, which is undefined. A single-intensity image has no range to stretch, so the edge-case rule applies and every pixel becomes 255.
  • Output: [[255, 255], [255, 255]], the same 2×22 \times 2 shape, all integers.
  • Notice: with more than one intensity, the darkest present value always maps to 0 and the brightest to 255. For pixels 10, 20, 20, 30 the CDF values are 1, 3, 4, giving 03,23,33\frac{0}{3}, \frac{2}{3}, \frac{3}{3} of 255, i.e. 0, 170, 255.

Constraints

  • image: 2D numpy array with values in [0, 255]
  • Return: Equalized image with same shape, values in [0, 255]
  • Output values should be integers

Learn this in

More from CV: Introduction to Computer Vision

solution.py

Test results

Sign in to run your code against the test cases.