[Tutor] writing function changeColor

Steven D'Aprano steve at pearwood.info
Thu Jul 19 01:09:43 CEST 2012


Coming back to your original question...


On Wed, Jul 18, 2012 at 01:10:51PM -0400, Aditi Pai wrote:
> Hello,
> 
> I am trying to write a function changeColor for an assignment. Two things
> that I am unsure about for this assignment are how to assign different
> colors to integers so that, red will be 1, blue will be 2, etc. Also, I

Is your assignment to invent your own colour scheme? Or to use an 
existing colour scheme?

(I'm Australian, we spell colour with a U.)

If you are supposed to use an existing scheme, then you need to find out 
which one you are supposed to use. I can't help with that.

I can tell you that there are generally two main ways to assign colours:

* palettes (also known as indexed colour)

* colour spaces

Palettes aren't terribly helpful in this question. A palette basically 
is a list of usually 256 integers (but sometimes fewer), each one of 
which arbitrarily represents a colour. So you might have:

0 = light blue
1 = pink
2 = dark green
3 = white
4 = very light grey
...
254 = black
255 = tangerine

or something.

Obviously because the order of colours is arbitrary, it is hard, if not 
impossible, to say "start with tangerine and make it 10% more blue".

Colour spaces are more useful. A colour space defines each colour in 
terms of usually three, but sometimes four, numbers, each one of which 
ranges between 0 and 255. Each number represents a different quality of 
the colour.

There are different colour spaces, because none of them describe colour 
perfectly. Some of them are better for modelling additive colours (like 
from your monitor, which generates coloured light); some are better for 
subtractive colours (like your colour printer). The whole field is 
awfully complex and I'm not an expert, but you can start here:

http://en.wikipedia.org/wiki/Color_space_encoding

I *think* that for your purposes, the best colour space to start with is 
the RGB model. In this, each colour is represented by an amount of red, 
green and blue, added together. For example:

"Black" is the complete absence of any colour, so:

Red = 0
Green = 0
Blue = 0

"White" is a complete mix of all colours, so:

Red = 255
Green = 255
Blue = 255


Everything else is somewhere in between, e.g. "Forest Green":

Red: 33 out of a maximum of 255, or 12.9%
Green: 139, or 54.5%
Blue: 33, or 12.9%

Notice that here the percentage represents the amount out of the maximum 
possible for each value, and then do NOT add to 100% in total.

If you increase the amount of blue by 50%, you get:

Red: 33 or 12.9%
Green: 139 or 54.5%
Blue: 33 + 16.5 = 50 (rounded to the nearest integer) or 19.6%

I have no idea what name this colour might have.

Does this help?


-- 
Steven


More information about the Tutor mailing list