Skip to content

Instantly share code, notes, and snippets.

@Swarchal
Last active November 12, 2016 01:03
Show Gist options
  • Select an option

  • Save Swarchal/d50a9059f2bbea2ba6c94384e04dfb18 to your computer and use it in GitHub Desktop.

Select an option

Save Swarchal/d50a9059f2bbea2ba6c94384e04dfb18 to your computer and use it in GitHub Desktop.
otsu threshold
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