Otsu's Threshold
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 that best separates the pixels into two classes (foreground and background) by maximizing the between-class variance .
Algorithm:
For each candidate threshold from 0 to 255:
-
Class probabilities:
- (background weight)
- (foreground weight)
-
Class means:
-
Between-class variance:
-
The optimal threshold maximizes .
where is the probability of intensity (histogram normalized by total pixel count).
Return the threshold value (integer) that maximizes .
Example
pixels = [0, 0, 0, 0, 0, 255, 255, 255, 255, 255] num_bins = 256
0
pixelsholds 10 intensities: five at (black) and five at (white).num_binsis , one bin per possible intensity. Normalising the counts gives , , and for every other .- At the background class is and the foreground is : , , , .
- So .
- Now try . No pixel lies in , so every one of these thresholds produces exactly the same two classes and the same . At the foreground is empty (), so 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 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