The luminance of a colour is a measure used to describe the perceived brightness of a colour. It is possible to calculate the luminance of a colour based on its RGB colour code.
So let’s consider an algorithm that collects an RGB colour code as an input, using the (255,255,255) format. The algorithm will then convert these R, G, B values to a 0 to 1 scale as follows:
New R1,G1 B1 values are then calculated using the following rules:
Finally, the luminance value of the colour can be calculated using the following formula:
The reason such complex formulas are necessary to calculate the luminance (“perceived brightness”) of a colour is partly because our eyes’ perception of the brightness of a colour is not linear (it is not directly proportionate to the number of photons being emitted by a computer screen). Effectively our eyes perceive more levels of light in dim conditions, and less in brighter conditions.
Your first task is to write a function called luminance() that takes 3 parameters r, g and b corresponding to the RGB values of a colour (integer values between 0 and 255). Your function will use the above algorithm to calculate and return the luminance of the given colour.
You can use the trinket at the bottom of this page to write the Python code for this fucntion.
The contrast ratio defines how easy a human eye recognises text or images on a coloured background.
- The contrast ratio is a numerical ratio between 1:1 and 21:1.
- To be easily readable, the contrast ratio between the text colour and the background colour must be at least 7:1.
- A contrast ratio of at least 4.5 may suffice for larger text.
To calculate the contrast ratio between two colours (e.g. font/text colour and background colour) you must first calculate the luminance of both colours and identify which colour is the lightest colour and which colour is the darkest colour. You can then use these luminance values (labelled Llight and Ldark) to calculate the contrast ratio as follows:
Contrast Ratio Function
Your second task is to write a function called contrastRatio() that takes 6 parameters corresponding to the RGB values of two colours (integer values between 0 and 255). Your function will work out the luminance values of both colours, identify the lightest of the two colours and use the above formula to calculate and return the contrast ratio between these two colours.
Once your code is complete, check that it works as expected using the following four tests:
|Test #||Input Values||Expected Output||Pass/Fail?|
Contrast Ratio: 21
|#2||(148, 57, 173)
(174, 84, 199)
Contrast Ratio: 1.42
|#3||(148, 57, 173)
(209, 157, 223)
Contrast Ratio: 2.78
|#4||(148, 57, 173)
(245, 232, 248)
Contrast Ratio: 5.16