Otsu's Threshold

~16 mincode completion

Implement otsu_threshold(hist).

  • hist is a 1D array of pixel counts, index = grey level.
  • Return the integer threshold with levels in class 0.

Examples

Two clusters at the ends: the split is after level 1

Input
otsu_threshold([4, 1, 0, 0, 1, 4])
Output
1

A flat histogram over 8 levels splits in the middle

Input
otsu_threshold([1, 1, 1, 1, 1, 1, 1, 1])
Output
3

A dark road and a few bright pixels: the threshold sits just above the dark mass

Input
otsu_threshold([10, 2, 0, 0, 0, 1, 1])
Output
1

Hints

Hint 1

Loop a fixed number of times and update the running value each pass.

Hint 2

A common slip here: maximised within class variance instead of between.

Requirements

  • hist: 1D array of counts, hist[v] = number of pixels at level v

  • Return integer t that maximises between-class variance (smallest on ties)

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~16 min

8 employers weight this skill

4 autonomy companies, 1 defense company, 1 health and bio company, 1 enterprise vendor, 1 AI product company. Top match scores 81.

Python
import numpy as np


def otsu_threshold(hist):
    """
    Otsu's threshold from a histogram.

    Args:
        hist: 1D array of counts, hist[v] = number of pixels at level v

    Returns:
        integer t that maximises between-class variance (smallest on ties)
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.