Skip to content

Instantly share code, notes, and snippets.

@jwmerrill
Created November 10, 2014 02:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwmerrill/179aae6c3d2d4e770614 to your computer and use it in GitHub Desktop.
Save jwmerrill/179aae6c3d2d4e770614 to your computer and use it in GitHub Desktop.
Kmeans thresholding of a grayscale image
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
@Ken-B
Copy link

Ken-B commented Mar 25, 2015

@jwmerrill
Can I use this code in a MIT licensed project?

Thank you,
Kind regards,
Ken Bastiaensen (@Ken-B)

@jwmerrill
Copy link
Author

Yes, please feel free.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment