Skip to content

Converting RGB colors to nearest html colors #577

@B-LIE

Description

@B-LIE

Is this a useful utility function? If so, you should change the code the the naming conventions in Colors.jl

I have a vector of colors that I have used in some Plots.jl code. Example:

using Colors

col = [colorant"forestgreen", colorant"royalblue", colorant"rebeccapurple", colorant"crimson", colorant"darkorange", colorant"sienna", colorant"slategrey", colorant"darkcyan", colorant"red", colorant"royalblue", colorant"forestgreen", colorant"darkorange"]

I need to pick, say, 4 new colors that are as distant as possible from these. Here is what I do:

new_col = distinguishable_colors(4, col; dropseed=true)

Now, for ease of using my code, I prefer to have HTML symbol names for the colors. The following does the trick:

# Pre-calculate once
const STANDARD_NAMES = collect(keys(Colors.color_names))
const STANDARD_COLORS = [parse(Colorant, n) for n in STANDARD_NAMES]

function get_color_names(colors)
    approx_names = map(colors) do target
        # Use the pre-calculated constants
        distances = [colordiff(target, c) for c in STANDARD_COLORS]
        STANDARD_NAMES[argmin(distances)]
    end
    
    return (
        symb = Symbol.(approx_names), 
        obj = [parse(Colorant, n) for n in approx_names]
    )
end

I can now do:

julia> get_color_names(new_col).symb
4-element Vector{Symbol}:
 :grey6
 :yellow1
 :pink
 :lightcyan1

julia> hcat(new_col, get_color_names(new_col).obj)

leading to:

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions