Skip to content

Instantly share code, notes, and snippets.

@vrld
Created October 30, 2014 12:34
Show Gist options
  • Save vrld/21972ff2b8384bdb8192 to your computer and use it in GitHub Desktop.
Save vrld/21972ff2b8384bdb8192 to your computer and use it in GitHub Desktop.
Various contour descriptors
function forward_difference(c::Matrix)
out = zeros(c)
@simd for i = 1:size(c,1)-1
@inbounds out[i,:] = c[i+1,:] - c[i,:]
end
@inbounds out[size(c,1),:] = c[1,:] - c[size(c,1),:]
out
end
function at(c::Matrix, t::Number, Δc::Matrix, cumlen::Vector{Float64})
k = 2
while t >= cumlen[k]
k += 1
end
c[k-1,:] + Δc[k-1,:] * (t - cumlen[k-1]) / (cumlen[k] - cumlen[k-1])
end
function at(c::Matrix, t::Number)
Δc = forward_difference(c)
cumlen = [.0, sum(Δc.^2,2) |> sqrt |> cumsum]
cumlen ./= cumlen[end]
at(c, t, Δc, cumlen)
end
function resample(c::Matrix, M::Int)
Δc = forward_difference(c)
cumlen = [.0, sum(Δc.^2,2) |> sqrt |> cumsum]
cumlen ./= cumlen[end]
out = zeros(M,2)
k = 2::Int64
for i = 1:M
t = (i-1) / M
while t >= cumlen[k]
k += 1
end
@inbounds out[i,:] = c[k-1,:] + Δc[k-1,:] * (t - cumlen[k-1]) / (cumlen[k] - cumlen[k-1])
end
out
end
fourierDescriptor(c::Matrix) = fft!(c[:,1] + c[:,2]im)
fourierDescriptor(c::Matrix, M::Int) = resample(c,M) |> fourierDescriptor
function makeInvariant!(d::Vector{Complex{Float64}})
d[1] = 0 # translation invariance
d ./= abs(d[2]) # scale invariance
d
end
makeInvariant(d) = makeInvariant!(copy(d))
function toContour(d::Vector)
id = ifft(d)
[real(id) imag(id)]
end
function centroidDistance(c::Matrix)
d = sum((c .- mean(c,1)).^2, 2) |> sqrt
d ./ maximum(d) # scale invariance
end
centroidDistance(c::Matrix, M::Int) = resample(c,M) |> centroidDistance
fftCentroidDistance(c::Matrix) = centroidDistance(c) |> fft
fftCentroidDistance(c::Matrix, M::Int) = resample(c,M) |> centroidDistance |> fft
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment