semmixcolor and perception

Converting RGB, CMY and CMYK

The simplest conversions in color theory: CMY is the inverse of RGB, and CMYK is CMY with black split out as a separate component. The formulas are short, but it is worth knowing what they do not handle.

All values are in 0..1. Divide 0..255 values by 255, percentages by 100.

RGB and CMY

C = 1 - R R = 1 - C M = 1 - G G = 1 - M Y = 1 - B B = 1 - Y

CMY describes how much light each ink should absorb (see CMY and CMYK models). White is (0, 0, 0), black (1, 1, 1).

CMY and CMYK

The part common to all three inks makes gray, which can be replaced with black:

K = min(C, M, Y) C' = (C - K) / (1 - K) M' = (M - K) / (1 - K) Y' = (Y - K) / (1 - K) (for K = 1: C' = M' = Y' = 0) back: C = C' · (1 - K) + K M = M' · (1 - K) + K Y = Y' · (1 - K) + K

Dividing by (1 - K) rescales the remaining inks to the full range, so C', M', Y' describe the hue and K describes how much it is darkened.

RGB and CMYK directly

K = 1 - max(R, G, B) C = (1 - R - K) / (1 - K) M = (1 - G - K) / (1 - K) Y = (1 - B - K) / (1 - K) R = (1 - C) · (1 - K) G = (1 - M) · (1 - K) B = (1 - Y) · (1 - K)

Example

RGB (200, 80, 40), #c85028:

R = 0.7843 G = 0.3137 B = 0.1569 CMY: C = 0.2157 M = 0.6863 Y = 0.8431 CMYK: K = min(0.2157, 0.6863, 0.8431) = 0.2157 C' = (0.2157 - 0.2157) / 0.7843 = 0 M' = (0.6863 - 0.2157) / 0.7843 = 0.6 Y' = (0.8431 - 0.2157) / 0.7843 = 0.8 CMYK = (0%, 60%, 80%, 21.6%) back: R = (1 - 0) · 0.7843 = 0.7843 → 200 G = (1 - 0.6) · 0.7843 = 0.3137 → 80 B = (1 - 0.8) · 0.7843 = 0.1569 → 40

Code

// r, g, b in 0..1
function rgbToCmyk(r, g, b) {
  const k = 1 - Math.max(r, g, b);
  if (k === 1) return { c: 0, m: 0, y: 0, k: 1 };
  return {
    c: (1 - r - k) / (1 - k),
    m: (1 - g - k) / (1 - k),
    y: (1 - b - k) / (1 - k),
    k,
  };
}

function cmykToRgb(c, m, y, k) {
  return { r: (1 - c) * (1 - k), g: (1 - m) * (1 - k), b: (1 - y) * (1 - k) };
}

What these formulas do not do

These are geometric conversions between two descriptions of the same cube. They know nothing about inks, paper or the press, so:

Print-ready files are made with the ICC profile of the print process (see color management). The formulas above suit screen graphics, visualization and understanding how the model works.