melonora / napari-cell-gater

A napari plugin for cell marker gating.
BSD 3-Clause "New" or "Revised" License
4 stars 1 forks source link

improve default gate value #28

Open josenimo opened 1 month ago

josenimo commented 1 month ago

double derivative of density plot

josenimo commented 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}")