📘
Otsu's Threshold
HardImage Processing
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 t that best separates the pixels into two classes (foreground and background) by maximizing the between-class variance σB2.
Algorithm:
For each candidate threshold t from 0 to 255:
-
Class probabilities:
- w0(t)=∑i=0tp(i) (background weight)
- w1(t)=∑i=t+1255p(i) (foreground weight)
-
Class means:
- μ0(t)=w0(t)∑i=0ti⋅p(i)
- μ1(t)=w1(t)∑i=t+1255i⋅p(i)
-
Between-class variance: σB2(t)=w0(t)⋅w1(t)⋅(μ0(t)−μ1(t))2
-
The optimal threshold maximizes σB2(t).
where p(i) is the probability of intensity i (histogram normalized by total pixel count).
Return the threshold value (integer) that maximizes σB2.
Example:
Input:
pixels = [0, 0, 0, 0, 0, 255, 255, 255, 255, 255] num_bins = 256
Output:
0
Reasoning:
- The input list
pixelsis used to calculate the probability of each intensity i, which is p(i)=total number of pixelsnumber of pixels with intensity i. For the given input, p(0)=105=0.5 and p(255)=105=0.5. - The class probabilities w0(t) and w1(t) are calculated for each candidate threshold t. Since p(0)=0.5 and p(255)=0.5, when t=0, w0(t)=0.5 and w1(t)=0.5.
- The between-class variance σB2(t) is calculated for each t. For t=0, σB2(t)=w0(t)⋅w1(t)⋅(μ0(t)−μ1(t))2=0.5⋅0.5⋅(0−255)2=0.5⋅0.5⋅65025=16281.25, which is the maximum possible value for σB2(t) given the input.
- The final output is the threshold value that maximizes σB2(t), which in this case is 0 since it results in the largest between-class variance.
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
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.