Skip to content

advertise ccolor in writing generic code #151

@johnnychen94

Description

@johnnychen94

Functions in JuliaImages should accept both numerical array AbstractArray{<:Number} and colorant array Abstract{<:Colorant} if possible.

It is not uncommon to infer the return eltype in the beginning of the algorithm so as to pre-allocate array. I previously have two versions of codes to achieve this. The first version is:

function foo(img::AbstractArray{T}) where T<:Number
    CT = RGB{floattype(T)}
    ...
end

function foo(img::AbstractArray{T}) where T<:Colorant
    CT = RGB{floattype(eltype(T))}
    ...
end

Then one day I found out that eltype(Float32) == Float32, which make it possible to merge it into one method:

function foo(img::AbstractArray{T}) where T<:Number
    CT = RGB{floattype(eltype(T))}
    ...
end

As @kimikage pointed it out in JuliaGraphics/ColorTypes.jl#201, ccolor does a similar thing more reliably (I assume so?):

function foo(img::AbstractArray{T}) where T<:Number
    CT = ccolor(RGB, floattype(T))
    ...
end

I feel this worth documenting somewhere in the tutorials; otherwise, it's like a missing spell and people repeatedly reinvent it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    best practiceworkflows and best practice that are useful in JuliaImages and/or Julia

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions