Open josenimo opened 1 month ago
idea is
import numpy as np
def kittler_illingworth_threshold(data):
# Calculate histogram
hist, bin_edges = np.histogram(data, bins=256, range=(0, 256))
# Calculate probability of each intensity level
P = hist / hist.sum()
# Cumulative sums
omega = np.cumsum(P)
# Means
mu = np.cumsum(P * np.arange(256))
# Total mean
mu_t = mu[-1]
# Between class variance
sigma_b_squared = (mu_t * omega - mu) ** 2 / (omega * (1 - omega))
# Replace NaNs with zero
sigma_b_squared = np.nan_to_num(sigma_b_squared)
# Find threshold
threshold = np.argmax(sigma_b_squared)
return threshold
# Example usage
data = np.random.randint(0, 256, 1000)
threshold = kittler_illingworth_threshold(data)
print(f"Optimal threshold: {threshold}")
double derivative of density plot