How to determine if given XYZ tristimulus values fall within a color gamut.
The gamut is defined by four CIE xy coordinates representing red, green, blue, and white.
Please provide the Python code.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! To determine if a given XYZ tristimulus value falls within a color gamut defined by four CIE xy coordinates (red, green, blue, white), you can follow these steps:
Steps
Convert the gamut's xy coordinates to XYZ (assuming Y=1 for chromaticity).
Convert the input XYZ to xyY.
Project the input xy onto the 2D chromaticity diagram.
Check if the point lies within the triangle formed by the RGB primaries (the white point is not used for the triangle, but can be used for white point adaptation if needed).
Python Code
Below is a Python function that checks if a given XYZ value is inside the RGB triangle on the xy chromaticity diagram:
python
import numpy as np
def xy_to_XYZ(x, y, Y=1.0):
"""Convert xy chromaticity to XYZ (Y is luminance, default 1.0)."""
if y == 0:
return np.array([0, 0, 0])
X = x * (Y / y)
Z = (1 - x - y) * (Y / y)
return np.array([X, Y, Z])
def XYZ_to_xy(XYZ):
"""Convert XYZ to xy chromaticity coordinates."""
X, Y, Z = XYZ
denom = X + Y + Z
if denom == 0:
return (0, 0)
x = X / denom
y = Y / denom
return (x, y)
def point_in_triangle(pt, v1, v2, v3):
"""Check if point pt is inside the triangle v1, v2, v3 (all are (x, y) tuples)."""
def sign(p1, p2, p3):
return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1])
b1 = sign(pt, v1, v2) < 0.0
b2 = sign(pt, v2, v3) < 0.0
b3 = sign(pt, v3, v1) < 0.0
return ((b1 == b2) and (b2 == b3))
def is_XYZ_in_gamut(XYZ, gamut_xy):
"""
Check if XYZ is within the gamut defined by RGB xy coordinates.
gamut_xy: dict with keys 'red', 'green', 'blue', 'white', each value is (x, y)
"""
# Convert input XYZ to xy
x, y = XYZ_to_xy(XYZ)
# Get the triangle vertices
r = gamut_xy['red']
g = gamut_xy['green']
b = gamut_xy['blue']
# Check if (x, y) is inside the triangle
return point_in_triangle((x, y), r, g, b)
# Example usage:
gamut_xy = {
'red': (0.64, 0.33),
'green': (0.30, 0.60),
'blue': (0.15, 0.06),
'white': (0.3127, 0.3290) # D65, for example
}
# Example XYZ value
XYZ = np.array([0.25, 0.40, 0.35])
in_gamut = is_XYZ_in_gamut(XYZ, gamut_xy)
print("Is in gamut:", in_gamut)
Notes
This code ignores the white point for the triangle test, as the RGB primaries define the gamut on the xy plane.
If you want to check for out-of-gamut due to luminance (Y), you may want to check if Y is within a certain range, but for chromaticity, the above is sufficient.
If you want to use the white point for chromatic adaptation, you would need to adapt the input XYZ to the gamut's white point before testing.
Let me know if you need a version that includes white point adaptation!