Created
November 10, 2014 02:18
-
-
Save jwmerrill/179aae6c3d2d4e770614 to your computer and use it in GitHub Desktop.
Kmeans thresholding of a grayscale image
This file contains 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
function graythresh_kmeans(img) | |
# Note, without the type annotation, this is slow because | |
# mean appears not to be type stable here | |
thresh = mean(img)::Gray{Float32} | |
while true | |
lastthresh = thresh | |
nplus = 0 | |
nminus = 0 | |
splus = zero(typeof(thresh)) | |
sminus = zero(typeof(thresh)) | |
for v in img | |
if v > thresh | |
splus += v | |
nplus += 1 | |
else | |
sminus += v | |
nminus += 1 | |
end | |
end | |
thresh = (splus/nplus + sminus/nminus)/2 | |
if thresh == lastthresh | |
return thresh | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jwmerrill
Can I use this code in a MIT licensed project?
Thank you,
Kind regards,
Ken Bastiaensen (@Ken-B)