Created
January 8, 2025 22:36
-
-
Save bpeterso2000/752bb6d7bd4575c03b97ca72c6629685 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import colorsys | |
def hex_to_rgb(hex_color): | |
# Remove the '#' if present | |
hex_color = hex_color.lstrip('#') | |
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)) | |
def calculate_luminance(hex_color): | |
# Convert hex to RGB | |
r, g, b = hex_to_rgb(hex_color) | |
# Normalize RGB values to be between 0 and 1 | |
r, g, b = [x / 255.0 for x in (r, g, b)] | |
# Apply the sRGB transfer function if components are below the threshold | |
def srgb_transfer_function(color): | |
if color <= 0.03928: | |
return color / 12.92 | |
else: | |
return ((color + 0.055) / 1.055) ** 2.4 | |
r, g, b = [srgb_transfer_function(c) for c in (r, g, b)] | |
# Calculate luminance using the formula: L = 0.2126 * R + 0.7152 * G + 0.0722 * B | |
luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b | |
return luminance | |
# Example usage | |
hex_color = "#FF0000" # Red | |
luminance = calculate_luminance(hex_color) | |
print(f"The relative luminance of {hex_color} is {luminance:.4f}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment