EasyComputer Vision

Image Histogram

Computer Vision

Easy

Problem

Count grayscale pixel intensities and return a compact sparse histogram. Scan every pixel, count each intensity, then return only intensities that appear. Each output entry is a two-element list containing the intensity followed by its count. Sort entries by increasing intensity.

Theory

A histogram counts how many times each value appears in a dataset. For grayscale images, it counts how many pixels have each possible intensity value (0 to 255).

The histogram is a 1D array of 256 bins:


Why Histograms Matter

Image analysis:

Image processing:

Computer vision:


Computing a Histogram

Step 1: Initialize bins

Step 2: Iterate through pixels

Step 3: Result


Numerical Example

Small 4x4 image:

0 50 50 100 0 50 100 100 50 100 150 200 100 150 200 255

Counting:

Histogram (non-zero bins only):

Total: 2 + 4 + 5 + 2 + 2 + 1 = 16 (total pixels)


Interpreting Histograms

Dark image:

Bright image:

Low contrast:

High contrast:

Bimodal:


Normalized Histogram

A normalized histogram converts counts to probabilities:

p[i] = \frac{\text{histogram}[i]}{\text{total pixels}}

Properties:


Cumulative Histogram

The cumulative histogram counts pixels up to each intensity:

C[i] = \sum_{j=0}^{i} \text{histogram}[j]

Properties:


Applications

Automatic thresholding (Otsu's method):

Histogram equalization:

Histogram matching:

Exposure detection:


Color Histograms

For color images, compute separate histograms for each channel:

Or compute joint histogram:


Implementation Notes

Efficiency:

Memory:

Edge cases:

Examples

Example 1

Input
image = [[0, 1], [1, 2]]
Output
[[0, 1], [1, 2], [2, 1]]
Explanation
Intensities zero and two occur once, while intensity one occurs twice.

Example 2

Input
image = [[128, 128], [128, 128]]
Output
[[128, 4]]

Hints

  1. Use a 256-element count list or a dictionary while scanning the pixels.
  2. Build the result in increasing intensity order and skip zero counts.

Requirements

Constraints

Starter Code

def image_histogram(image: list) -> list:
    """
    Returns a list of intensity and count pairs.
    """
    # Write code here
    pass

Test Cases

CaseMatches
Simplepublic
All samepublic