Below is a complete Python program that converts an RGB color to both LAB and CMYK. This example does not require any external libraries and uses standard conversion formulas.
Note:
- The conversion from RGB to LAB first linearizes the sRGB values, converts them to the CIE XYZ color space, and then converts XYZ to CIELAB using the D65 white reference.
- The CMYK conversion uses a straightforward formula. The results are returned as percentages.
def rgb_to_cmyk(r, g, b):
"""
Convert an RGB color to CMYK.
The RGB input is expected in the range [0, 255].
Returns:
A tuple of (C, M, Y, K) each in percent (0 to 100).
"""
# Normalize the RGB values to [0, 1]
r_norm = r / 255.0
g_norm = g / 255.0
b_norm = b / 255.0
# Calculate K (black key) component.
k = 1 - max(r_norm, g_norm, b_norm)
if k == 1: # Pure black
return 0, 0, 0, 100
# Calculate the CMY values
c = (1 - r_norm - k) / (1 - k)
m = (1 - g_norm - k) / (1 - k)
y = (1 - b_norm - k) / (1 - k)
# Return values as percentages.
return (c * 100, m * 100, y * 100, k * 100)
def rgb_to_lab(r, g, b):
"""
Convert an RGB color to LAB.
The input RGB values are expected in the range [0, 255].
Returns:
A tuple (L, a, b) with L in [0, 100] and a, b typically in a range around -128 to +127.
"""
# 1. Normalize RGB to [0, 1]
r = r / 255.0
g = g / 255.0
b = b / 255.0
# 2. Apply gamma correction to convert sRGB to linear RGB.
def pivot_rgb(c):
return ((c + 0.055) / 1.055) ** 2.4 if c > 0.04045 else c / 12.92
r_lin = pivot_rgb(r)
g_lin = pivot_rgb(g)
b_lin = pivot_rgb(b)
# 3. Convert linear RGB to XYZ using the Observer= 2° Illuminant=D65
x = r_lin * 0.4124 + g_lin * 0.3576 + b_lin * 0.1805
y = r_lin * 0.2126 + g_lin * 0.7152 + b_lin * 0.0722
z = r_lin * 0.0193 + g_lin * 0.1192 + b_lin * 0.9505
# 4. Normalize for the D65 reference white point.
# The reference white point values for D65 are: X=0.95047, Y=1.00000, Z=1.08883.
x = x / 0.95047
y = y / 1.00000
z = z / 1.08883
# 5. Convert XYZ to LAB
def pivot_xyz(t):
return t ** (1/3) if t > 0.008856 else (7.787 * t) + (16 / 116)
fx = pivot_xyz(x)
fy = pivot_xyz(y)
fz = pivot_xyz(z)
l = (116 * fy) - 16
a = 500 * (fx - fy)
b_val = 200 * (fy - fz)
return (l, a, b_val)
def main():
print("RGB to LAB and CMYK Converter")
# Input for RGB values
try:
r = int(input("Enter the Red component (0-255): "))
g = int(input("Enter the Green component (0-255): "))
b = int(input("Enter the Blue component (0-255): "))
except ValueError:
print("Invalid input. Please enter integer values from 0 to 255.")
return
# Validate the input ranges.
if any(not (0 <= val <= 255) for val in [r, g, b]):
print("RGB values must be in the range 0 to 255!")
return
# Convert to CMYK and LAB.
cmyk = rgb_to_cmyk(r, g, b)
lab = rgb_to_lab(r, g, b)
print("\nConverted color values:")
print(f"CMYK: C={cmyk[0]:.2f}%, M={cmyk[1]:.2f}%, Y={cmyk[2]:.2f}%, K={cmyk[3]:.2f}%")
print(f"LAB: L={lab[0]:.2f}, a={lab[1]:.2f}, b={lab[2]:.2f}")
if __name__ == "__main__":
main()
How the Program Works
-
RGB to CMYK Conversion:
- The RGB values are first normalized to the range [0, 1].
- The black key (K) value is found using
K = 1 - max(R, G, B).
- Then C, M, and Y are calculated. If the input color is pure black (R=G=B=0), it directly returns 100% K with 0% for the other components.
- The results are converted to percentage values.
-
RGB to LAB Conversion:
- The RGB values are normalized and then linearized using the standard sRGB gamma correction.
- The linearized values are converted to the XYZ color space using a standard transformation matrix.
- XYZ is normalized by the D65 reference white, then converted to LAB through a nonlinear transformation to better approximate human perception.
- The output LAB values are returned.
-
Execution:
- The
main() function prompts the user to enter RGB values and then prints the corresponding CMYK and LAB values.
You can run this script directly using Python 3. Enjoy converting your colors!