`component_centroids` did not recognize `Matrix{Int32}`

I’m new to Julia. I was trying to execute center = component_centroids(cq)[2:end] where cq is of type Matrix{Int32}, but got the following error:

MethodError: no method matching component_centroids(::Matrix{Int32})

Closest candidates are:
  component_centroids(!Matched::AbstractArray{Int64, N}) where N
   @ ImageMorphology C:\Users\whoever\.julia\packages\ImageMorphology\1lEjs\src\connected.jl:247

So I have to write center = component_centroids(Int64.(cq))[2:end] instead. However, I looked into the source code of component_centroids and found no sign that Int64 is necessary. The source code is provided below for convenience:

"`component_centroids(labeled_array)` -> an array of centroids for each label, including the background label 0"
function component_centroids(img::AbstractArray{Int,N}) where {N}
    len = length(0:maximum(img))
    n = fill(zero(CartesianIndex{N}), len)
    counts = fill(0, len)
    @inbounds for I in CartesianIndices(size(img))
        v = img[I] + 1
        n[v] += I
        counts[v] += 1
    return map(v -> n[v].I ./ counts[v], 1:len)

I’m not sure if this is a bug or there’s something I misunderstood.

This should be

function component_centroids(img::AbstractArray{<:Integer,N}) where {N}

if you want to accept any type of integer array here. See Julia FAQ - Troubleshooting “method not matched”: parametric type invariance and MethodErrors, and note that Int is a concrete type (a synonym for Int64 on 64-bit systems) whereas Integer is the abstract integer supertype.

1 Like