Due: Friday, Mar. 12, 2027.
In order to understand natural images, one needs to understand how objects reflect light and how humans perceive that reflected light as color. This lab introduces colorimetry, the quantitative measurement and manipulation of color. There are three major components to understanding color: how light is reflected from a natural scene, how humans perceive reflected light, and how a display, such as a monitor, produces light.
You direct Claude, or another agentic AI, to write the code from the definitions and signatures on this page. You run the experiments and explain the results. You are graded on your specification, the checks you run, and your reading of the results.
lab8-data.zip
(6 MB) unzips to a folder data with three files:
x, y, z and two
illuminants: illum1, the D65 illuminant
(noon daylight), and illum2, a fluorescent lamp. Each
is sampled at the 31 wavelengths 400, 410, …, 700 nm.R, a 170 by 256 by 31
array. R[m, n, k] is the reflectance of pixel
\((m, n)\) at the \(k\)-th wavelength.
scipy.io.loadmat reads the .mat files. From
the shell, in the folder that holds lab8.py:
wget https://charlesbouman.org/ece63700/labs/lab8-data.zip unzip lab8-data.zip
lab8.py, which holds
functions and nothing else. Run experiments from a separate script
that imports it. Use the labs conda environment from
Lab 2, with NumPy, not PyTorch, and matplotlib for plotting.for loop over pixels or wavelengths. Every
sum over wavelength is a matrix product.uint8 arrays with labeled
axes.| Item | Experiment | Input | Function and settings |
|---|---|---|---|
| D1 | Color matching functions and illuminants (Step 2) | data.mat |
lms_cmfs with \(A^{-1}\) of equation (5);
chromaticity |
| D2 | Chromaticity diagram (Step 3) | data.mat |
CIE 1931 and Rec. 709 primaries of equations (10) and (11); D65 and equal energy white points of equations (12) and (13) |
| D3 | The matrix \(M_{709\_D65}\) (Step 4) | none | rgb_to_xyz_matrix with the Rec. 709 primaries and
the D65 white point |
| D4 | Image under D65 (Step 5) | reflect.mat, illum1;
img.png for the check |
reflectance_to_xyz, xyz_to_rgb with
\(M_{709\_D65}\), to_display with
\(\gamma = 2.2\) |
| D5 | Image under fluorescent light (Step 6) | reflect.mat, illum2 |
as D4, with the same \(M_{709\_D65}\) and \(\gamma = 2.2\) |
| D6 | Color chromaticity diagram (Step 7) | none | fill_chromaticity with step = 0.005
and \(M_{709}\), all \(\kappa = 1\); to_display
with \(\gamma = 2.2\) |
The lab uses a display gamma of \(\gamma = 2.2\) throughout, the gamma of the sRGB standard.
lab8.py
Copy these constants and helpers into lab8.py. The
constants are the numbers of equations (5) and (10) to (13).
import numpy as np
from PIL import Image
from scipy.io import loadmat
#: The 31 wavelengths in nm.
WAVELENGTHS = np.arange(400, 701, 10)
#: The matrix A^(-1) that maps XYZ to LMS, equation (5).
A_INV = np.array([[0.2430, 0.8560, -0.0440],
[-0.3910, 1.1650, 0.0870],
[0.0100, -0.0080, 0.5630]])
#: Chromaticities (x, y, z) of the CIE 1931 primaries, one row each for R, G, B.
PRIMARIES_CIE1931 = np.array([[0.73467, 0.26533, 0.0],
[0.27376, 0.71741, 0.00883],
[0.16658, 0.00886, 0.82456]])
#: Chromaticities (x, y, z) of the Rec. 709 primaries, one row each for R, G, B.
PRIMARIES_709 = np.array([[0.640, 0.330, 0.030],
[0.300, 0.600, 0.100],
[0.150, 0.060, 0.790]])
#: Chromaticity (x, y, z) of the D65 white point.
WHITE_D65 = np.array([0.3127, 0.3290, 0.3583])
#: Chromaticity (x, y, z) of the equal energy white point.
WHITE_EE = np.array([1.0, 1.0, 1.0]) / 3.0
def load_spectra(path="data/data.mat"):
"""Return cmf (3, 31) with rows x0, y0, z0, and the (31,) illuminants S_d65 and S_fl."""
d = loadmat(path)
cmf = np.stack([d["x"].ravel(), d["y"].ravel(), d["z"].ravel()]).astype(np.float64)
return cmf, d["illum1"].ravel().astype(np.float64), d["illum2"].ravel().astype(np.float64)
def load_reflectance(path="data/reflect.mat"):
"""Return R (170, 256, 31); R[m, n, k] is the reflectance of pixel (m, n) at WAVELENGTHS[k]."""
return np.asarray(loadmat(path)["R"], dtype=np.float64)
def load_rgb(path):
"""Read an 8-bit RGB PNG as an (H, W, 3) uint8 array."""
return np.asarray(Image.open(path).convert("RGB"), dtype=np.uint8)
def save_rgb(img, path):
"""Write an (H, W, 3) uint8 array as an 8-bit RGB PNG."""
Image.fromarray(np.asarray(img, dtype=np.uint8)).save(path)
Reflection of light. The color that one sees is a function of both the reflectance of a surface and the spectral distribution of the light source, or illuminant. Let \(S(\lambda)\) be the spectral energy density of the illuminant at wavelength \(\lambda\), and let \(R(\lambda)\) be the fraction of that energy reflected toward the viewer. The viewer sees light with the spectral distribution
$$ I(\lambda) = R(\lambda) \, S(\lambda) \ . \tag{1} $$So the perceived color of an object can depend on the illuminant. We are concerned with wavelengths from 400 to 700 nm, the range that is most visible. A simple model of an illuminant is the equal energy white \(S_{EE}(\lambda) = 1\). A more common model is the standard D65 illuminant, a tabulated set of measurements that approximates noon sunlight.
Human perception of color. Humans have three types of color receptors, or cones, called long, medium, and short for the wavelengths they are most sensitive to. Their measured responses \(l_0(\lambda)\), \(m_0(\lambda)\), and \(s_0(\lambda)\) are the cones' color matching functions. The total response of each cone is
$$ L = \int I(\lambda)\, l_0(\lambda)\, d\lambda \ , \qquad M = \int I(\lambda)\, m_0(\lambda)\, d\lambda \ , \qquad S = \int I(\lambda)\, s_0(\lambda)\, d\lambda \ . \tag{2} $$So while the spectrum of light may be very complex, the response of the visual system is limited to three dimensions. This is the tristimulus model of color vision. With the spectra sampled at \(\lambda = 400, 410, \dots, 700\) nm, the integrals become inner products,
$$ \begin{bmatrix} L \\ M \\ S \end{bmatrix} = \begin{bmatrix} l_0 \\ m_0 \\ s_0 \end{bmatrix} I \ , \tag{3} $$where \(l_0\), \(m_0\), and \(s_0\) are \(1 \times 31\) row vectors and \(I\) is a \(31 \times 1\) column vector.
The XYZ color space. The most standard representation of tristimulus values is the CIE 1931 \(XYZ\) system, related to \(LMS\) by
$$ \begin{bmatrix} X \\ Y \\ Z \end{bmatrix} = A \begin{bmatrix} L \\ M \\ S \end{bmatrix} \ , \qquad \begin{bmatrix} x_0 \\ y_0 \\ z_0 \end{bmatrix} = A \begin{bmatrix} l_0 \\ m_0 \\ s_0 \end{bmatrix} \ , \tag{4} $$where the inverse of \(A\) is approximately
$$ A^{-1} = \begin{bmatrix} 0.2430 & 0.8560 & -0.0440 \\ -0.3910 & 1.1650 & 0.0870 \\ 0.0100 & -0.0080 & 0.5630 \end{bmatrix} \ . \tag{5} $$The color of a spectrum \(I\) is then
$$ \begin{bmatrix} X \\ Y \\ Z \end{bmatrix} = \begin{bmatrix} x_0 \\ y_0 \\ z_0 \end{bmatrix} I \ . \tag{6} $$The functions \(x_0\), \(y_0\), and \(z_0\) are positive for all wavelengths. For the equal energy spectrum \(I_{EE} = [1, 1, \dots, 1]^t\), \((X, Y, Z) = (1, 1, 1)\), so each of \(x_0\), \(y_0\), and \(z_0\) sums to 1. The \(Y\) component is closely associated with perceived brightness and is called the luminance.
Chromaticity. Changes in the length of the vector \((X, Y, Z)\) change the brightness of the color. Changes in its direction change the hue and saturation, which together are the chromaticity. The chromaticity \((x, y, z)\) is \((X, Y, Z)\) scaled by its sum,
$$ x = \frac{X}{X+Y+Z} \ , \qquad y = \frac{Y}{X+Y+Z} \ , \qquad z = \frac{Z}{X+Y+Z} \ . \tag{7} $$Geometrically, the chromaticity is the intersection of the vector \((X, Y, Z)\) with the plane \(X + Y + Z = 1\). Since \(x + y + z = 1\), often only \((x, y)\) is given.
def lms_cmfs(cmf):
"""Return the (3, 31) LMS color matching functions l0, m0, s0 = A_INV @ cmf."""
def chromaticity(XYZ):
"""Return (..., 3) chromaticities (X, Y, Z) / (X + Y + Z) of a (..., 3) array with X + Y + Z > 0."""
Task 2a. Plot \(x_0(\lambda)\), \(y_0(\lambda)\), and \(z_0(\lambda)\) against wavelength on one graph, with a legend.
Task 2b. Compute \(l_0\), \(m_0\), and \(s_0\) with
lms_cmfs, and plot them in the same way.
Task 2c. Plot the D65 and fluorescent illuminants against wavelength on one graph.
Task 2d. Check. Report the largest of \(|\sum_\lambda x_0 - 1|\), \(|\sum_\lambda y_0 - 1|\), and \(|\sum_\lambda z_0 - 1|\), which must be below \(10^{-12}\). Compute the chromaticity of the D65 illuminant itself with equations (6) and (7). Its \((x, y)\) must be within 0.001 of the D65 white point \((0.3127, 0.3290)\) of equation (12). Report the chromaticity of the fluorescent illuminant in the same way.
The three plots, the sum check, and the chromaticities of the two illuminants with the difference from the D65 white point.
A chromaticity diagram shows colors by their \((x, y)\) chromaticity. Combinations of any two colors always fall along the straight line between their two points.
The most saturated colors come from spectra with energy at a single wavelength. The \(XYZ\) coordinates of such a pure spectral source at wavelength \(\lambda_0\) are
$$ \begin{bmatrix} X \\ Y \\ Z \end{bmatrix} = \begin{bmatrix} \int \delta(\lambda - \lambda_0)\, x_0(\lambda)\, d\lambda \\ \int \delta(\lambda - \lambda_0)\, y_0(\lambda)\, d\lambda \\ \int \delta(\lambda - \lambda_0)\, z_0(\lambda)\, d\lambda \end{bmatrix} = \begin{bmatrix} x_0(\lambda_0) \\ y_0(\lambda_0) \\ z_0(\lambda_0) \end{bmatrix} \ . \tag{8} $$Their chromaticities form a boundary for all visible colors. With the sampled data, they are the chromaticities of the 31 columns of the \((3, 31)\) array of color matching functions,
$$ (x, y, z)(\lambda_0) = \frac{\big(x_0(\lambda_0),\ y_0(\lambda_0),\ z_0(\lambda_0)\big)} {x_0(\lambda_0) + y_0(\lambda_0) + z_0(\lambda_0)} \ . \tag{9} $$Standard RGB primaries. One important set of RGB primaries is specified in the CIE 1931 standard, with the chromaticities
$$ \begin{aligned} R_{CIE\_1931} &= (0.73467,\ 0.26533,\ 0.0) \\ G_{CIE\_1931} &= (0.27376,\ 0.71741,\ 0.00883) \\ B_{CIE\_1931} &= (0.16658,\ 0.00886,\ 0.82456) \ . \end{aligned} \tag{10} $$These are useful for laboratory measurements, but not practical for displays. A more common set for displays is the Rec. 709 standard,
$$ \begin{aligned} R_{709} &= (0.640,\ 0.330,\ 0.030) \\ G_{709} &= (0.300,\ 0.600,\ 0.100) \\ B_{709} &= (0.150,\ 0.060,\ 0.790) \ . \end{aligned} \tag{11} $$White points. A white point is the chromaticity of a “white light” spectrum. The D65 and equal energy white points are
$$ (x_{wp}, y_{wp}, z_{wp})_{D65} = (0.3127,\ 0.3290,\ 0.3583) \ , \tag{12} $$ $$ (x_{wp}, y_{wp}, z_{wp})_{EE} = (0.3333,\ 0.3333,\ 0.3333) \ . \tag{13} $$Task 3a. Plot the chromaticities \((x, y)\) of the pure spectral sources of equation (9) as a solid line from 400 to 700 nm. Close the curve with a straight line from 700 nm back to 400 nm. Label a few points with their wavelengths.
Task 3b. On the same diagram, plot the three CIE 1931 primaries, connect them with straight lines to show the range of colors they can produce, and label each point. Do the same for the Rec. 709 primaries.
Task 3c. Plot and label the D65 and equal energy
white points. Use equal scales on the two axes
(ax.set_aspect("equal")).
Task 3d. Check. Compute the chromaticity of \(I_{EE}\) with equations (6) and (7). Its largest difference from \((1/3, 1/3, 1/3)\) must be below \(10^{-12}\).
The labeled chromaticity diagram, with x and y both from 0 to 1 and equal scales on the two axes, and the result of the check.
Color primary transformations. Most displays produce colors by adding three primaries. Let \(\vec R\), \(\vec G\), and \(\vec B\) hold the \(XYZ\) values of the primaries. Then
$$ \begin{bmatrix} X \\ Y \\ Z \end{bmatrix} = r \vec R + g \vec G + b \vec B = M \begin{bmatrix} r \\ g \\ b \end{bmatrix} \ , \qquad M = \begin{bmatrix} X_r & X_g & X_b \\ Y_r & Y_g & Y_b \\ Z_r & Z_g & Z_b \end{bmatrix} \ , \tag{14} $$and the \((r, g, b)\) needed for a color \((X, Y, Z)\) is
$$ \begin{bmatrix} r \\ g \\ b \end{bmatrix} = M^{-1} \begin{bmatrix} X \\ Y \\ Z \end{bmatrix} \ . \tag{15} $$For almost all primaries, some visible colors give a negative \(r\), \(g\), or \(b\). A display can only produce positive quantities of each primary, so it cannot produce all visible colors.
Chromaticity and white point of the primaries. Primaries are usually specified by their chromaticities and a white point. The chromaticities give only the direction of each vector. The \(XYZ\) values are the chromaticities scaled by constants \(\kappa_r\), \(\kappa_g\), and \(\kappa_b\):
$$ M = \begin{bmatrix} x_r & x_g & x_b \\ y_r & y_g & y_b \\ z_r & z_g & z_b \end{bmatrix} \begin{bmatrix} \kappa_r & 0 & 0 \\ 0 & \kappa_g & 0 \\ 0 & 0 & \kappa_b \end{bmatrix} \ . \tag{16} $$For a display, the white point is the chromaticity produced at \((r, g, b) = (1, 1, 1)\), or \((255, 255, 255)\) in 8 bits. (This definition differs slightly from the one in Step 3, but the same term is used for both.) Assume the brightest output has \(Y = 1\). Then the white point in \(XYZ\) is \((x_{wp}/y_{wp},\ 1,\ z_{wp}/y_{wp})\), and the constants are
$$ \begin{bmatrix} \kappa_r \\ \kappa_g \\ \kappa_b \end{bmatrix} = \begin{bmatrix} x_r & x_g & x_b \\ y_r & y_g & y_b \\ z_r & z_g & z_b \end{bmatrix}^{-1} \begin{bmatrix} x_{wp}/y_{wp} \\ 1 \\ z_{wp}/y_{wp} \end{bmatrix} \ . \tag{17} $$
The rows of PRIMARIES_709 are the chromaticities of R, G,
and B, so the matrix of chromaticities in equations (16) and (17) is
its transpose.
def rgb_to_xyz_matrix(primaries, white=None):
"""Return M (3, 3), column j = kappa_j * chromaticity of primary j (rows of primaries); kappa from equation (17) if white is given, else all 1."""
Task 4a. Assume your display uses the Rec. 709 primaries and a
D65 white point. Compute
M = rgb_to_xyz_matrix(PRIMARIES_709, WHITE_D65), the
matrix \(M_{709\_D65}\). Print it to 4 decimal places, with
\(\kappa_r\), \(\kappa_g\), and \(\kappa_b\).
Task 4b. Check. Report the largest entry of \(|M [1, 1, 1]^t - (x_{wp}/y_{wp},\ 1,\ z_{wp}/y_{wp})|\), and the largest difference between the chromaticities of the columns of \(M\) and the Rec. 709 primaries. Both must be below \(10^{-12}\).
\(M_{709\_D65}\), the three constants \(\kappa\), and the two checks.
You display a calibrated color image from a known illuminant spectrum and the reflectance at each pixel:
and the same for \(g\) and \(b\). Clip before the gamma correction.
The reflectances are scaled so that a white surface under
D65 has \(Y \approx 1\), so the values of R are
near 0.01. A white surface in this scaling has constant reflectance
\(R(\lambda) = 1/Y_{65}\), where \(Y_{65} = y_0 \, S_{65}\) is the
luminance of the D65 illuminant.
def reflectance_to_xyz(R, S, cmf):
"""Return (H, W, 3) XYZ of I = R * S, from R (H, W, 31), illuminant S (31,), and cmf (3, 31)."""
def xyz_to_rgb(XYZ, M):
"""Return (..., 3) linear (r, g, b) = M^(-1) (X, Y, Z), not clipped."""
def to_display(rgb, gamma):
"""Return (..., 3) uint8 round(255 * clip(rgb, 0, 1) ** (1 / gamma))."""
The color is the last axis, so an \((H, W, 3)\) array
XYZ times \(M^{-1}\) is XYZ @ inv(M).T.
Task 5a. Render the image under D65
(illum1). Show it and save it with
save_rgb. Report the fractions of pixels with a linear
component below 0, above 1, and either. Count a component as outside
only if it is outside by more than \(10^{-9}\).
Task 5b. Check. Send a \((1, 1, 31)\) white surface with every
entry \(1/Y_{65}\) through reflectance_to_xyz under
D65 and xyz_to_rgb. Report its \((r, g, b)\),
which must be within 0.005 of \((1, 1, 1)\).
Task 5c. Check. Compare your image with
load_rgb("data/img.png"). Report the number of the
\(170 \times 256 \times 3\) values that differ and the largest
difference, which must be at most 1 gray level.
xyz_to_rgb omits the transpose or uses \(M\) instead of
\(M^{-1}\).
The image under D65, the three clipping fractions, and the two checks.
Now change only the light source. Use the same \(M_{709\_D65}\), because the display does not change.
Task 6a. Render the image under fluorescent light
(illum2). Show it next to the D65 image of D4,
and save it.
Task 6b. Report the three clipping fractions of Task 5a. For both images, report the mean linear \((r, g, b)\) before clipping and the chromaticity \((x, y)\) of the mean \(XYZ\).
Task 6c. Describe how the colors of the two images differ, and where the differences are largest.
The fluorescent image next to the D65 image, the clipping fractions, the means for both images, and your description.
You make a chromaticity diagram like that of Step 3 that also shows
the colors your display can produce: the color of every point of the
plane \(X + Y + Z = 1\) that the display can reproduce. Assume the
Rec. 709 primaries lie exactly on this plane, so \(M_{709}\) is given
by equations (11) and (16) with \(\kappa_r = \kappa_g = \kappa_b = 1\),
which is rgb_to_xyz_matrix(PRIMARIES_709).
def fill_chromaticity(step, M):
"""Map grid x = j * step, y = i * step (0 to 1), z = 1 - x - y to (r, g, b) = M^(-1) (x, y, z); set all three to 1 where any is negative.
returns rgb, (N, N, 3) with N = round(1 / step) + 1; inside, (N, N) bool, True where r, g, b are all >= 0
"""
Build the grid with np.meshgrid, so that \(x\) increases
with the column and \(y\) with the row. A point where \(r\), \(g\),
or \(b\) is negative cannot be produced by these primaries, and
it is shown as white.
Task 7a. Compute fill_chromaticity(0.005, M709) and
apply to_display with \(\gamma = 2.2\). Show it with
ax.imshow(img, origin="lower", extent=(-0.0025, 1.0025, -0.0025, 1.0025)),
so that pixel \((i, j)\) is centered at \((x, y) = (0.005 j, 0.005 i)\).
Label the axes \(x\) and \(y\).
Task 7b. On the same axes, plot the chromaticities of the pure spectral sources from Step 3. The axes must be scaled correctly for the two to line up. The result should be a color filled triangle inside the pure spectral source outline, with its corners at the Rec. 709 primaries.
Task 7c. Check. Report the number of grid points inside the triangle times \(0.005^2\), and the area of the triangle with corners at the three Rec. 709 primaries. The two must agree within 0.001. Apply \(M_{709}^{-1}\) to the three primaries and report the largest difference from the identity matrix, which must be below \(10^{-12}\).
The color chromaticity diagram with the pure spectral source outline, and the two checks.
You directed your AI assistant to write seven functions:
lms_cmfs, chromaticity,
rgb_to_xyz_matrix, reflectance_to_xyz,
xyz_to_rgb, to_display, and
fill_chromaticity.
The specification you gave your AI assistant, quoted. Show any correction you made during the build and say what was wrong.
Answer each in a few sentences, citing your own figures and numbers.
Your answers to the five questions.
Submit two files through Brightspace:
lab8.py, as a plain .py file.
Do not paste the code into the report, and do not send a zip file.
Commit lab8.py to your
image-processing-labs repository under lab8
and push it before you submit.
Concise and clear beats long.