mike3467
mike3467

Reputation: 85

Find contrast between two colours

I would like to write a function in Python that compares two colours. Let's say I have a background colour and a font colour. And I want wo check if the font has enough contrast to be visible on the background. I receive the colours in RGB format like 16777215 (white). How can I do that?

What does the difference between two colour values, e.g. 16777215 - 12788622 mean? Does the difference say anything about the contrast?

Upvotes: -2

Views: 107

Answers (1)

K J
K J

Reputation: 11835

PDF uses colors in many ways however most are counted as textual floats at a position. So if you have 1.00 red in the same position on 1.00 green then there is Human contrast (unless red/green colour blind)

Both are symbolically ÿ (when decompressed for rendering) and thus have a decimalised value of 255 (we tend to say 1.00 = \O000 or \x00 in such cases). This makes it difficult to determine PDF contrast in a simplistic fashion.

Here the foreground text Hello is value 127 and the background is [.5 .5 .5] yet both look like the same grey however may print as different colours by a printers profile). Mathematically wildly different, yet have no contrast whatsoever. There are many many similar ways to set PDF bytes as transparently the same contrast visually yet mathematically their bytes will be different values.

stream
q /GS0 gs .5 .5 .5 rg 0 0 438 540 re f 0.5 g BT /F0 12 Tf 1 0 0 1 100 400 Tm [(Hello)] TJ ET Q
endstream

enter image description here

When viewed in Adobe Reader there is a contrast seen even if mild!
enter image description here
But we can enhance Colour Contrast for viewing or printing
enter image description here

For this reason PDF/A verification requires a Human (Pre-flight attendant) be used to decide if a PDF has sufficiently contrasting colours.

These are very contrasting colours but all just the same 2 characters since colours in a PDF are predominantly described in ASCII or ANSI or Hex encoded textual terms (many other encodings are used but usually those are compressed as raw single byte colours).

enter image description here

And 2 colours as seen above are "Black" but render as 2 white squares. enter image description here

Upvotes: 1

Related Questions