Skip to content

Instantly share code, notes, and snippets.

@thyeem
Created November 9, 2024 19:22
Show Gist options
  • Save thyeem/ed18c76caf13bd99dea483fa40523e9b to your computer and use it in GitHub Desktop.
Save thyeem/ed18c76caf13bd99dea483fa40523e9b to your computer and use it in GitHub Desktop.
Otsu's method to perform automatic data thresholding
import numpy as np
def otsu(x):
hist, bin_edges = np.histogram(x, bins=range(min(x), max(x) + 2))
total = len(x)
max_, threshold = 0, 0
sum_total, sum_1, weight_0, weight_1 = 0, 0, 0, 0
for i in range(len(hist)):
sum_total += i * hist[i]
for i in range(len(hist)):
weight_0 += hist[i]
if weight_0 == 0:
continue
weight_1 = total - weight_0
if weight_1 == 0:
break
sum_1 += i * hist[i]
mean_0 = sum_1 / weight_0
mean_1 = (sum_total - sum_1) / weight_1
between_class_variance = weight_0 * weight_1 * (mean_0 - mean_1) ** 2
if between_class_variance > max_:
max_ = between_class_variance
threshold = i
return threshold
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment