ECE 63700: Digital Image Processing I

Lab 6: Pointwise Operations and Gamma

Overview What the lab is about, the data, and the ground rules.

What This Lab Is About

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.

The Data

lab6-data.zip (220 KB) holds four 8-bit grayscale PNG images:

  • race.png, 384 pixels wide and 256 tall.
  • kids.png, 366 pixels wide and 242 tall, with low contrast.
  • linear.png, 256 pixels wide and 384 tall, stored on a linear intensity scale.
  • gamma15.png, the same size, gamma corrected for a display with \(\gamma = 1.5\).

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.

Ground Rules

  • All code goes in 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.
  • Use the exact signatures on this page, each with a short docstring.
  • Gray levels are integers from 0 to 255. Read each image as 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.
  • No Python for loop over pixels or gray levels. A pointwise operation is a table of 256 values, applied with apply_table.
  • Show every image with vmin=0, vmax=255, a colorbar, and labeled axes.
Give the AI the equations, array types, rounding rule, and signatures. Run the checks in Steps 2, 4, 5, 8, and 9 before you interpret any image.
Parameters for the Experiments The settings for every hand-in item.

Parameters for Every Experiment

ItemExperimentInputFunction and settings
D1Histograms (Step 2) race.png, kids.png histogram, bins at gray levels 0 to 255
D2Histogram equalization (Step 3) kids.png empirical_cdf, equalize, \(L = 256\)
D3Checks of the equalization (Step 4) kids.png and its equalized image empirical CDF against \((i+1)/256\) for \(i = 0, \dots, 255\)
D4Contrast stretching (Step 5) kids.png stretch, \(T_1\) and \(T_2\) of your choice that make the output span 0 to 255
D5Gamma 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
D6Gamma correction (Step 8) linear.png gamma_correct with the \(\gamma\) of D5 from the half pattern with lines
D7Changing the gamma (Step 9) gamma15.png change_gamma from \(\gamma = 1.5\) to the \(\gamma\) of D5
Module 1: Histograms, Equalization, and Contrast Stretching Steps 1 to 5. Set up the code, compute histograms, equalize a histogram, check the result, and stretch the contrast.

Step 1: Set Up lab6.py

Copy 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]

Step 2: Histograms

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.

HAND IN · D1

The two images and their labeled histograms, and the results of the two checks.

Step 3: Histogram Equalization

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.

HAND IN · D2

The labeled plot of \(\hat F_X(i)\) for kids.png, the equalized image, its labeled histogram, and your comparison.

Step 4: Check the Equalization

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.

Pass criteria. \(D\) is much smaller for the equalized image, but not 0. The number of distinct gray levels never rises.
HAND IN · D3

The two values of \(D\), the plot of the CDFs and the line, the two counts of distinct gray levels, and the order check.

Step 5: Contrast Stretching

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.

T₁ T₂ 255 0 255 input x output f(x)
The contrast stretching map.

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\).

HAND IN · D4

Your \(T_1\) and \(T_2\), the stretched image and its labeled histogram, your comparison, and the results of the checks.

Module 2: Gamma Steps 6 to 11. Learn the gamma model, measure the gamma of your display, gamma correct an image, change the gamma of an image, and answer the questions.

Step 6: Gamma

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.

Step 7: Measure the Gamma of Your Display

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.

Set up the display first.
  • Each line must be exactly 1 or 2 display pixels wide. Check this with a screenshot of the pattern, zoomed in: the lines must be sharp and evenly spaced.
  • Use 100% browser zoom (Ctrl+0, or Cmd+0 on a Mac). The page shows the device pixel ratio it found.
  • Turn off Night Shift, Night Light, True Tone, automatic brightness, and blue light filters. Set a comfortable brightness and leave it.
  • Use a built-in display or external monitor, not a projector, and match on the page itself, not on a screenshot.
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.

HAND IN · D5

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\).

Step 8: Gamma Correct a Linear Image

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.

HAND IN · D6

The original and corrected images, labeled with the \(\gamma\) used, the formula, and the result of the check.

Step 9: Change the Gamma of an Image

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.

HAND IN · D7

Your derivation, the original and converted images, labeled with the two values of \(\gamma\), and the result of the check.

Step 10: Your Specification

You directed your AI assistant to write eight functions: histogram, empirical_cdf, equalize, stretch, gamma_from_match, power_law, gamma_correct, and change_gamma.

HAND IN · D8

The specification you gave your AI assistant, quoted, with any corrections and what was wrong.

Step 11: Questions to Answer

Answer each in a few sentences. Cite your own images and numbers.

  1. Step 3 shows that \(Y = F_X(X)\) is exactly uniform. Why is the histogram of your equalized image not exactly flat? Use \(D\) and the counts of distinct gray levels from D3.
  2. When does contrast stretching give a better image than histogram equalization? Compare D2 and D4, and say what each method does to the regions of kids.png that hold the most pixels.
  3. Why are images stored on a gamma corrected scale rather than a linear one, even on a display that could show a linear scale? Explain with 8-bit quantization and the response of the eye. Count how many of the gray levels 0 to 63 your corrected linear.png uses, and find the outputs for input gray levels 1, 2, and 3.
  4. What happens if you gamma correct an image twice? Correct your corrected linear.png again, display it, and explain it by the exponent of the combined operation.
  5. Convert 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?
HAND IN · D9

Your answers to the five questions.

Deliverables What to submit, and where each item comes from.

What to Hand In

Submit two files through Brightspace.

  1. A report, as a single PDF, labeled "Lab 6", containing the items listed below in this order.
  2. Your 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.

  1. Your name and the link to your GitHub repository.
  2. D1 race.png and kids.png with their labeled histograms, and the results of the two checks.
  3. D2 The plot of \(\hat F_X(i)\) for kids.png, the equalized image, its histogram, and your comparison.
  4. D3 The two values of \(D\), the plot of the CDFs, the counts of distinct gray levels, and the order check.
  5. D4 Your \(T_1\) and \(T_2\), the stretched image and its histogram, your comparison, and the checks.
  6. D5 Your display and its device pixel ratio, the matched gray levels, the derivation, and the three values of \(\gamma\).
  7. D6 The original and gamma corrected linear.png, the formula, and the round trip check.
  8. D7 The derivation, the original and converted gamma15.png, and the check.
  9. D8 The specification you gave your AI assistant, quoted, with any corrections you made during the build.
  10. D9 Your answers to the five questions.

Concise and clear beats long.