Last active
November 12, 2016 01:03
-
-
Save Swarchal/d50a9059f2bbea2ba6c94384e04dfb18 to your computer and use it in GitHub Desktop.
otsu threshold
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
| using StatsBase | |
| function otsu_threshold(img, bit_depth = 256) | |
| counts = fit(Histogram, img[:], nbins = bit_depth).weights | |
| const total = prod(size(img)) | |
| current_max, threshold = 0, 0 | |
| weightB, sumB = 0, 0 | |
| sumT = sum([i * counts[i] for i in 1:bit_depth]) | |
| for (i, count) in enumerate(counts) | |
| weightB += count | |
| weightF = total - weightB | |
| if weightF == 0 break end | |
| sumB += i * count | |
| meanB = sumB / weightB | |
| meanF = (sumT - sumB) / weightF | |
| varBetween = weightB * weightF | |
| varBetween *= (meanB - meanF) * (meanB - meanF) | |
| if varBetween > current_max | |
| current_max = varBetween | |
| threshold = i | |
| end | |
| end | |
| return threshold | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment