v9.1.1
Menu

Otsu's Threshold

hardPROImage ProcessingComputer Vision 1

Implement Otsu's method to find the optimal binarization threshold that maximizes between-class variance.

Given a list of pixel intensities (values 0-255), find the threshold tt that best separates the pixels into two classes (foreground and background) by maximizing the between-class variance σB2\sigma_B^2.

Algorithm:

For each candidate threshold tt from 0 to 255:

  1. Class probabilities:

    • w0(t)=∑i=0tp(i)w_0(t) = \sum_{i=0}^{t} p(i) (background weight)
    • w1(t)=∑i=t+1255p(i)w_1(t) = \sum_{i=t+1}^{255} p(i) (foreground weight)
  2. Class means:

    • μ0(t)=∑i=0ti⋅p(i)w0(t)\mu_0(t) = \frac{\sum_{i=0}^{t} i \cdot p(i)}{w_0(t)}
    • μ1(t)=∑i=t+1255i⋅p(i)w1(t)\mu_1(t) = \frac{\sum_{i=t+1}^{255} i \cdot p(i)}{w_1(t)}
  3. Between-class variance: σB2(t)=w0(t)⋅w1(t)⋅(μ0(t)−μ1(t))2\sigma_B^2(t) = w_0(t) \cdot w_1(t) \cdot (\mu_0(t) - \mu_1(t))^2

  4. The optimal threshold maximizes σB2(t)\sigma_B^2(t).

where p(i)p(i) is the probability of intensity ii (histogram normalized by total pixel count).

Return the threshold value (integer) that maximizes σB2\sigma_B^2.

Example

Input
pixels = [0, 0, 0, 0, 0, 255, 255, 255, 255, 255]
num_bins = 256
Output
0
Reasoning
  • pixels holds 10 intensities: five at 00 (black) and five at 255255 (white). num_bins is 256256, one bin per possible intensity. Normalising the counts gives p(0)=510=0.5p(0) = \frac{5}{10} = 0.5, p(255)=0.5p(255) = 0.5, and p(i)=0p(i) = 0 for every other ii.
  • At t=0t = 0 the background class is {0}\{0\} and the foreground is {255}\{255\}: w0=0.5w_0 = 0.5, w1=0.5w_1 = 0.5, μ0=0\mu_0 = 0, μ1=255\mu_1 = 255.
  • So σB2(0)=0.5⋅0.5⋅(0−255)2=0.25⋅65025=16256.25\sigma_B^2(0) = 0.5 \cdot 0.5 \cdot (0 - 255)^2 = 0.25 \cdot 65025 = 16256.25.
  • Now try t=1,2,…,254t = 1, 2, \dots, 254. No pixel lies in 1..2541..254, so every one of these thresholds produces exactly the same two classes and the same σB2=16256.25\sigma_B^2 = 16256.25. At t=255t = 255 the foreground is empty (w1=0w_1 = 0), so μ1\mu_1 is undefined and that split is not a candidate.
  • Notice that 255 thresholds tie for the maximum. The tie rule in the constraints (return the smallest) is what makes the answer 0, not anything special about t=0t = 0 itself.

Constraints

  • Input: List of pixel intensities (integers 0-255), number of bins (256)
  • Return: Optimal threshold as an integer
  • If multiple thresholds give the same maximum variance, return the smallest
  • Use pure Python (no numpy)
  • At least 2 distinct intensity values in the input

More from Computer Vision 1

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.