[Python] Find contrast between two colours

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Edit: A solution based on the comments of @VC.One that loops through a pdf document to find text with low contrast on a white background:

    import streamlit as st
    import pymupdf

    def main():
    # File Uploader
    uploaded_file = st.file_uploader("Select PDF file: ", type='pdf')

    # Search document
    if uploaded_file is not None:
    find_low_contrast_font(uploaded_file)

    def find_low_contrast_font(uploaded_file):
    # Open document
    doc = pymupdf.open("pdf", uploaded_file.read())

    # Loop through the pages
    for page_num in range(doc.page_count):
    page = doc[page_num]
    for text in page.get_text("dict")["blocks"]:
    for line in text["lines"]:
    for span in line["spans"]:
    if contrast_is_low(span["color"]):
    st.write(f"Low contrast font on page {page_num + 1}: {span['text']}")

    # Close document
    doc.close()

    def contrast_is_low(font_color):
    background_color = 16777215 # White
    minimum_distance = 40 # (DF,DF,DF) / (223,223,223) / 14671839 / light grey: distance to white is 32
    low_contrast = False

    background_color_rgb_dict = get_rgb_values_from_integer(background_color)
    background_color_luminance = calculate_luminance(background_color_rgb_dict)

    font_color_rgb_dict = get_rgb_values_from_integer(font_color)
    font_color_luminance = calculate_luminance(font_color_rgb_dict)

    distance = calculate_distance(background_color_luminance, font_color_luminance)

    if distance <= minimum_distance:
    low_contrast = True

    return low_contrast

    def get_rgb_values_from_integer(rgb_int):
    blue = rgb_int & 255
    green = (rgb_int >> 8) & 255
    red = (rgb_int >> 16) & 255
    rgb_dict = {
    "r": red,
    "g": green,
    "b": blue
    }
    return rgb_dict

    def calculate_luminance(rgb_dict):
    return 0.299 * rgb_dict["r"] + 0.587 * rgb_dict["g"] + 0.114 * rgb_dict["b"]

    def calculate_distance(background_color_luminance, font_color_luminance):
    return abs(background_color_luminance - font_color_luminance)

    if __name__ == "__main__":
    main()

    Continue reading...

Compartilhe esta Página