RGB conversion to and from an Array, broadcasting

Hi,
I’ve just had a couple of days with Julia - I’m very much enjoying the Pluto, Jupyter and repl environments. Python has been making me bilious.

I have some very ‘early-learner’ questions related to idioms for unpacking and repacking single RGB values. The MIT Introduction to Computational Thinking course has a very early exercise to write a function that inverts an RGB value. I can do it the blah blah way, but…

A. I know how to make an RGB value like this RGB(-1.0, 0.0, 0.0), but I cannot find out how to convert an Array containing the same values to a single RGB value.

v = (-1.0, 0.0, 0.0)
v2 = RGB(v) # I can find no examples

B. How do I unpack an RGB value into an array, without using [c.r, c.g. c.b]?
I’d like to do something like (r,g,b) = c, or c.asArray - preserving order. My brackets are in dissaray :slight_smile:

C. I’m disappointed because I can broadcast an operation over an array, but not over an RBG value:

c = RGB(-1.0, 0.0, 0.0)
v = (c.r, c.g, c.b)
v2 = 1 .- v # Works nicely
# I don't know how  to covert back to RGB

I would like to be able to do:

c = RGB(-1.0, 0.0, 0.0)
c2 = 1 -. c

I tried looking at cmap but there were no examples simple enough for me to interpret at my level.

Cheers…

To unpack a tuple or array into an RGB value, you can use the splat operator like this:

julia> v2 = RGB(v...)
RGB{Float64}(-1.0,0.0,0.0)

I think you want mapc, not cmap. For your example,

julia> mapc(v -> 1 - v, c)
RGB{Float64}(2.0,1.0,1.0)
2 Likes

Thanks very much! And there it is in the FAQ. :crazy_face:
An insight as to why broadcast doesn’t work on RGB instances?

Each RGB instance is supposed to be treated as if it were a scalar value. This makes it easier to broadcast over each RGB value collectively rather than each individual component.

See GitHub - JuliaGraphics/ColorVectorSpace.jl: Treat colors as if they are n-vectors for the purposes of arithmetic if you want to treat it like a vector.

2 Likes