First let me say that I am starting the journey with computer vision so I would be grateful for any idea!
What I need to do is to calculate the contrast between a text and a background on an image. I used MS Azure OCR API to analyze the image and retrieve the bounding boxes containing the words from the image.
So we can assume the image I have is a rectangle containing a single word = text letters and a bit of background between them.
The background can be multi-color or single-color. If it is multi-color, we can assume the colors are very close to each other (let’s say they are different shades of the same color).
The text was made using a single-color font, but due to the anti-aliasing effect that has been applied to the original font, a lot of the pixels of the text end up being multi-color (various shades of the original font color). Font itself can vary in size and type.
The problem: how to calculate the contrast between the original font color (how to find that color?) and the “average” background color ? By “avarage” background color, I mean that the algorithm should map the various colors occuring in the background into one simplified color.
Thanks in advance for your help!
EDIT: Here's what I tried so far:
I found an open-source implementation of the Median Cut algorithm and used it to extract dominant colors palette approximation from my image. I pass 8 as palette size, so the algorithm divides the color space into 8 buckets and calculates the average color for each bucket and returns those 8 colors as the palette. https://github.com/SvenWoltmann/color-thief-java
After extracting the approximated palette, I calculate the contrast between each two colors, using the following formula (according to https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-procedure):
• (L1 + 0.05) / (L2 + 0.05), where
◦ L1 is the relative luminance of the lighter of the foreground or background colors, and
◦ L2 is the relative luminance of the darker of the foreground or background colors.
Then, I choose the maximum of those contrasts. So I assume the colors furthest from each other are the text and background color. (This assumption is true for images where text is on a single-color background, but not necessarily true for images with multi-color background.)
The results I am getting are often not satisfactory, as the calculated contrast differs significantly from the original one (measured manually in GIMP). That’s probably due to the fact that 1. the color-thief algorithm returns approximation (average) of the colors and not the exact background and text colors and 2. for certain cases (like multi-color background) the algorithm might mistake two background colors for background and text colors.
Example images:





