Created
November 9, 2024 19:22
-
-
Save thyeem/ed18c76caf13bd99dea483fa40523e9b to your computer and use it in GitHub Desktop.
Otsu's method to perform automatic data thresholding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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