PIXELBANKv9.1.0
Menu

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:
  • The input list pixels is used to calculate the probability of each intensity ii, which is p(i)=number of pixels with intensity itotal number of pixelsp(i) = \frac{\text{number of pixels with intensity } i}{\text{total number of pixels}}. For the given input, p(0)=510=0.5p(0) = \frac{5}{10} = 0.5 and p(255)=510=0.5p(255) = \frac{5}{10} = 0.5.
  • The class probabilities w0(t)w_0(t) and w1(t)w_1(t) are calculated for each candidate threshold tt. Since p(0)=0.5p(0) = 0.5 and p(255)=0.5p(255) = 0.5, when t=0t = 0, w0(t)=0.5w_0(t) = 0.5 and w1(t)=0.5w_1(t) = 0.5.
  • The between-class variance σB2(t)\sigma_B^2(t) is calculated for each tt. For t=0t = 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\sigma_B^2(t) = w_0(t) \cdot w_1(t) \cdot (\mu_0(t) - \mu_1(t))^2 = 0.5 \cdot 0.5 \cdot (0 - 255)^2 = 0.5 \cdot 0.5 \cdot 65025 = 16281.25, which is the maximum possible value for σB2(t)\sigma_B^2(t) given the input.
  • The final output is the threshold value that maximizes σB2(t)\sigma_B^2(t), which in this case is 00 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 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

0/0
Run code to see test results.
Otsu's Threshold - Hard | PixelBank