Due: Friday, Feb. 26, 2027.
This laboratory discusses point operations on images. A point operation remaps pixels at one intensity to a different intensity. Point operations make up an important class of techniques for image enhancement.
In Module 1 you compute the histogram, which shows the distribution of pixel intensities in an image, and you enhance an image by histogram equalization and contrast stretching. In Module 2 you determine the gamma of your display, which describes its nonlinear behavior, and then apply gamma correction to compensate for this nonlinearity.
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, your checks, and your reading of the results.
lab6-data.zip (220 KB) holds four 8-bit grayscale PNG images:
In the folder that holds lab6.py:
wget https://charlesbouman.org/ece63700/labs/lab6-data.zip unzip lab6-data.zip
Module 2 also uses the page gamma-match.html.
lab6.py. Use the labs
conda environment from Lab 2, with NumPy (not PyTorch) and
matplotlib.lab6.py holds only functions. Run experiments from a
separate script that imports it.uint8 and do not scale it. Every function that
returns an image returns uint8, rounded to the nearest
gray level. \(T_1\), \(T_2\), and \(g\) are in gray levels.for loop over pixels or gray levels. A
pointwise operation is a table of 256 values, applied with
apply_table.vmin=0, vmax=255,
a colorbar, and labeled axes.| Item | Experiment | Input | Function and settings |
|---|---|---|---|
| D1 | Histograms (Step 2) | race.png, kids.png |
histogram, bins at gray levels 0 to 255 |
| D2 | Histogram equalization (Step 3) | kids.png |
empirical_cdf, equalize, \(L = 256\) |
| D3 | Checks of the equalization (Step 4) | kids.png and its equalized image |
empirical CDF against \((i+1)/256\) for \(i = 0, \dots, 255\) |
| D4 | Contrast stretching (Step 5) | kids.png |
stretch, \(T_1\) and \(T_2\) of your choice that make
the output span 0 to 255 |
| D5 | Gamma of your display (Step 7) | gamma-match.html |
start at \(g = 127\); the half pattern with lines, the half
pattern as a checkerboard, and the quarter pattern;
gamma_from_match |
| D6 | Gamma correction (Step 8) | linear.png |
gamma_correct with the \(\gamma\) of D5 from the
half pattern with lines |
| D7 | Changing the gamma (Step 9) | gamma15.png |
change_gamma from \(\gamma = 1.5\) to the
\(\gamma\) of D5 |
lab6.pyCopy these helpers into lab6.py.
import numpy as np
from PIL import Image
def load_image(path):
"""Read an 8-bit grayscale image as an (H, W) uint8 array."""
return np.asarray(Image.open(path).convert("L"), dtype=np.uint8)
def save_image(x, path):
"""Write an (H, W) uint8 array as an 8-bit grayscale PNG."""
Image.fromarray(np.asarray(x, dtype=np.uint8)).save(path)
def to_uint8(y):
"""Round an array of gray levels, clip it to 0 to 255, and return uint8."""
return np.clip(np.round(y), 0, 255).astype(np.uint8)
def apply_table(x, table):
"""Apply a pointwise operation given as a table of 256 values: output = table[x]."""
table = np.asarray(table)
if table.shape != (256,):
raise ValueError("table must have 256 entries")
return table[x]
The histogram of a digital image shows the distribution of its pixel intensities. Let \(X_s\) be the pixel at position \(s\) in the lattice \(S\), taking the values \(0, \dots, L-1\) with \(L = 256\). The histogram of the image is
$$ h(i) = \sum_{s \in S} \delta(X_s - i) \ , \qquad i = 0, \dots, L-1 \ , \tag{1} $$where \(\delta(0) = 1\) and \(\delta(k) = 0\) for \(k \neq 0\). So \(h(i)\) is the number of pixels that take on the value \(i\).
def histogram(x):
"""Return the (256,) int64 histogram h of a uint8 image; h[i] counts gray level i."""
histogram does not call np.histogram, because
the check uses it.
Task 2a. Display race.png and
kids.png, and plot each histogram as a bar plot with one
bar per gray level 0 to 255, with labeled axes and a title.
Task 2b. Check. Confirm that each histogram sums to the number
of pixels. Count the bins where it differs from
np.histogram(x, bins=256, range=(0, 256)). The count must
be 0.
The two images and their labeled histograms, and the results of the two checks.
The objective of histogram equalization is to transform the image so that the output histogram is uniform over the full range of gray values. Think of a pixel as a random variable \(X\) with cumulative distribution \(F_X(x) = P\{X \le x\}\), and form \(Y = F_X(X)\) by mapping \(X\) through its own cumulative distribution function. Then for \(0 \le y \le 1\)
$$ P\{Y \le y\} = P\{X \le F_X^{-1}(y)\} = F_X\big(F_X^{-1}(y)\big) = y \ , $$so \(Y\) has a uniform distribution on \([0, 1]\). Therefore the histogram of an image can be equalized by mapping the pixels through their cumulative distribution function. We estimate it from the histogram by the empirical CDF,
$$ \hat F_X(i) = \frac{\sum_{j=0}^{i} h(j)}{\sum_{j=0}^{L-1} h(j)} \ , \qquad i = 0, \dots, L-1 \ . \tag{2} $$The normalization term assures that \(\hat F_X(L-1) = 1\). However, \(Y_s = \hat F_X(X_s)\) may not extend over the full range of gray levels. To correct this, let \(Y_{\min}\) and \(Y_{\max}\) be the minimum and maximum of \(Y_s\) over the image, and form
$$ Z_s = (L-1) \, \frac{\hat F_X(X_s) - Y_{\min}}{Y_{\max} - Y_{\min}} \ , \tag{3} $$rounded to the nearest integer. Histogram equalization is the transformation from \(X_s\) to \(Z_s\).
def empirical_cdf(x):
"""Return the (256,) float64 empirical CDF F of a uint8 image, so F[255] = 1."""
def equalize(x):
"""Return the (H, W) uint8 histogram equalized image of equation (3)."""
Task 3a. Plot \(\hat F_X(i)\) for kids.png, for
\(i = 0, \dots, 255\).
Task 3b. Equalize kids.png. Display the result and
plot its histogram, with labeled axes and a title.
Task 3c. Compare the image and its histogram to the originals from D1.
The labeled plot of \(\hat F_X(i)\) for kids.png, the
equalized image, its labeled histogram, and your comparison.
A flat histogram has the empirical CDF \((i+1)/256\). The distance from flat is
$$ D = \max_{0 \le i \le 255} \left| \hat F(i) - \frac{i+1}{256} \right| \ . $$
Task 4a. Compute \(D\) for kids.png and its
equalized image. Plot both empirical CDFs and the line on one graph.
Task 4b. Count the distinct gray levels in both images. Confirm that the equalization is a pointwise operation that does not decrease: pixels with the same input gray level have the same output gray level, and a larger input never gives a smaller output.
The two values of \(D\), the plot of the CDFs and the line, the two counts of distinct gray levels, and the order check.
Contrast stretching maps the darker pixels in \([0, T_1]\) to zero (black) and the lighter pixels in \([T_2, 255]\) to white. Then the pixels in \([T_1, T_2]\) are stretched out to use the full scale of \([0, 255]\):
$$ f(x) = \begin{cases} 0 & x \le T_1 \\ 255 \, \dfrac{x - T_1}{T_2 - T_1} & T_1 < x < T_2 \\ 255 & x \ge T_2 \ , \end{cases} $$rounded to the nearest integer.
If a pixel transformation is a one-to-one function \(y = f(x)\), then the input and output histograms are approximately related by
$$ h_{\text{out}}(y) \approx \left. \frac{h_{\text{in}}(x)}{|f'(x)|} \right|_{x = f^{-1}(y)} \ , \tag{4} $$where \(f^{-1}(y)\) is rounded to the nearest integer. The map \(f\) is not one-to-one, so the output histogram may have spikes at 0 and 255. Between them \(f'\) is the constant \(255/(T_2 - T_1)\), so the output histogram should be a stretched and rescaled version of the input histogram.
def stretch(x, T1, T2):
"""Return the (H, W) uint8 contrast stretched image f(x), for 0 <= T1 < T2 <= 255."""
Task 5a. Choose \(T_1\) and \(T_2\) so that the output histogram
of kids.png spans the full range from 0 to 255. Report
your choice. Display the output image and its histogram, labeled, and
compare them with the originals from D1.
Task 5b. Check. Confirm that the output has smallest gray level 0 and largest 255. For each input gray level \(i\) with \(T_1 < i < T_2\), the output bin \(f(i)\) must hold exactly \(h_{\text{in}}(i)\) pixels. Count the gray levels where this fails. Confirm that \(h_{\text{out}}(0)\) equals the number of input pixels at or below \(T_1\), and \(h_{\text{out}}(255)\) the number at or above \(T_2\).
Your \(T_1\) and \(T_2\), the stretched image and its labeled histogram, your comparison, and the results of the checks.
For a long time the most widely used displays were cathode ray tubes (CRTs). In a CRT, the relationship between applied voltage \(V\) and light intensity \(I\) is a power law,
$$ I = V^{\gamma} \ . $$The exponent is the gamma \(\gamma\) of the display, and a typical CRT gamma is around 2.5. LCD and OLED displays have very different physical properties, but they use correction tables to give a similar response. Most current displays follow the sRGB standard, which is close to \(\gamma = 2.2\). For an 8-bit pixel value \(x\), the light intensity \(y\) produced by the display is
$$ y = 255 \left( \frac{x}{255} \right)^{\gamma} \ . \tag{5} $$Because of this power law, an image representing linearly scaled light intensity appears too dark on the display, especially for small and mid range pixel values. Gamma correction compensates by applying the inverse of equation (5), raising \(x/255\) to the power \(1/\gamma\), before display.
There is another important reason for a gamma corrected scale. The human visual system is more sensitive to changes in light intensity at low background illumination than at high. Quantizing a linearly scaled image to 8 bits produces easily perceived gray level steps in dark regions, called false contours. The gamma corrected scale very nearly matches a perceptually uniform scale. Therefore most digital cameras and scanners gamma correct images before storing them, and most digital images, such as JPEG and MPEG video, are already on a gamma corrected scale.
The method visually compares a pattern of black and white lines to a fixed gray level. Viewed from a distance, the pattern appears as a uniform gray because of the blur of the optics of the eye. If half the lines are white, the perceived intensity of the pattern is
$$ I_c = \frac{I_{255} + 0}{2} \ , $$where \(I_{255}\) is the intensity of level 255. By equation (5), gray level \(g\) produces \(I_g = I_{255} \, (g/255)^{\gamma}\). The two match when \(I_g = I_c\), which is when
$$ \left( \frac{g}{255} \right)^{\gamma} = \frac{1}{2} \ . \tag{6} $$gamma-match.html shows bands of black and white lines next to solid gray bands. A slider sets the gray level \(g\). At the match the bands disappear when viewed from a distance. The lines can be 1 or 2 display pixels wide. The page also offers a checkerboard version of the half pattern, and a quarter pattern with one white line in four, of intensity \(I_{255}/4\). A magnifier shows the pixel values around the mouse.
def gamma_from_match(g, fraction):
"""Return the display gamma given matched gray level g (0 < g < 255) and white fraction 0.5 or 0.25."""
Task 7a. Open the half pattern of lines. Start at \(g = 127\), step back, and adjust \(g\) until the bands disappear. Match 3 times, once starting from a dark gray and once from a light gray. Report the 3 values of \(g\) and their mean.
Task 7b. Derive an expression for \(\gamma\) in terms of \(g\) from equation (6), and compute \(\gamma\) from the mean \(g\). Also compute how much \(\gamma\) changes when \(g\) changes by one gray level.
Task 7c. Check. Repeat with the checkerboard and the quarter pattern, and compute \(\gamma\) from each. If the display follows the power law and treats each pixel independently, the three values agree.
The make and model of your display and the device pixel ratio that the page shows, the matched gray levels, your derivation, and the three values of \(\gamma\).
linear.png is stored with a linear scaling. To correct it,
apply the inverse of equation (5) with the \(\gamma\) of your display.
def power_law(x, p):
"""Return 255 (x/255)^p as float64, not rounded, so it can be inverted exactly."""
def gamma_correct(x, gamma):
"""Return the (H, W) uint8 gamma correction of a linear image for a display with this gamma."""
Task 8a. Display linear.png.
Task 8b. Gamma correct linear.png with the
\(\gamma\) from Task 7b, display the result, and write down the
formula you used.
Task 8c. Check. Apply power_law with exponent
\(1/\gamma\) and then \(\gamma\) to linear.png, without
rounding. The largest absolute difference from linear.png
must be below \(10^{-10}\) gray levels.
The original and corrected images, labeled with the \(\gamma\) used, the formula, and the result of the check.
Sometimes an image is gamma corrected, but not for the gamma of your
display. gamma15.png is gamma corrected for
\(\gamma = 1.5\). To reproduce it accurately, you must change its gamma
correction.
def change_gamma(x, gamma_in, gamma_out):
"""Convert a uint8 image gamma corrected for gamma_in to one corrected for gamma_out."""
Task 9a. Derive the formula that converts
gamma15.png for your display. Compute it in one step from
the uint8 input, and round only once.
Task 9b. Display gamma15.png and the converted
image.
Task 9c. Check. Count the pixels that
change_gamma(x, 1.5, 1.5) changes. The count must be 0.
Your derivation, the original and converted images, labeled with the two values of \(\gamma\), and the result of the check.
You directed your AI assistant to write eight functions:
histogram, empirical_cdf,
equalize, stretch,
gamma_from_match, power_law,
gamma_correct, and change_gamma.
The specification you gave your AI assistant, quoted, with any corrections and what was wrong.
Answer each in a few sentences. Cite your own images and numbers.
kids.png that hold the most
pixels.linear.png uses, and find the outputs for input gray
levels 1, 2, and 3.linear.png again, display it, and explain it
by the exponent of the combined operation.gamma15.png in two steps: first to a linear
scale, rounded to uint8, then with
gamma_correct. Compare with your one-step result of
D7. Count the distinct gray levels of the intermediate image and of
both results, and the pixels where the results differ. Which method
is better, and why?Your answers to the five questions.
Submit two files through Brightspace.
lab6.py, as a plain .py file.
Do not paste code into the report or send a zip file. Commit and push
lab6.py to your image-processing-labs
repository under lab6 before you submit.
race.png and kids.png with their labeled
histograms, and the results of the two checks.kids.png, the
equalized image, its histogram, and your comparison.linear.png, the
formula, and the round trip check.gamma15.png, and the check.Concise and clear beats long.