Created
March 22, 2023 18:47
-
-
Save sukhitashvili/8070b9ba18c5b6766193bd0ac3cb5bfe to your computer and use it in GitHub Desktop.
Does Otsu binarization on an input array of floats
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
| def binary_otsu(input_vector: list) -> float: | |
| """ | |
| Otsu's method to find the best threshold for a binary image or vector | |
| """ | |
| pixel_number = len(input_vector) | |
| mean_weight = 1.0 / pixel_number | |
| his, bins = np.histogram(input_vector, bins=50) | |
| final_thresh = -1 | |
| final_value = -1 | |
| intensity_arr = bins[:-1] | |
| for t in range(his.shape[0]): # This goes from 1 to 254 uint8 range (Pretty sure wont be those values) | |
| pcb = np.sum(his[:t]) | |
| pcf = np.sum(his[t:]) | |
| Wb = pcb * mean_weight | |
| Wf = pcf * mean_weight | |
| mub = np.sum(intensity_arr[:t] * his[:t]) / float(pcb) | |
| muf = np.sum(intensity_arr[t:] * his[t:]) / float(pcf) | |
| # print mub, muf | |
| value = Wb * Wf * (mub - muf) ** 2 | |
| if value > final_value: | |
| final_thresh = t | |
| final_value = value | |
| return intensity_arr[final_thresh] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment