Lab evaluation prep, assignment by assignment

Each assignment has six parts: concept → solution code → real outputs → line-by-line walkthrough → "what if" questions → viva questions. Every output image on this page was produced by running the exact code shown.

Sample images: cameraman.png (512×512 grayscale), coffee.png (600×400 colour), page.png (unevenly lit text), moon.png (low contrast), hubble.png (very dark; Hubble deep field converted to grayscale and resized to 600×523) cameraman_noisy.png (cameraman + Gaussian noise, σ = 20), coins.png, the textures brick/grass/gravel.png, and test_pattern.png (three flat grey levels, made with NumPy for the noise histograms). They all come from scikit-image (skimage.data.camera(), .coffee(), .page(), .moon(), .hubble_deep_field(), .coins(), .brick()…) if you want the same inputs.

Assignment 1 · Thresholding

Convert a grayscale image to a binary image

Case 1: use the mean intensity of the image as the threshold.

Case 2: take the threshold value as input from the user.

01Concept explanation

1.1 What a digital image actually is

A digital image is a 2-D function f(x, y). The pair (x, y) is a location (row, column) and f(x, y) is the intensity (grey level) at that location. In the computer it is just a matrix of numbers with M rows and N columns. Each entry is a pixel (picture element).

In Python, OpenCV loads an image as a NumPy array. For a grayscale image the array has shape (rows, cols) and data type uint8 (unsigned 8-bit integer), so every pixel is a whole number from 0 (black) to 255 (white).

Syllabus link · Image formation, sampling and quantization

Simple image formation model: the light reaching the camera is the product of how much light falls on the scene and how much the object reflects.

f(x, y) = i(x, y) · r(x, y) 0 < i < ∞ (illumination), 0 < r < 1 (reflectance)

This is why the same object can look dark in shadow and bright in sunlight, which is exactly what breaks a single global threshold (see the uneven-lighting example in Part 5).

Sampling digitises the coordinates: it decides how many pixels (M × N) we use, which sets spatial resolution. Quantization digitises the amplitude: it decides how many grey levels each pixel can take. With k bits per pixel there are L = 2k levels, numbered 0 … L−1. Storage needed = M × N × k bits.

Light, luminance, brightness, contrast: luminance is the measurable light energy an observer perceives from a source; brightness is the subjective sensation of it (it depends on surroundings, as in simultaneous contrast); contrast is the difference between the brightest and darkest parts of an image, which in a histogram shows up as how widely the values are spread.

1.2 Three types of images

TypeValues per pixelBits / pixelNumPy shape (OpenCV)Size of a 512×512 image
Binary2 values: 0 or 1 (stored as 0 / 255 in OpenCV)1 (in theory)(512, 512), uint832 KB in theory (1 bit); 256 KB as uint8 in memory
Grayscale256 levels, 0–2558(512, 512), uint8256 KB
Colour (RGB)3 values per pixel (B, G, R in OpenCV)24 (8 × 3)(512, 512, 3), uint8768 KB

A binary image is the simplest: each pixel says only "object" or "background". Converting grayscale to binary loses information on purpose. We keep only the separation between the thing we care about and everything else. That makes it the first step of segmentation, OCR, counting objects, and building masks.

1.3 The histogram: the tool for choosing a threshold

The histogram counts how many pixels have each intensity value.

Formula · Histogram h(r_k) = n_k n_k = number of pixels with intensity r_k, k = 0 … L−1 p(r_k) = n_k / (M·N) normalised histogram (≈ probability of level r_k), Σ p(r_k) = 1

When an image has a dark object on a bright background (or the reverse), its histogram tends to be bimodal: one hump for the object and one for the background. A good threshold sits in the valley between the two humps.

1.4 Thresholding: the core idea

Thresholding is a point operation. Each output pixel depends only on the input pixel at the same location. We pick one number T and compare every pixel against it:

Formula · Global thresholding g(x, y) = 1 (white, 255) if f(x, y) > T g(x, y) = 0 (black) if f(x, y) ≤ T

"Global" means one T for the whole image. If T changes from place to place it is called local / adaptive thresholding.

Step by step:

  1. Read the image as grayscale (one channel, 0–255).
  2. Decide the threshold T: the mean (Case 1) or the user's value (Case 2).
  3. Visit every pixel. If it is greater than T write 255, otherwise write 0.
  4. Display and save the result. The output has only two values, so it is binary.

1.5 Case 1: mean intensity as the threshold

Formula · Mean intensity T = (1 / (M·N)) · Σ_x Σ_y f(x, y) = Σ_k r_k · p(r_k)

Why it makes sense: the mean is the image's "average brightness", so pixels brighter than average become white and darker ones become black. It needs no user input and adapts to each image.

Limitation: the mean is pulled towards whichever region is larger. If the background covers 90% of the image, the mean sits close to the background's grey level instead of in the valley, and part of the background gets misclassified. For the cameraman image the mean is 129.06, close to Otsu's optimum of 102, so it works reasonably well here.

1.6 Case 2: user-defined threshold

The user chooses T (0–255), usually by looking at the histogram or by trial and error. A lower T makes more pixels white, and a higher T makes more pixels black. This gives full control, but the result is subjective and has to be retuned for each image.

Syllabus · the rest of "Thresholding" (Image Segmentation unit)

The assignment covers only two ways of picking T. The syllabus topic "Thresholding" also includes the following methods.

(a) Basic iterative global thresholding (Gonzalez & Woods). It starts from the mean, so it is a direct upgrade of Case 1:

  1. Choose an initial estimate T, normally the mean intensity.
  2. Split the pixels into G1 (f > T) and G2 (f ≤ T).
  3. Compute the mean of each group, m1 and m2.
  4. Set T = (m1 + m2) / 2.
  5. Repeat steps 2–4 until T changes by less than a small ΔT.

(b) Otsu's method: tries every k from 0 to 255 and picks the one that best separates the two classes. It maximises the between-class variance (equivalently, it minimises within-class variance):

σ_B²(k) = P1(k) · P2(k) · [m1(k) − m2(k)]² T_otsu = argmax_k σ_B²(k) P1, P2 = fraction of pixels in each class; m1, m2 = mean of each class

In OpenCV: cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU). The 0 is ignored, and the computed T comes back as the first return value.

(c) Adaptive (local) thresholding: computes a separate T for every pixel from its neighbourhood. This handles uneven illumination (the i(x,y) term in the image formation model above):

T(x, y) = mean (or Gaussian-weighted mean) of the blockSize × blockSize neighbourhood − C

(d) Multiple thresholds: two thresholds T1 < T2 split the image into three classes (dark, middle, bright). This is useful when the histogram has three modes.

1.7 Comparing ways to choose T

MethodHow T is chosenAutomatic?StrengthWeakness
Mean (Case 1)Average of all pixelsYesOne line of code, fastBiased towards the larger region; ignores histogram shape
User value (Case 2)Typed inNoFull control; can be tuned by eyeSubjective; must be retuned per image
Iterative (mean-split)T = (m1 + m2)/2, repeatedYesMoves from the mean towards the valleyStill one global T
OtsuMaximise between-class varianceYesOptimal for bimodal histogramsStruggles with unimodal histograms, tiny objects and uneven lighting
AdaptiveLocal mean − C, per pixelYes (blockSize and C set by hand)Handles shadows and uneven illuminationSlower; noisy in flat regions; two parameters to tune

1.8 OpenCV threshold types (the type argument)

FlagIf src > TOtherwiseResult is binary?
cv2.THRESH_BINARYmaxval0Yes (used in this assignment)
cv2.THRESH_BINARY_INV0maxvalYes (inverted)
cv2.THRESH_TRUNCTsrc (unchanged)No: brights are clipped at T
cv2.THRESH_TOZEROsrc (unchanged)0No: darks become 0
cv2.THRESH_TOZERO_INV0src (unchanged)No
+ cv2.THRESH_OTSUAdded to one of the above. OpenCV computes T itself and ignores the T you pass.

02Solution

One program covers both cases: Case 1 is done manually with NumPy and Case 2 with OpenCV's cv2.threshold. If you're asked for either case "using a built-in function", swap the two lines (both forms are shown in Part 4).

a1_solution.py
# Assignment 1: Convert a grayscale image to a binary image
#   Case 1: threshold = mean intensity of the image
#   Case 2: threshold entered by the user
import cv2
import numpy as np

IMG_PATH = "cameraman.png"          # change to your own image

# 1. Read the image directly as grayscale (flag 0 == cv2.IMREAD_GRAYSCALE)
img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:                     # imread does NOT raise an error on a bad path
    raise FileNotFoundError(f"Could not read {IMG_PATH}")
print("Shape:", img.shape, "| dtype:", img.dtype,
      "| min:", img.min(), "| max:", img.max())

# ---------------- Case 1: mean intensity as threshold ----------------
T_mean = np.mean(img)               # average of all pixel values (a float)
print(f"Case 1 -> mean intensity threshold T = {T_mean:.2f}")

# Rule: pixel > T  -> 255 (white / object),  else -> 0 (black / background)
binary_mean = np.where(img > T_mean, 255, 0).astype(np.uint8)

# ---------------- Case 2: threshold from the user ----------------
T_user = int(input("Enter threshold value (0-255): "))
if not 0 <= T_user <= 255:
    raise ValueError("Threshold must lie between 0 and 255")

# Same rule, using OpenCV's built-in function.
# Returns (threshold_used, output_image)
ret, binary_user = cv2.threshold(img, T_user, 255, cv2.THRESH_BINARY)
print(f"Case 2 -> user threshold T = {ret}")

# Percentage of white pixels: a quick sanity check of each result
for name, b in [("mean", binary_mean), ("user", binary_user)]:
    print(f"White pixels ({name} T): {100 * np.count_nonzero(b) / b.size:.1f}%")

# ---------------- Display and save ----------------
cv2.imshow("Grayscale input", img)
cv2.imshow("Case 1 - mean threshold", binary_mean)
cv2.imshow("Case 2 - user threshold", binary_user)
cv2.imwrite("a1_binary_mean.png", binary_mean)
cv2.imwrite("a1_binary_user.png", binary_user)
cv2.waitKey(0)                      # wait for any key press
cv2.destroyAllWindows()

Console output (user typed 100):

Shape: (512, 512) | dtype: uint8 | min: 0 | max: 255
Case 1 -> mean intensity threshold T = 129.06
Enter threshold value (0-255): 100
Case 2 -> user threshold T = 100.0
White pixels (mean T): 63.7%
White pixels (user T): 68.1%

Version without built-in functions (if the examiner asks "do it with loops")

a1_loops.py
# Assignment 1, "without built-in functions" version (pixel-by-pixel loops)
import cv2
import numpy as np

img = cv2.imread("cameraman.png", 0)
rows, cols = img.shape

# Mean intensity computed by hand: sum of all pixels / number of pixels
total = 0
for i in range(rows):
    for j in range(cols):
        total += int(img[i, j])     # int() avoids uint8 overflow while adding
T = total / (rows * cols)

binary = np.zeros((rows, cols), dtype=np.uint8)   # start all black
for i in range(rows):
    for j in range(cols):
        if img[i, j] > T:
            binary[i, j] = 255                     # white if above threshold

print("Mean threshold:", round(T, 2))
cv2.imwrite("a1_binary_loops.png", binary)

This gives exactly the same image as the NumPy version (mean = 129.06) but is far slower, because Python visits all 262,144 pixels one at a time. NumPy's np.where does the same comparison in compiled C code. That makes it vectorised.

Optional add-on · Otsu & adaptive (syllabus, not asked in the assignment)
# Otsu: T is computed automatically, the 0 we pass is ignored
T_otsu, bin_otsu = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print("Otsu threshold:", T_otsu)        # 102.0 for cameraman

# Adaptive: a separate threshold for every pixel from its 25x25 neighbourhood
bin_adapt = cv2.adaptiveThreshold(img, 255,
                                  cv2.ADAPTIVE_THRESH_GAUSSIAN_C,  # or ADAPTIVE_THRESH_MEAN_C
                                  cv2.THRESH_BINARY,
                                  25,     # blockSize: odd, >= 3
                                  10)     # C: subtracted from the local mean

# Basic iterative global thresholding (starts from the mean = Case 1)
T = img.mean()
while True:
    m1 = img[img > T].mean(); m2 = img[img <= T].mean()
    T_new = (m1 + m2) / 2
    if abs(T_new - T) < 0.5: break
    T = T_new
print("Iterative threshold:", round(T_new, 2))   # 103.07 for cameraman

03Output images

Input: cameraman.png, 512×512 grayscale, values 0–255
Input: cameraman.png, 512×512 grayscale, values 0–255
Case 1: T = mean = 129.06 → 63.7% white
Case 1: T = mean = 129.06 → 63.7% white
Case 2: user T = 100 → 68.1% white
Case 2: user T = 100 → 68.1% white

What changed: the input has 256 grey levels. Each output has only two (0 and 255). Every pixel brighter than T became pure white and every pixel at or below T became pure black.

Why it looks like this: the sky and the light grass are brighter than both thresholds, so they turn white. The man's coat, hair and the tripod are very dark (mostly below 40), so they stay black whichever T we use. The grass is the interesting part: its values spread roughly from 110 to 170, straddling the mean threshold of 129, so small variations push some pixels above and some below T. That is why it breaks up into a speckled texture.

Case 1 vs Case 2: lowering T from 129 to 100 means pixels with values 101–129 now count as "bright". More of the grass and the distant buildings turn white (63.7% → 68.1%) and the speckle in the grass reduces. The silhouette of the man is the same in both, because his pixels are far below either threshold.

Where the thresholds sit on the histogram

Histogram with thresholds
The tall peak on the left is the dark coat and the broad hump on the right is the sky and grass. Otsu (102) lands near the valley; the mean (129) sits further right because the large bright region pulls it up. User T = 100 is almost at Otsu's choice, which is why Case 2 looks cleaner.
Say this when you show the output

"The mean intensity of this image is 129, so every pixel above 129 is set to 255 and the rest to 0. The man and tripod are very dark, so they stay black. The sky is bright, so it turns white. The grass has mid-grey values near the threshold, so it becomes speckled. When I lower the threshold to 100, more mid-grey pixels cross over to white, so the grass is cleaner."

04Code walkthrough

import cv2
import numpy as np

cv2 is OpenCV (installed as opencv-python). It reads, writes, displays and processes images. numpy handles the image matrix: every OpenCV image is a NumPy array, so NumPy maths works directly on it.

img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(...)

Loads the file and converts it to a single-channel 8-bit image during loading. imread does not raise an error for a wrong path. It silently returns None, and the program then crashes later with a confusing message. The if check catches this early.

cv2.imread(filename, flags) → ndarray or None

filename: path to the image (jpg, png, bmp, tif…).

flags: how to load it. cv2.IMREAD_COLOR = 1 (default, 3-channel BGR, drops alpha); cv2.IMREAD_GRAYSCALE = 0 (1-channel); cv2.IMREAD_UNCHANGED = -1 (as stored, keeps the alpha channel or 16-bit depth).

Returns a NumPy array of shape (rows, cols) or (rows, cols, 3), dtype uint8.

print("Shape:", img.shape, "| dtype:", img.dtype,
      "| min:", img.min(), "| max:", img.max())

A sanity check. shape = (rows, cols) = (height, width). Width comes second. dtype should be uint8, and min/max show the intensity range actually used.

T_mean = np.mean(img)

Adds up all 262,144 pixel values and divides by the count, giving 129.06. It returns a float. NumPy accumulates the sum in a wide type internally, so the uint8 values do not overflow while being added. Same as img.mean().

binary_mean = np.where(img > T_mean, 255, 0).astype(np.uint8)

This is the thresholding rule in one line.

  • img > T_mean builds a boolean mask the same size as the image (True where the pixel is brighter than T).
  • np.where(mask, 255, 0) puts 255 where True and 0 where False.
  • .astype(np.uint8): np.where returns int64, and OpenCV needs 8-bit to display and save correctly.
np.where(condition, x, y) → ndarray

Element-wise "if-else" over the whole array: picks x where the condition is True and y where it is False. Equivalent alternative: (img > T).astype(np.uint8) * 255.

T_user = int(input("Enter threshold value (0-255): "))
if not 0 <= T_user <= 255:
    raise ValueError(...)

input() always returns a string, so int() converts it. The range check matters because a threshold outside 0–255 makes no sense for 8-bit images (T ≥ 255 → all black; T < 0 → all white).

ret, binary_user = cv2.threshold(img, T_user, 255,
                                 cv2.THRESH_BINARY)

OpenCV's built-in thresholding. It returns two values: the threshold actually used (ret, a float) and the output image. ret matters with Otsu, where OpenCV picks the threshold itself.

cv2.threshold(src, thresh, maxval, type) → (retval, dst)

src: input image, normally single-channel 8-bit (a colour image is thresholded channel by channel; see Part 5).

thresh: the threshold T (any number; float is fine). Ignored with THRESH_OTSU/THRESH_TRIANGLE.

maxval: value given to pixels that pass. Usually 255; use 1 if you want a 0/1 mask for maths.

type: rule to apply (THRESH_BINARY, _INV, TRUNC, TOZERO…; see table 1.8). Comparison is strictly src > thresh.

np.count_nonzero(b) / b.size

Counts white (non-zero) pixels and divides by the total pixel count (size = rows × cols). This is a quick way to compare two thresholds numerically.

cv2.imshow("Grayscale input", img)
cv2.imwrite("a1_binary_mean.png", binary_mean)
cv2.waitKey(0)
cv2.destroyAllWindows()

imshow(window_name, image) opens a window. The name must be unique, or the window gets replaced. imwrite(filename, image) saves the image; the file extension decides the format, and it returns True on success. waitKey(0) waits forever for a key press, while waitKey(500) waits 500 ms. Without waitKey the window never draws. destroyAllWindows() closes them all.

Common mistakes
  • Forgetting the flag in imread: the image loads as 3-channel BGR, and thresholding then gives a coloured output (shown in Part 5).
  • Writing binary = cv2.threshold(...) with a single variable. You get a tuple, and imshow fails. Unpack both: ret, binary = ....
  • cv2.imshow crashes in Google Colab / Jupyter. Use from google.colab.patches import cv2_imshow or plt.imshow(img, cmap='gray') instead. Without cmap='gray', Matplotlib shows a grayscale image in false colour (viridis).
  • Saving a binary image as .jpg: JPEG compression adds grey values near edges, so the saved file is no longer strictly binary. Use .png.

05"What if" questions

What if the threshold is very low (50) or very high (200)?
T = 50: only very dark pixels stay black → mostly white
T = 50: only very dark pixels stay black → mostly white
T = 129 (mean)
T = 129 (mean)
T = 200: only very bright pixels survive → mostly black
T = 200: only very bright pixels survive → mostly black

A low T classifies almost everything as "bright", so only the darkest parts (coat, hair, tripod) stay black. A high T leaves only the brightest sky white. As T moves from 0 to 255 the image goes from all white to all black. The useful T lies in the histogram valley.

What if we use THRESH_BINARY_INV instead of THRESH_BINARY?
THRESH_BINARY, T = 100
THRESH_BINARY, T = 100
THRESH_BINARY_INV, T = 100: exact complement
THRESH_BINARY_INV, T = 100: exact complement

Black and white swap: pixels above T become 0 and the rest 255. This is the same as taking the complement of the binary image (Assignment 3). Use it when the object of interest is darker than the background, because many later operations (contours, morphology) expect the object to be white.

What if we pass a colour image instead of a grayscale one?
Colour input (BGR)
Colour input (BGR)
cv2.threshold(colour, 100, 255, BINARY)
cv2.threshold(colour, 100, 255, BINARY)

cv2.threshold does not complain. It thresholds each of the B, G, R channels separately. Each channel becomes 0 or 255, giving 2³ = 8 possible colours (black, red, yellow, white…), so the result is not binary. Also, np.mean would average all three channels together. Always convert to grayscale first (imread(..., 0) or cvtColor(..., COLOR_BGR2GRAY)).

What if the lighting is uneven (shadow on one side)?
Input: page.png, lit unevenly
Input: page.png, lit unevenly
Global, T = mean (171.5)
Global, T = mean (171.5)
Global, Otsu
Global, Otsu
Adaptive Gaussian, block 25, C = 10
Adaptive Gaussian, block 25, C = 10

The left of the page is in shadow, so its background is darker than the threshold and turns black, hiding the text. Any single global T (mean or Otsu) fails because the "background" grey level changes across the image (illumination i(x,y) is not constant). Adaptive thresholding compares each pixel with its own neighbourhood, so it recovers all the text.

What about the other types: TRUNC and TOZERO?
THRESH_TRUNC, T = 100: values above 100 clipped to 100
THRESH_TRUNC, T = 100: values above 100 clipped to 100
THRESH_TOZERO, T = 100: values ≤ 100 set to 0, rest kept
THRESH_TOZERO, T = 100: values ≤ 100 set to 0, rest kept

Neither is binary. TRUNC flattens the bright part (the image looks dull and grey because the maximum is now 100). TOZERO keeps bright detail and blacks out dark regions. Only BINARY and BINARY_INV answer this assignment.

What if we use >= instead of >?

Only pixels whose value is exactly equal to T change (they become white instead of black). With T = 129.06 (a float) no pixel can be exactly equal, so there is no difference. With an integer T = 100, the pixels with value exactly 100 flip. Note that OpenCV's THRESH_BINARY uses strict >.

What if we use the median instead of the mean as the threshold?

The median splits the pixels into two equal halves, so the result is always about 50% white, whatever the content (for cameraman the median is 152, so the grass would go mostly black). The mean is affected by extreme values: a few very bright pixels pull it up. Neither looks at the histogram valley; Otsu does.

What if we forget .astype(np.uint8) after np.where?

np.where(img > T, 255, 0) returns int64. cv2.imwrite may refuse or convert it unpredictably, and cv2.imshow treats non-uint8 images differently (for example, it scales float images by 255, so a 0–255 float image appears almost entirely white). Always convert back to uint8.

What if maxval is 1 instead of 255?

The output holds 0 and 1. That is still binary and handy for maths (counting, masking), but on screen it looks completely black, because 1 out of 255 is nearly black. Multiply by 255 before displaying.

What if the image path is wrong?

cv2.imread returns None without raising an error. The next line that uses it fails with AttributeError: 'NoneType' object has no attribute 'shape' (or an assertion error inside cv2.threshold). That is why the program checks if img is None.

What if we smooth (blur) the image before thresholding?

Blurring averages each pixel with its neighbours, so isolated noisy pixels near T are pulled towards their region's value. The speckle in areas like the grass reduces and boundaries become smoother. That is why "Gaussian blur → Otsu" is a common pipeline. (Filtering is covered in later assignments.)

06Viva / evaluation angle

30-second explanation of the whole program

"I read the image in grayscale, so each pixel is a value from 0 to 255. For Case 1 I compute the mean of all pixels and use it as the threshold: pixels above it become 255 and the rest 0, using np.where. For Case 2 I take the threshold from the user and apply OpenCV's cv2.threshold with THRESH_BINARY. The output has only two values, so it is a binary image. Finally I display and save both results."

What is a binary image? How is it stored in OpenCV?

An image with only two values, object and background (1 bit per pixel in theory). OpenCV stores it as uint8 with values 0 and 255 so it can be displayed directly.

What is thresholding? Is it a point or neighbourhood operation?

Comparing each pixel with a value T and mapping it to 0 or 255. It is a point operation: the output at (x, y) depends only on the input at (x, y). Adaptive thresholding is the exception, because it uses a neighbourhood to compute T.

What does cv2.threshold return?

A tuple (retval, dst): the threshold used and the output image.

Why use the mean as the threshold? When does it fail?

It is automatic and represents average brightness. It fails when one region is much larger than the other (the mean shifts towards it), when the histogram is not bimodal, or when lighting is uneven.

What is a histogram and how does it help choose T?

A count of pixels at each intensity. For a bimodal histogram the best T lies in the valley between the two peaks.

What is Otsu's method?

An automatic global threshold that tests all T values and picks the one that maximises between-class variance (it separates the two classes best). Use the cv2.THRESH_OTSU flag. For cameraman it gives 102.

Global vs adaptive thresholding?

Global uses one T for the whole image. Adaptive computes T per pixel from a local window (mean or Gaussian − C) and handles uneven illumination.

What does flag 0 in cv2.imread(path, 0) mean?

IMREAD_GRAYSCALE: load as a single channel. 1 = colour (default), −1 = unchanged (keeps alpha).

Why cv2.waitKey(0)?

It keeps the window open until a key is pressed, and it processes GUI events so the window is actually drawn.

What is the difference between THRESH_BINARY and THRESH_BINARY_INV?

BINARY: > T → 255 else 0. BINARY_INV: > T → 0 else 255. They are complements of each other.

What is the mean threshold you got and what percentage is white?

For cameraman.png: T = 129.06, 63.7% white. With T = 100: 68.1% white. Know your own numbers if you use a different image.

What are sampling and quantization?

Sampling digitises coordinates (number of pixels, which sets spatial resolution). Quantization digitises intensity (number of grey levels, L = 2k). Thresholding is extreme quantization down to 2 levels.

How much memory does a 512×512 8-bit image need? A binary one?

512 × 512 × 8 bits = 256 KB. Binary at 1 bit/pixel = 32 KB (in practice OpenCV still uses 1 byte per pixel).

Where is binary conversion used?

Document scanning / OCR, object counting, masks for segmentation, morphological operations, fingerprint and barcode processing.

Assignment 2 · Colour models

Convert an RGB (colour) image to grayscale

Case 1: take the mean (average) of the three planes.

Case 2: input the weightage of R, G, B from the user. Each weight is between 0 and 1 and the three sum to 1 (e.g. 0.7, 0.2, 0.1).

01Concept explanation

1.1 How we see colour (image perception)

Visible light spans roughly 400 nm (violet) to 700 nm (red). The retina has three kinds of cone cells, most sensitive to long (red), medium (green) and short (blue) wavelengths. Gonzalez & Woods state that about 65% of cones respond mainly to red, 33% to green and only about 2% to blue. The eye's overall brightness sensitivity peaks in the green–yellow region (around 555 nm).

Consequence for this assignment: a pure green and a pure blue of the same numeric value do not look equally bright to us. Green looks much brighter and blue much darker. A "fair" grayscale conversion should therefore weight the channels unequally. That is the whole point of Case 2.

1.2 What a colour image is in memory

A colour image is three grayscale images (planes) stacked together, one each for red, green and blue. Each plane is 8-bit, so a pixel needs 24 bits and can show 224 ≈ 16.7 million colours.

The #1 OpenCV trap: BGR, not RGB

cv2.imread stores the channels in B, G, R order. So img[:,:,0] is blue, img[:,:,2] is red, and cv2.split(img) returns B, G, R. If you write R, G, B = cv2.split(img), your "R" weight is actually applied to blue. Matplotlib expects RGB, so a BGR image shown with plt.imshow has red and blue swapped (the coffee turns blue).

1.3 Colour models

A colour model is a coordinate system for describing colours. The syllabus lists colour models under Digital Image Fundamentals.

ModelComponentsIdeaUsed forOpenCV
RGBRed, Green, BlueAdditive: light is added; (0,0,0) = black, (255,255,255) = white. Colours are points in a cube.Screens, camerasdefault (as BGR)
CMY / CMYKCyan, Magenta, Yellow (+ blacK)Subtractive: inks absorb light. C = 1 − R, M = 1 − G, Y = 1 − B (normalised).Printingno direct flag; compute as 255 − channel
HSI / HSVHue, Saturation, Intensity/ValueSeparates colour (H, S) from brightness (I or V). Close to how humans describe colour.Colour-based segmentation, enhancementCOLOR_BGR2HSV (H is 0–179 in 8-bit)
YCbCrLuma Y, blue-diff Cb, red-diff CrY is the weighted grayscale; Cb and Cr carry the colour.JPEG compression, videoCOLOR_BGR2YCrCb

Grayscale conversion means keeping only the brightness part and discarding hue and saturation. Case 1 gives HSI's I; the standard weighted formula gives YCbCr's Y.

1.4 Case 1: simple average

Formula · Average method Gray = (R + G + B) / 3 (= the I of the HSI model)

Each channel counts equally. It is easy, but it ignores how the eye works. Pure red (255,0,0), pure green (0,255,0) and pure blue (0,0,255) all become 85, the same grey, even though green looks far brighter than blue. Images often come out slightly dull and flat.

1.5 Case 2: weighted average (luminosity method)

Formula · Weighted method Gray = w_R·R + w_G·G + w_B·B with 0 ≤ w_i ≤ 1 and w_R + w_G + w_B = 1 Standard (ITU-R BT.601, used by cv2.cvtColor): Y = 0.299 R + 0.587 G + 0.114 B HDTV (BT.709): Y = 0.2126 R + 0.7152 G + 0.0722 B

Why must the weights sum to 1? So that the output stays in 0–255 and white stays white: (255, 255, 255) → 255·(wR+wG+wB) = 255. If the sum is greater than 1, bright pixels exceed 255 and must be clipped, which washes the image out. If it is less than 1, the whole image gets darker. A weighted average with weights summing to 1 is a convex combination, so the result always lies between the smallest and largest channel value.

Why is green weighted most in the standard formula? Because the eye's brightness sensitivity peaks at green. Blue gets the least weight because it contributes least to perceived brightness.

The user-supplied weights in Case 2 let you choose which colour should look bright. The example 0.7, 0.2, 0.1 makes reddish regions bright, and 0.1, 0.2, 0.7 makes bluish regions bright. This is like putting a coloured filter in front of a black-and-white camera.

1.6 Step by step

  1. Read the colour image (BGR, shape rows × cols × 3).
  2. Split it into B, G, R planes and convert them to float, so sums like 200 + 200 + 200 do not overflow the uint8 limit of 255.
  3. Case 1: compute (R + G + B)/3 for every pixel.
  4. Case 2: read three weights, check each is in [0, 1] and they sum to 1, then compute wRR + wGG + wBB.
  5. Round, clip to 0–255, convert back to uint8, then display and save.

1.7 Comparing grayscale methods

Average (Case 1)User weights (Case 2)cv2.cvtColor BGR2GRAY
Formula(R+G+B)/3wRR+wGG+wBB0.299R+0.587G+0.114B
Matches human perception?No: all channels equalOnly if you choose perceptual weightsYes (luminance)
Red, green, blue patches85, 85, 85 (identical)Depends on weights76, 150, 29 (distinct)
SpeedFastFastFastest (optimised C++)
Use whenQuick and simpleYou want one colour emphasisedDefault choice in practice
Syllabus · Pseudo-colour and full-colour image processing

Pseudo-colour (false colour) goes the other way: it assigns colours to grey levels so small intensity differences become visible to the eye, which tells colours apart far better than greys. Methods:

  • Intensity slicing: cut the grey range into bands and give each band a colour (e.g. 0–63 blue, 64–127 green…).
  • Grey-level to colour transformations: three separate functions map the grey level to R, G and B. A colormap such as JET does exactly this: cv2.applyColorMap(gray, cv2.COLORMAP_JET).

Used in thermal images, X-ray baggage scanners, weather radar and medical imaging.

Full-colour processing works on true colour images in two ways: (1) process each channel separately and recombine (per-component), or (2) treat each pixel as a 3-D vector (vector-based). Per-channel processing works for operations like the complement (Assignment 3), but it can distort hues for others, such as histogram-equalising R, G and B separately. In that case convert to HSV/HSI and process only V/I.

Note that grayscale → colour is not a real inverse. cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) just copies the grey value into all three channels, so the image looks the same. The colour information was lost when we converted to gray.

02Solution

a2_solution.py
# Assignment 2: Convert an RGB (colour) image to grayscale
#   Case 1: simple mean (average) of the three planes
#   Case 2: weighted sum, weights for R, G, B entered by the user (sum = 1)
import cv2
import numpy as np

IMG_PATH = "coffee.png"

# 1. Read in colour. OpenCV stores channels in B, G, R order (not R, G, B!)
img = cv2.imread(IMG_PATH, cv2.IMREAD_COLOR)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")
print("Shape:", img.shape)          # (rows, cols, 3)

# 2. Separate the planes and convert to float so sums cannot overflow 255
B, G, R = cv2.split(img.astype(np.float32))

# ---------------- Case 1: average of the three planes ----------------
gray_avg = (R + G + B) / 3.0
gray_avg = np.round(gray_avg).astype(np.uint8)   # back to 0-255 integers

# ---------------- Case 2: user-defined weights ----------------
wr = float(input("Weight for R (0-1): "))
wg = float(input("Weight for G (0-1): "))
wb = float(input("Weight for B (0-1): "))

# Validate: each weight in [0, 1] and the three add up to 1
if not all(0 <= w <= 1 for w in (wr, wg, wb)):
    raise ValueError("Each weight must lie between 0 and 1")
if abs((wr + wg + wb) - 1.0) > 1e-6:          # tolerance for float rounding
    raise ValueError(f"Weights must sum to 1 (got {wr + wg + wb})")

gray_w = wr * R + wg * G + wb * B
gray_w = np.clip(np.round(gray_w), 0, 255).astype(np.uint8)

# Reference: OpenCV's built-in conversion (0.299 R + 0.587 G + 0.114 B)
gray_cv = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# ---------------- Display and save ----------------
cv2.imshow("Colour input", img)
cv2.imshow("Case 1 - average", gray_avg)
cv2.imshow("Case 2 - weighted", gray_w)
cv2.imshow("OpenCV cvtColor", gray_cv)
cv2.imwrite("a2_gray_avg.png", gray_avg)
cv2.imwrite("a2_gray_weighted.png", gray_w)
cv2.imwrite("a2_gray_cvtcolor.png", gray_cv)
cv2.waitKey(0)
cv2.destroyAllWindows()

Console output (user typed 0.7, 0.2, 0.1):

Shape: (400, 600, 3)
Weight for R (0-1): 0.7
Weight for G (0-1): 0.2
Weight for B (0-1): 0.1
Why the tolerance 1e-6 in the sum check

In Python, 0.7 + 0.2 + 0.1 evaluates to 0.9999999999999999, not 1.0, because decimal fractions are not exact in binary floating point. Checking == 1 would wrongly reject the assignment's own example. Compare with a small tolerance, or use math.isclose(total, 1).

Using indexing instead of cv2.split (equivalent)

img_f = img.astype(np.float32)
B = img_f[:, :, 0]      # channel 0 = Blue  (OpenCV order)
G = img_f[:, :, 1]      # channel 1 = Green
R = img_f[:, :, 2]      # channel 2 = Red
gray_avg = np.mean(img_f, axis=2).round().astype(np.uint8)   # average along the channel axis

03Output images

Input: coffee.png, 600×400, 3 channels
Input: coffee.png, 600×400, 3 channels
Case 1: average (R+G+B)/3 · mean brightness 98.6
Case 1: average (R+G+B)/3 · mean brightness 98.6
Case 2: weights R 0.7, G 0.2, B 0.1 · mean brightness 133.3
Case 2: weights R 0.7, G 0.2, B 0.1 · mean brightness 133.3
Reference: cv2.cvtColor BGR2GRAY · mean brightness 103.7
Reference: cv2.cvtColor BGR2GRAY · mean brightness 103.7

What changed: each output has one channel instead of three. Hue and saturation are gone and only brightness remains.

Why the three greys differ: this is a warm, reddish-brown photo. The red channel is the brightest (average 158.6), green is moderate (85.8) and blue is dark (51.5). Case 2 puts 70% weight on red, so the coffee and the wooden table come out brightest there. The average treats the weak blue channel equally, which pulls everything down, so Case 1 is the darkest and flattest. The standard formula sits between them.

Worked example, one pixel of the coffee (B, G, R) = (62, 151, 232):

Case 1: (232 + 151 + 62) / 3 = 148.3 → 148 Case 2: 0.7·232 + 0.2·151 + 0.1·62 = 198.8 → 199 cvtColor: 0.299·232 + 0.587·151 + 0.114·62 = 165.1 → 165

These are exactly the values in the saved output images at that pixel. Doing one pixel by hand like this is a strong way to prove your code is correct in the viva.

The three planes on their own

R plane (channel 2): bright almost everywhere: warm image
R plane (channel 2): bright almost everywhere: warm image
G plane (channel 1): medium
G plane (channel 1): medium
B plane (channel 0): dark: little blue in the scene
B plane (channel 0): dark: little blue in the scene

Each plane is a grayscale image in its own right: bright where that colour is strong. The white cup is bright in all three (white = R, G and B all high). The orange coffee is bright in R, medium in G and dark in B. Every grayscale method is just a different blend of these three pictures.

Say this when you show the output

"The image has three planes. In Case 1 I add them and divide by 3. In Case 2 the user's weights decide how much each colour contributes. With 0.7 on red, reddish areas like the coffee and the table become brighter. OpenCV's built-in conversion uses 0.299, 0.587 and 0.114 because our eyes are most sensitive to green."

04Code walkthrough

img = cv2.imread(IMG_PATH, cv2.IMREAD_COLOR)
print("Shape:", img.shape)      # (400, 600, 3)

Loads a 3-channel image in BGR order. Shape is (rows, cols, channels) = (height, width, 3). IMREAD_COLOR is the default, so the flag is optional, but writing it makes the intent clear.

B, G, R = cv2.split(img.astype(np.float32))

Two things happen here.

  • .astype(np.float32) converts 0–255 integers to floats, so R + G + B can reach 765 without wrapping around (uint8 arithmetic wraps: 200 + 100 = 44).
  • cv2.split separates the 3-D array into three 2-D arrays, in B, G, R order.
cv2.split(m) → (ch0, ch1, ch2) · cv2.merge([ch0, ch1, ch2]) → image

split breaks a multi-channel image into single-channel arrays (B, G, R for a normal imread). merge does the reverse. Indexing img[:,:,k] is a faster alternative to split because it gives a view and makes no copy.

gray_avg = (R + G + B) / 3.0
gray_avg = np.round(gray_avg).astype(np.uint8)

NumPy adds the three arrays element-wise, meaning pixel by pixel, all at once, and divides by 3. np.round rounds to the nearest integer (148.3 → 148). astype(np.uint8) converts back to 8-bit so OpenCV can display and save it. Without rounding, astype just chops off the decimals, so 148.9 would become 148.

wr = float(input("Weight for R (0-1): "))
...
if not all(0 <= w <= 1 for w in (wr, wg, wb)):
    raise ValueError(...)
if abs((wr + wg + wb) - 1.0) > 1e-6:
    raise ValueError(...)

Reads three weights as floats and enforces the two conditions in the assignment: each weight is between 0 and 1, and they sum to 1. all(...) is True only if every weight passes. The sum is compared with a tolerance because of floating-point error (0.7+0.2+0.1 = 0.9999999999999999).

gray_w = wr * R + wg * G + wb * B
gray_w = np.clip(np.round(gray_w), 0, 255).astype(np.uint8)

Multiplies each plane by its weight (a scalar times a matrix scales every pixel) and adds them. np.clip(x, 0, 255) forces values into the valid range. With valid weights it never triggers, but it protects against overflow if the validation is removed.

gray_cv = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

OpenCV's built-in conversion, using 0.299R + 0.587G + 0.114B. Included as a reference to compare against. In the viva you can say it is the standard weighted method from Case 2 with fixed perceptual weights.

cv2.cvtColor(src, code) → dst

src: input image. code: which conversion. Common codes: COLOR_BGR2GRAY, COLOR_BGR2RGB (for Matplotlib), COLOR_GRAY2BGR (copy gray into 3 channels), COLOR_BGR2HSV, COLOR_BGR2YCrCb, COLOR_BGR2LAB.

The input must have the channel count the code expects. BGR2GRAY on a 1-channel image raises an error (Invalid number of channels … 'scn' is 1).

Common mistakes
  • Adding uint8 planes directly: (R + G + B) / 3 on uint8 overflows and wraps around (see Part 5 for the image). Convert to float or int first.
  • Unpacking as R, G, B = cv2.split(img): the weights land on the wrong channels.
  • Checking sum == 1 with floats: rejects 0.7 + 0.2 + 0.1.
  • Showing with Matplotlib without converting: plt.imshow(img) swaps red and blue; plt.imshow(gray) without cmap='gray' shows false colour.
  • Forgetting astype(np.uint8): cv2.imshow on a float image expects values 0–1, so a 0–255 float image appears almost entirely white.

05"What if" questions

What if we add the uint8 planes without converting to float?
Correct: float arithmetic
Correct: float arithmetic
Wrong: (R + G + B) / 3 on uint8 planes
Wrong: (R + G + B) / 3 on uint8 planes

uint8 can only hold 0–255, so sums wrap around modulo 256. For the coffee pixel 232 + 151 + 62 = 445 → 445 − 256 = 189 → 189/3 = 63 instead of 148. Bright areas (like the white cup, whose sum is well over 255) turn dark and pick up ugly contours where the wrap happens. NumPy does this silently, with no error.

What if the weights are reversed: R 0.1, G 0.2, B 0.7? (Also what happens if you forget OpenCV's BGR order.)
R 0.7, G 0.2, B 0.1 (mean 133.3)
R 0.7, G 0.2, B 0.1 (mean 133.3)
R 0.1, G 0.2, B 0.7 (mean 69.1)
R 0.1, G 0.2, B 0.7 (mean 69.1)

Now blue dominates. This image has very little blue, so it becomes dark: the orange coffee goes almost black, while the white cup (high in all channels) stays bright. This is exactly the output you get if you unpack R, G, B = cv2.split(img) by mistake: the "0.7 for R" is applied to the blue plane. If your Case 2 output is unexpectedly dark for a warm image, check the channel order.

Why can't the simple average tell red, green and blue apart?
Test chart: red, green, blue, yellow
Test chart: red, green, blue, yellow
Average: 85, 85, 85, 170
Average: 85, 85, 85, 170
cvtColor: 76, 150, 29, 226
cvtColor: 76, 150, 29, 226

Each pure colour has one channel at 255 and two at 0, so the average is 255/3 = 85 for all three, which makes them indistinguishable. The luminance formula gives green 150 (bright), red 76 and blue 29 (dark), which matches how bright they actually look. Any information that differs only in hue is lost by the average method.

What if the weights don't add up to 1, e.g. 0.7, 0.7, 0.7?

The sum is 2.1, so every pixel is scaled up about 2.1×. Anything above 255/2.1 ≈ 121 is clipped to 255, so most of the image goes flat white and detail is lost. If the sum is below 1 (e.g. 0.2, 0.2, 0.2), the image darkens to 60% brightness. That is why the program rejects such inputs.

What if the input is already grayscale?

If read with imread(path) (default colour flag), OpenCV returns 3 identical channels, so every method gives back the same grey image (since R = G = B, any weights summing to 1 return that value). If read with flag 0, it has only one channel: cv2.split returns one array, so unpacking into B, G, R fails, and cvtColor(..., BGR2GRAY) raises "Invalid number of channels".

What if the PNG has an alpha (transparency) channel?

With the default IMREAD_COLOR flag the alpha is dropped, so nothing changes. With IMREAD_UNCHANGED the image has 4 channels (B, G, R, A), so B, G, R = cv2.split(img) raises too many values to unpack. Use COLOR_BGRA2GRAY or slice img[:,:,:3].

Can we convert the grayscale back to colour?

No. Grayscale conversion is many-to-one: many different colours map to the same grey (the red, green and blue patches all gave 85 above). cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) only copies the grey into three channels so the result can be combined with colour images, for example to draw a coloured border (Assignment 3). Adding colour back artificially is pseudo-colouring:

Grayscale
Grayscale
Pseudo-colour: cv2.applyColorMap(gray, COLORMAP_JET)
Pseudo-colour: cv2.applyColorMap(gray, COLORMAP_JET)

JET maps dark → blue, mid → green/yellow, bright → red. The colours show intensity, not the original colours: the white cup rim appears red because it is the brightest part.

What does the image look like in HSV, and which channel is a "grayscale"?
H (hue, 0–179): which colour
H (hue, 0–179): which colour
S (saturation): how pure / vivid
S (saturation): how pure / vivid
V (value) = max(R, G, B)
V (value) = max(R, G, B)

HSV separates colour from brightness. V is a third grayscale method: max(R, G, B). It makes every saturated colour look bright. The cup and the coffee are both bright in V, but the coffee is far more saturated (bright in S). This separation is why HSV is preferred for colour-based segmentation.

What if we read the image with Matplotlib (plt.imread) instead?

Matplotlib returns RGB order, and for PNG files it returns float values 0–1 instead of 0–255. Your channel unpacking becomes R, G, B, and you must multiply by 255 (or skip the uint8 conversion) before using OpenCV functions.

06Viva / evaluation angle

30-second explanation of the whole program

"I read the colour image, which OpenCV stores as B, G, R. I split it into three planes and convert them to float to avoid overflow. Case 1 averages the three planes. Case 2 reads three weights from the user, checks each is between 0 and 1 and that they sum to 1, and computes the weighted sum. I round, convert back to uint8 and display. I also compare with cvtColor, which uses 0.299, 0.587 and 0.114, because the human eye is most sensitive to green."

Why does OpenCV use BGR?

For historical reasons: early camera makers and Windows bitmap formats stored pixels as BGR, and OpenCV kept that convention. Channel 0 is blue and channel 2 is red.

Why is the weighted method better than the average?

The eye is not equally sensitive to the three colours (most to green, least to blue). Weighted conversion matches perceived brightness. The average makes red, green and blue look identical (all 85).

What are the standard weights and where do they come from?

0.299, 0.587, 0.114 from ITU-R BT.601 (the Y of YCbCr). HDTV's BT.709 uses 0.2126, 0.7152, 0.0722.

Why must the weights sum to 1?

To keep the output in 0–255 and preserve white → 255. A sum above 1 causes clipping/saturation; below 1 darkens the image.

Why convert to float before adding?

uint8 wraps around above 255 (modulo 256), giving wrong, dark values. Float holds the true sum.

What does cv2.split return for a colour image?

Three 2-D arrays in B, G, R order, each the same height and width as the image.

What is the shape of the input and output?

Input (400, 600, 3); output (400, 600). The channel dimension disappears.

How many colours can a 24-bit image show?

224 = 16,777,216.

Name some colour models and their uses.

RGB (displays), CMY/CMYK (printing), HSI/HSV (segmentation and enhancement, since it separates colour from brightness), YCbCr (JPEG, video).

What is pseudo-colour processing?

Assigning colours to grey levels (intensity slicing or colormaps) so the eye can spot small intensity differences. Used in thermal, medical and satellite images.

Is RGB → gray reversible?

No. It is many-to-one, so hue and saturation are lost.

Verify your output for one pixel.

Coffee pixel (B,G,R) = (62,151,232): average 148, weighted (0.7,0.2,0.1) 199, cvtColor 165. Print img[150,300] and gray[150,300] to show this live.

Assignment 3 · Borders and point processing

Pad an image with a border · Image complement

Q1: draw a border around the input image (pad it). Take the border width (in pixels) and the border colour from the user. Do it for both a binary and a grayscale image.

Q2: find the image complement. Do it for both a binary and a grayscale image.

01Concept explanation

Q1 · 1.1 What padding is

Padding adds extra rows and columns of pixels around the edges of an image. If the original image is M × N and we add a border of width w on all four sides, the output size becomes:

Formula · Size after padding new size = (M + top + bottom) × (N + left + right) uniform border w: (M + 2w) × (N + 2w) e.g. 512×512, w = 20 → 552×552

The original pixels are copied unchanged into the centre. Only the new outer pixels need values, and the border type decides what those values are.

1.2 Why padding matters (not just decoration)

  • Neighbourhood processing / filtering: a 3×3 filter centred on a corner pixel needs neighbours that do not exist. Padding provides them. For a k × k kernel you pad by (k − 1)/2 on each side, so a 3×3 kernel needs 1 pixel and a 5×5 needs 2. Every smoothing and sharpening filter in later assignments relies on this.
  • DFT / frequency-domain filtering: the DFT treats an image as if it repeats periodically. Zero-padding to at least P ≥ 2M − 1, Q ≥ 2N − 1 prevents wrap-around error when filtering in the frequency domain.
  • Display / framing: separating images in a collage, or making room for labels. This is the literal "draw a border" of this assignment.
  • Size fitting: padding to a required size, such as a square input for a CNN or a multiple of 8 for JPEG's 8×8 blocks.

1.3 Border types

OpenCV's documentation describes each type with a pattern. abcdefgh is one row of the image and | marks its edges:

Border typePatternWhat the new pixels areTypical use
cv2.BORDER_CONSTANTiiiiii|abcdefgh|iiiiiiA fixed value i (the value argument)This assignment; zero-padding for the DFT
cv2.BORDER_REPLICATEaaaaaa|abcdefgh|hhhhhhThe edge pixel repeatedFilters that should not darken edges
cv2.BORDER_REFLECTfedcba|abcdefgh|hgfedcMirror image, edge pixel repeatedSmooth continuation
cv2.BORDER_REFLECT_101gfedcb|abcdefgh|gfedcbMirror without repeating the edge pixelDefault in OpenCV filters (BORDER_DEFAULT)
cv2.BORDER_WRAPcdefgh|abcdefgh|abcdefPixels from the opposite side (tiling)Mimics the periodic assumption of the DFT

1.4 What "border colour" means for each image type

Image typeChannelsValid border valueIn code
Binary1Only 0 (black) or 255 (white). Anything else breaks the binary property.value=0 or value=255
Grayscale1One intensity, 0–255value=128
Colour3A (B, G, R) triplevalue=(0, 0, 255) = red

To put a coloured border on a grayscale image, first convert it to 3 channels with cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR). A single-channel image has nowhere to store colour.

1.5 Step by step (Q1)

  1. Read the grayscale image and threshold it to get a binary version.
  2. Read the border width w and the border value/colour from the user. Validate them (w ≥ 0, value 0–255).
  3. Create a canvas of size (M + 2w) × (N + 2w) filled with the border value.
  4. Copy the original image into the centre region [w : w+M, w : w+N].
  5. cv2.copyMakeBorder performs steps 3 and 4 in one call.
Syllabus · Basic relationships between pixels (why borders matter for neighbourhoods)

Padding exists because operations look at a pixel's neighbours. For a pixel p at (x, y):

  • 4-neighbours N4(p): (x±1, y) and (x, y±1), the pixels above, below, left and right.
  • Diagonal neighbours ND(p): (x±1, y±1).
  • 8-neighbours N8(p) = N4 ∪ ND. A border pixel has some of these outside the image, and padding supplies them.
  • Adjacency: two pixels are 4-, 8- or m-adjacent (mixed) if they are neighbours of that kind and their values are both in a set V (for example V = {255} in a binary image). m-adjacency avoids the double paths that 8-adjacency creates.
  • Path, connectivity, region, boundary: a path is a chain of adjacent pixels; pixels are connected if a path joins them; a connected set is a region; its boundary is the set of region pixels that have a neighbour outside it.

Distance measures between p = (x, y) and q = (s, t):

Euclidean D_e = √((x − s)² + (y − t)²) City-block D_4 = |x − s| + |y − t| (D_4 = 1 ⇔ 4-neighbours) Chessboard D_8 = max(|x − s|, |y − t|) (D_8 = 1 ⇔ 8-neighbours)

Q2 · 1.6 Image complement (negative)

The complement flips every intensity to the opposite end of the scale: black ↔ white, dark grey ↔ light grey. It is the photographic negative.

Formula · Image negative s = (L − 1) − r L = number of grey levels 8-bit (L = 256): s = 255 − r e.g. 212 → 43, 0 → 255, 255 → 0 binary (0/1): s = 1 − r = NOT r (0/255 storage: s = 255 − r) normalised [0, 1]: s = 1 − r colour: apply to each channel: (255 − B, 255 − G, 255 − R)
  • Grayscale: the transfer curve is a straight line sloping down. Dark regions become bright and vice versa, while the contrast (differences between pixels) is preserved: if two pixels differ by 30, their negatives still differ by 30.
  • Binary: object and background swap. In set terms this is the set complement Ac, which appears in morphology (e.g. A − B = A ∩ Bc).
  • Bit view: for an 8-bit value, 255 − r is the same as flipping all 8 bits, because 255 = 11111111₂. So cv2.bitwise_not gives the identical result. Example: 212 = 11010100₂ → 00101011₂ = 43.
  • Applying it twice gives back the original: 255 − (255 − r) = r. The negative is its own inverse.
  • Uses: bringing out white or grey detail inside large dark regions, as in mammograms (the classic Gonzalez example); viewing film negatives; inverting masks.
Syllabus · Point processing: the family the negative belongs to

The syllabus lists point processing under image enhancement. A point operation is s = T(r): each output pixel depends only on the input pixel at the same place, so it can be drawn as a transfer curve. The negative is the simplest example. The others:

TransformationFormulaEffect
Identitys = rNo change
Negative (this assignment)s = L − 1 − rReverses intensities
Logs = c · log(1 + r), c = 255 / log(256)Expands dark values, compresses bright ones. Used to display Fourier spectra.
Inverse logs = c · (er − 1) (scaled)Opposite of log
Power-law (gamma)s = c · rγ (r normalised to 0–1)γ < 1 brightens; γ > 1 darkens. Used for gamma correction of displays.
Contrast stretchingpiecewise linear through (r1, s1), (r2, s2)Spreads a narrow intensity range over 0–255
Thresholding (Assignment 1)stretching with r1 = r2 = T, s1 = 0, s2 = L−1The extreme case: binary output
Intensity-level slicinghighlight [A, B], keep or darken the restPicks out one range (e.g. water in satellite images)
Bit-plane slicingextract bit k of each pixelShows which bits carry the visual information; the basis of some compression and steganography

Point processing contrasts with neighbourhood processing (filters, which need the padding from Q1) and histogram processing (equalisation, matching).

1.7 Ways to compute the complement

ExpressionWorks on uint8?Notes
255 - img✓Direct formula; clearest in a viva
cv2.bitwise_not(img)✓Flips all bits; identical result for uint8; works on colour too
~img / np.invert(img)✓ (uint8 only)On int32 data ~200 = −201, which is wrong
np.logical_not(img > 0)binary onlyReturns True/False; multiply by 255 to display
256 - img✗NumPy 2 raises OverflowError: Python integer 256 out of bounds for uint8; it is also mathematically off by one
-img✗uint8 wraps: −200 → 56. That gives 256 − r, not 255 − r, and 0 stays 0.

02Solution

Q1 · Border / padding

a3q1_solution.py
# Assignment 3, Q1: Draw a border around an image (pad the image)
#   Border width and colour come from the user. Done for grayscale AND binary.
import cv2
import numpy as np

IMG_PATH = "cameraman.png"

gray = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if gray is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")

# Make a binary version (threshold at 127) so we can pad both kinds
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# ---------------- User input ----------------
w = int(input("Border width in pixels: "))
val = int(input("Border intensity for grayscale (0 = black ... 255 = white): "))
if w < 0 or not 0 <= val <= 255:
    raise ValueError("Width must be >= 0 and intensity must be 0-255")

# ---------------- Method 1: OpenCV copyMakeBorder ----------------
# Arguments: src, top, bottom, left, right, borderType, value
gray_border = cv2.copyMakeBorder(gray, w, w, w, w,
                                 cv2.BORDER_CONSTANT, value=val)

# A binary image may only hold 0 or 255, so snap the colour to the nearer one
bin_val = 255 if val >= 128 else 0
binary_border = cv2.copyMakeBorder(binary, w, w, w, w,
                                   cv2.BORDER_CONSTANT, value=bin_val)

# ---------------- Method 2: manual padding with NumPy ----------------
h, wd = gray.shape
padded = np.full((h + 2 * w, wd + 2 * w), val, dtype=np.uint8)  # canvas of border colour
padded[w:w + h, w:w + wd] = gray                                 # paste image in the middle
print("Manual == OpenCV:", np.array_equal(padded, gray_border))

# ---------------- Optional: a coloured border on a grayscale image ----------------
# A 1-channel image cannot hold a colour, so convert it to 3 channels first.
r, g, b = map(int, input("Colour border as R G B (e.g. 255 0 0): ").split())
gray_3ch = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
colour_border = cv2.copyMakeBorder(gray_3ch, w, w, w, w,
                                   cv2.BORDER_CONSTANT, value=(b, g, r))  # BGR order!

print("Original:", gray.shape, "-> padded:", gray_border.shape)

cv2.imshow("Grayscale + border", gray_border)
cv2.imshow("Binary + border", binary_border)
cv2.imshow("Colour border", colour_border)
cv2.imwrite("a3_gray_border.png", gray_border)
cv2.imwrite("a3_binary_border.png", binary_border)
cv2.imwrite("a3_colour_border.png", colour_border)
cv2.waitKey(0)
cv2.destroyAllWindows()

Console output (inputs: width 20, intensity 255, colour 255 0 0):

Border width in pixels: 20
Border intensity for grayscale (0 = black ... 255 = white): 255
Manual == OpenCV: True
Colour border as R G B (e.g. 255 0 0): 255 0 0
Original: (512, 512) -> padded: (552, 552)

Q2 · Complement

a3q2_solution.py
# Assignment 3, Q2: Image complement (negative) for grayscale AND binary images
#   s = (L - 1) - r     where L = number of grey levels (256 for 8-bit)
import cv2
import numpy as np

IMG_PATH = "cameraman.png"

gray = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if gray is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

L = 2 ** 8                       # 8-bit image -> 256 levels (0..255)

# ---------------- Grayscale complement ----------------
neg_gray = (L - 1) - gray        # 255 - r, applied to every pixel at once
neg_gray_cv = cv2.bitwise_not(gray)          # built-in: flips every bit
print("255 - r == bitwise_not:", np.array_equal(neg_gray, neg_gray_cv))

# ---------------- Binary complement ----------------
neg_binary = 255 - binary        # 0 -> 255, 255 -> 0 (black <-> white)
# Logical view: treat as True/False and apply NOT
neg_binary_logical = np.logical_not(binary > 0).astype(np.uint8) * 255
print("Arithmetic == logical:", np.array_equal(neg_binary, neg_binary_logical))

# Sanity check on one pixel
print("Pixel (100,100):", gray[100, 100], "->", neg_gray[100, 100])

cv2.imshow("Grayscale", gray)
cv2.imshow("Grayscale complement", neg_gray)
cv2.imshow("Binary", binary)
cv2.imshow("Binary complement", neg_binary)
cv2.imwrite("a3_neg_gray.png", neg_gray)
cv2.imwrite("a3_binary.png", binary)
cv2.imwrite("a3_neg_binary.png", neg_binary)
cv2.waitKey(0)
cv2.destroyAllWindows()

Console output:

255 - r == bitwise_not: True
Arithmetic == logical: True
Pixel (100,100): 212 -> 43

03Output images

Q1 · Border (w = 20)

Grayscale + white border (value 255) → 552×552
Grayscale + white border (value 255) → 552×552
Binary + white border (snapped to 255)
Binary + white border (snapped to 255)
Grayscale → BGR + red border (R G B = 255 0 0)
Grayscale → BGR + red border (R G B = 255 0 0)

What changed: the image grew from 512×512 to 552×552, with 20 new pixels on every side, all set to the chosen value. The original 512×512 pixels are untouched in the centre (the manual NumPy version produced a pixel-identical result: Manual == OpenCV: True).

Binary case: the binary image uses only 0 and 255, so the border must also be 0 or 255. The user typed 255, so the frame is white and the image stays strictly binary. Typing, say, 100 would be snapped to 0.

Colour case: the picture still looks grey because R = G = B inside, but it now has 3 channels, so a red border (B, G, R) = (0, 0, 255) is possible. The user types R G B, and the code reverses it for OpenCV.

Q2 · Complement

Grayscale input
Grayscale input
Complement 255 − r · pixel (100,100): 212 → 43
Complement 255 − r · pixel (100,100): 212 → 43
Binary input (T = 127) · 64.3% white
Binary input (T = 127) · 64.3% white
Binary complement · 35.7% white
Binary complement · 35.7% white

Grayscale: the bright sky (≈ 205) became dark (≈ 50) and the black coat became almost white. The mean brightness went from 129.1 to 125.9 (= 255 − 129.1), since the negative reflects the whole histogram around the middle. Detail is not lost, only reversed: the folds of the coat, invisible in the original because they are nearly black, are easier to see once they are light grey.

Binary: every 0 became 255 and every 255 became 0, so object and background swap. The white fraction flips from 64.3% to 35.7% (they add to 100%).

Say this when you show the output

"For the border, the output is 2w pixels larger in each dimension and the original is copied into the centre. For a binary image the border must be 0 or 255 to keep it binary. For the complement I subtract every pixel from 255, so dark becomes bright. For example, pixel (100,100) was 212 and became 43. Applying the complement twice gives back the original image."

04Code walkthrough

Q1 · Border

gray = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

Reads a grayscale image and makes a binary one from it (Assignment 1). The _ discards the returned threshold value, which we do not need here.

w = int(input("Border width in pixels: "))
val = int(input("Border intensity ... "))
if w < 0 or not 0 <= val <= 255:
    raise ValueError(...)

User inputs, converted from strings to integers. A negative width makes copyMakeBorder fail with an assertion error (top >= 0 && bottom >= 0 …), so we check first.

gray_border = cv2.copyMakeBorder(gray, w, w, w, w,
                    cv2.BORDER_CONSTANT, value=val)

The core line: adds w pixels on top, bottom, left and right, all filled with val.

cv2.copyMakeBorder(src, top, bottom, left, right, borderType, value=None) → dst

src: input image (any number of channels).

top, bottom, left, right: border thickness in pixels on each side. They can differ, e.g. (0, 60, 0, 0) pads only the bottom. Must be ≥ 0.

borderType: BORDER_CONSTANT, REPLICATE, REFLECT, REFLECT_101, WRAP (see table 1.3).

value: fill colour, used only with BORDER_CONSTANT. A number for grayscale (e.g. 0, 255) or a (B, G, R) tuple for colour (e.g. (0,0,255)). Omitted → 0 (black).

Returns a new image of size (rows + top + bottom, cols + left + right). The original is not modified.

bin_val = 255 if val >= 128 else 0
binary_border = cv2.copyMakeBorder(binary, w, w, w, w,
                    cv2.BORDER_CONSTANT, value=bin_val)

A Python conditional expression snaps any user value to the nearer of 0 or 255, so the padded binary image still has only two values.

h, wd = gray.shape
padded = np.full((h + 2*w, wd + 2*w), val, dtype=np.uint8)
padded[w:w + h, w:w + wd] = gray

The manual method, i.e. what copyMakeBorder does internally for a constant border.

  • np.full(shape, fill, dtype) creates a bigger canvas filled with the border value.
  • The slice [w : w+h, w : w+wd] selects the centre region (rows w to w+h−1, columns w to w+wd−1), and the original image is pasted into it.
  • np.array_equal confirms it matches OpenCV's output exactly.

np.pad(gray, w, mode='constant', constant_values=val) is a one-line NumPy alternative.

r, g, b = map(int, input(...).split())
gray_3ch = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
colour_border = cv2.copyMakeBorder(gray_3ch, w, w, w, w,
                    cv2.BORDER_CONSTANT, value=(b, g, r))

input().split() splits "255 0 0" into three strings, and map(int, …) converts each one. GRAY2BGR copies the single channel into three identical channels so a colour can be stored. The value is passed as (b, g, r) because OpenCV is BGR. Passing (r, g, b) would turn a red request into a blue border.

Q2 · Complement

L = 2 ** 8
neg_gray = (L - 1) - gray

Writes the textbook formula s = (L − 1) − r directly. NumPy broadcasts the scalar 255 against the whole array, so every pixel is subtracted at once with no loop. No overflow can happen, because 255 − r is always between 0 and 255 for uint8 r.

neg_gray_cv = cv2.bitwise_not(gray)

Built-in alternative: inverts every bit of every pixel. For 8-bit images this equals 255 − r (verified: True).

cv2.bitwise_not(src[, dst[, mask]]) → dst

src: any image (gray, binary or colour; each channel is inverted). mask (optional, 8-bit single-channel): only pixels where the mask is non-zero are inverted. Related functions: bitwise_and, bitwise_or, bitwise_xor, used later for masking.

neg_binary = 255 - binary
neg_binary_logical = np.logical_not(binary > 0).astype(np.uint8) * 255

The binary complement computed two ways. Arithmetic: 255 − r maps 0→255 and 255→0. Logical: binary > 0 gives True/False, logical_not flips it, and astype(uint8)*255 turns True/False back into 255/0. Both give the same image (True).

print("Pixel (100,100):", gray[100, 100], "->", neg_gray[100, 100])

Indexing is [row, col], i.e. [y, x]. Printing one pixel before and after (212 → 43) is the quickest way to show the formula working.

Common mistakes
  • Mixing up the argument order of copyMakeBorder: it is top, bottom, left, right, not top, left, bottom, right.
  • Passing value with a non-constant border type: it is silently ignored.
  • Giving a colour tuple to a 1-channel image: only the first number is used, so (255, 0, 0) on grayscale gives a border of value 255 (white), not red. Convert to BGR first.
  • Writing 256 - img or -img for the complement (see table 1.7).
  • Using ~img on a non-uint8 array, such as int32 after some arithmetic: you get negative numbers.

05"What if" questions

What if we use a different border type instead of CONSTANT?

Applied to a 200×200 crop with a 50-pixel border, so the effect is easy to see:

Original crop (200×200)
Original crop (200×200)
CONSTANT (value 0): plain black frame
CONSTANT (value 0): plain black frame
REPLICATE: edge pixels smeared outwards (streaks)
REPLICATE: edge pixels smeared outwards (streaks)
REFLECT: mirror image, edge pixel repeated
REFLECT: mirror image, edge pixel repeated
REFLECT_101: mirror, edge not repeated (OpenCV default)
REFLECT_101: mirror, edge not repeated (OpenCV default)
WRAP: opposite edge brought round (tiling)
WRAP: opposite edge brought round (tiling)

Only CONSTANT draws a "border" in the visual sense. The others invent plausible pixel values. That is what you want before filtering, because a black border would darken the edges of a blurred image. REFLECT and REFLECT_101 look almost the same; the difference is whether the outermost pixel is repeated (cba|abc vs dcb|abc).

What if the border is only on one side, or the sides differ?
copyMakeBorder(g, 0, 60, 0, 0, CONSTANT, value=255): bottom only → 572×512
copyMakeBorder(g, 0, 60, 0, 0, CONSTANT, value=255): bottom only → 572×512

Each side is independent. This is useful for adding a caption strip under an image. The new shape is (512 + 0 + 60) × (512 + 0 + 0).

What if the user enters border value 128 for the binary image?

If we did not snap it, the padded image would contain three values (0, 128, 255) and would no longer be binary. A later step that expects only 0/255 (such as counting white pixels or morphology) would treat the grey border inconsistently. That is why the code converts the value to the nearer of 0 or 255.

What if the width is 0, negative, or bigger than the image?

0: the image is returned unchanged in size. Negative: OpenCV raises Assertion failed: top >= 0 && bottom >= 0 …. Bigger than the image: works for CONSTANT and REPLICATE. For REFLECT/WRAP, OpenCV keeps reflecting or wrapping, so the pattern repeats.

What if we take the complement of a colour image?
Colour input
Colour input
255 − img: each channel inverted
255 − img: each channel inverted

Each of B, G and R is inverted separately (a per-component full-colour operation). Every colour becomes its complementary colour, the one opposite it on the colour wheel: orange coffee → blue, white cup → black, black saucer → white. This is how film negatives look, and it is also the RGB → CMY relation (C = 1 − R).

What if we write 256 - img or -img?

256 - img: NumPy 2.x raises OverflowError: Python integer 256 out of bounds for uint8. Older NumPy silently wrapped it. Mathematically it is also wrong (L − r instead of L − 1 − r). -img on uint8 wraps to 256 − r: 200 → 56 instead of 55, and 0 stays 0 instead of becoming 255.

What if we reorder the steps: complement first, then add the border?

The two orders differ. Border → complement: the border is complemented too, so a white border becomes black. Complement → border: the border keeps the colour the user asked for. If the border colour matters, add it last.

Similarly, complement → threshold versus threshold → complement: thresholding 255 − f at 255 − T marks pixels with f < T, while complementing threshold(f, T) marks f ≤ T. They match everywhere except pixels exactly equal to T.

What if we apply the complement twice?

We get the original back exactly: 255 − (255 − r) = r. The negative is its own inverse (an involution), and no information is lost. Contrast this with thresholding or grayscale conversion, which cannot be undone.

How do other point-processing curves compare with the negative?
Transfer curves
Transfer curves s = T(r)
Log: dark detail expanded (mean 208.7)
Log: dark detail expanded (mean 208.7)
Gamma 0.4: brightens (mean 181.7)
Gamma 0.4: brightens (mean 181.7)
Gamma 2.5: darkens (mean 73.1)
Gamma 2.5: darkens (mean 73.1)

The negative is the only one with a downward slope. Log and γ < 1 bend upward, which stretches dark values apart and squeezes bright ones together (the coat shows detail). γ > 1 does the opposite. All of them are one-line NumPy expressions on the float image, e.g. np.uint8(255 * (img/255) ** 0.4).

What if the image were 16-bit or float in [0, 1]?

Use the general formula s = (L − 1) − r: for 16-bit, L = 65536, so 65535 − r. For a normalised float image, 1.0 − r. Hard-coding 255 would be wrong in both cases. cv2.bitwise_not handles 16-bit correctly (flips 16 bits) but is not defined for floats.

06Viva / evaluation angle

30-second explanation of both programs

"For padding I read the border width and colour from the user and call cv2.copyMakeBorder with BORDER_CONSTANT. It adds w pixels on each side, so the image grows by 2w in each dimension. For the binary image I snap the colour to 0 or 255 so it stays binary. I also did it manually: I make a larger array filled with the border value and copy the image into the centre. For the complement I compute 255 minus each pixel, so dark becomes bright. cv2.bitwise_not gives the same result, and for a binary image it simply swaps black and white."

What is padding and why is it needed?

Adding pixels around the image. Needed so filters and neighbourhood operations have neighbours at the edges, to avoid wrap-around error in DFT filtering, to fit a required size, and for display borders.

What are the parameters of copyMakeBorder?

src, top, bottom, left, right, borderType, value. The value is used only with BORDER_CONSTANT.

Name the border types. Which is OpenCV's default for filters?

CONSTANT, REPLICATE, REFLECT, REFLECT_101, WRAP. The default (BORDER_DEFAULT) is REFLECT_101.

What is the output size for a 512×512 image with a 20-pixel border?

552×552, i.e. (M + 2w) × (N + 2w).

How much padding does a 5×5 filter need?

(5 − 1)/2 = 2 pixels on each side.

How do you put a coloured border on a grayscale image?

Convert to 3 channels with cvtColor(gray, COLOR_GRAY2BGR), then pad with a (B, G, R) value.

What is the formula for the image negative?

s = L − 1 − r. For 8-bit: s = 255 − r.

Why does bitwise_not give the same result as 255 − r?

255 is 11111111 in binary, so subtracting from it flips every bit. Example: 212 = 11010100 → 00101011 = 43.

Is the complement a point or neighbourhood operation?

A point operation: s = T(r), and each pixel is handled independently. Padding exists to support neighbourhood operations.

Where is the image negative used?

Enhancing white or grey detail in dark regions (e.g. mammograms), viewing film negatives, inverting binary masks.

What is the complement of a binary image in set terms?

The set complement Ac, i.e. a logical NOT: object and background swap. It is used in morphology.

Name other point-processing transformations.

Log, inverse log, power-law (gamma), contrast stretching, thresholding, intensity-level slicing, bit-plane slicing.

What are 4-neighbours and 8-neighbours?

N4: up, down, left, right. N8: N4 plus the 4 diagonals. City-block distance D4 = 1 means 4-neighbours; chessboard distance D8 = 1 means 8-neighbours.

Assignment 4 · Point processing for enhancement

Log transform · Power-law (gamma) · Contrast stretching

Q1: enhance the input image using the log transform. Assume c = 1.

Q2: enhance the input image using the power-law (gamma) transform. Assume c = 1 and take γ from the user.

Q3: enhance the input image using intensity-level slicing (contrast stretching). Take the input range and the desired output range from the user (e.g. 80–120 stretched to 50–150).

01Concept explanation

1.1 Enhancement and point processing

Image enhancement means processing an image so the result is more suitable for a specific purpose, usually to make detail easier to see. In the spatial domain we work on the pixels directly:

g(x, y) = T[ f(x, y) ]

When T looks at only the single pixel at (x, y), it is a point operation (also called an intensity or grey-level transformation). It can be written as s = T(r), where r is the input grey level and s the output, and drawn as a transfer curve. All three questions here are point operations, like the negative in Assignment 3 and thresholding in Assignment 1.

Reading a transfer curve: where the curve is steeper than 45° (slope > 1), input levels are spread further apart, so contrast increases in that range. Where it is flatter (slope < 1), levels are squeezed together and contrast decreases. No point transform can increase contrast everywhere; it takes contrast from one range and gives it to another.

Transfer curves used in this assignment. Curves above the diagonal brighten; curves below it darken. The steep part of each curve is where contrast gets stretched.
Transfer curves used in this assignment. Curves above the diagonal brighten; curves below it darken. The steep part of each curve is where contrast gets stretched.

Q1 · 1.2 Log transformation

Formula · Log transform s = c · log(1 + r) r ≥ 0, c is a constant c = 1 (as given): s ranges from log(1) = 0 to log(256) ≈ 5.545 → rescale for display c = 255 / log(256): maps 0 → 0 and 255 → 255 directly (≈ 45.99)
  • Why "1 +": log(0) is −∞. Adding 1 makes black (r = 0) map to 0.
  • Shape: very steep near 0 and flat near 255. It expands dark values and compresses bright values. In our image, r = 5 becomes 82 and r = 20 becomes 140, while r = 100 only reaches 212.
  • When to use it: images whose important detail is in the dark range, and especially when the dynamic range is huge. The classic case is a Fourier spectrum: the DC value of cameraman's DFT is 33,832,495 while most other values are tiny, so it looks completely black without the log (see Part 5).
  • Inverse log (exponential), s = c·(er − 1), does the opposite: it expands bright values.
Exam tip · "c = 1" and the display problem

With c = 1 the raw output only lies in 0 to 5.5. Shown as an 8-bit image, that is nearly black. You must rescale to 0–255 by multiplying by 255 / log(256) or by min-max normalising (cv2.normalize). Say this explicitly: "c = 1 gives the shape of the curve; scaling to 0–255 is only for display." The base of the log (ln, log10, log2) does not matter after scaling, because changing the base only multiplies by a constant.

Q2 · 1.3 Power-law (gamma) transformation

Formula · Power law s = c · r^γ r normalised to [0, 1] (r = pixel / 255), then output = 255 · s γ < 1 : curve above the diagonal → brightens, expands dark levels (like log) γ = 1 : identity, no change γ > 1 : curve below the diagonal → darkens, expands bright levels
  • Why normalise first: on raw 0–255 values, 2550.4 = 9.2 (almost black) and 2552.5 ≈ 1,038,000 (far beyond 255). With r in [0, 1], rγ also stays in [0, 1] for any γ > 0, and c = 1 keeps it there. Black stays black (0γ = 0) and white stays white (1γ = 1).
  • Versus log: log is one fixed curve. Gamma is a family of curves, and γ lets you control how much to brighten or darken.
  • Gamma correction: CRT and LCD displays respond roughly as intensity ∝ voltage2.2, which darkens images. Pre-processing with s = r1/2.2 cancels this. That is where the name comes from, and why most image files are stored "gamma-encoded".
  • Typical values: γ = 0.3–0.6 for dark or under-exposed images (MRI, night shots, astronomy); γ = 1.5–5 for washed-out, over-exposed images (aerial photos in haze).

Q3 · 1.4 Contrast stretching

A low-contrast image uses only a narrow band of grey levels. Our moon image has 90% of its pixels between 96 and 123. Contrast stretching widens that band with a piecewise-linear transfer function through the control points (r1, s1) and (r2, s2):

Formula · Piecewise-linear contrast stretching ⎧ (s1 / r1) · r 0 ≤ r < r1 s = ⎨ s1 + (s2 − s1)/(r2 − r1) · (r − r1) r1 ≤ r ≤ r2 ← the stretch ⎩ s2 + (255 − s2)/(255 − r2) · (r − r2) r2 < r ≤ 255 Example 80–120 → 50–150: slope of the middle segment = (150 − 50)/(120 − 80) = 2.5
  • The middle slope 2.5 means two pixels that differed by 4 grey levels now differ by 10, so contrast in 80–120 is multiplied by 2.5.
  • The outer segments have slopes 50/80 = 0.625 and 105/135 ≈ 0.78. Contrast there decreases, which is the price of stretching the middle.
  • Keeping r1 < r2 and s1 ≤ s2 makes the function monotonically increasing, so the order of grey levels is preserved and no artificial edges appear.
  • Special cases: s1 = r1, s2 = r2 → identity. r1 = r2 = T, s1 = 0, s2 = 255 → thresholding (Assignment 1). (r1, s1) = (r_min, 0), (r2, s2) = (r_max, 255) → min-max stretching to the full range.
Name clash to explain in the viva: "intensity-level slicing" vs "contrast stretching"

The assignment puts both names on one question, but the textbook (Gonzalez & Woods) treats them as two different techniques.

  • Contrast stretching remaps a range with a piecewise-linear function. This is what the example "80–120 → 50–150" describes, so it is what the solution implements.
  • Intensity-level slicing highlights one range: pixels in [A, B] are set to a high value, and the rest are either set low (binary output) or left unchanged (shown in Part 5).

If asked, state the assumption: "levels outside the input range are mapped linearly to the remaining output range, so the mapping stays continuous." Part 5 shows what happens if they are left unchanged instead.

Syllabus · the rest of "point processing"

Bit-plane slicing: an 8-bit pixel is 8 bits. Bit-plane k is the image of bit k across all pixels. The higher-order planes (bits 7, 6, 5) hold most of the visual information and the lowest planes look like noise. This is why LSB steganography (hiding data in bit 0, part of the syllabus) is invisible. In code: plane_k = (img >> k) & 1.

Look-up tables (LUTs): any point operation depends only on r, so it needs to be computed just once for each of the 256 levels and then applied with cv2.LUT(img, lut). That is fast and is how Q3 is implemented.

1.5 Comparing the three transforms

LogPower-law (gamma)Contrast stretching
Formulac·log(1 + r)c·rγpiecewise linear through (r1,s1), (r2,s2)
Parametersnone (c fixed)γr1, r2, s1, s2
Curvesmooth, fixed shapesmooth family of curvesstraight segments
Brightens dark areas?Yes, stronglyYes if γ < 1Only within the chosen range
Darkens / fixes washed-out?NoYes if γ > 1Yes, choose the bright range
Best forHuge dynamic range (Fourier spectra), very dark imagesGamma correction, under- or over-exposureLow-contrast images in a known range
ControlNoneOne knobExact control of the ranges

02Solution

Q1 · Log transform

a4q1_log.py
# Assignment 4, Q1: Log transformation   s = c * log(1 + r),  c = 1
import cv2
import numpy as np

IMG_PATH = "hubble.png"              # a dark image benefits most

img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")

r = img.astype(np.float64)           # float, so log() gives decimals
c = 1                                # given in the assignment

# Apply the transform to every pixel at once (natural log)
s = c * np.log(1 + r)                # "1 +" avoids log(0) = -infinity
print(f"Raw log output range: {s.min():.3f} to {s.max():.3f}")   # 0 to ~5.545

# With c = 1 the output only spans 0 .. log(256) = 5.545, which would look
# almost black on a 0-255 display. Rescale it linearly to the full 0-255 range.
s_scaled = s * 255 / np.log(1 + 255)
out = np.uint8(np.round(s_scaled))

print("Mean intensity: before =", round(img.mean(), 1), "| after =", round(out.mean(), 1))
for v in (0, 5, 20, 100, 255):       # how a few input levels are mapped
    sv = round(c * np.log(1 + v) * 255 / np.log(1 + 255))
    print(f"  r = {v:3d}  ->  s = {sv:3d}")

cv2.imshow("Original", img)
cv2.imshow("Log transformed", out)
cv2.imwrite("a4_log.png", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
Raw log output range: 1.609 to 5.541
Mean intensity: before = 19.4 | after = 127.7
  r =   0  ->  s =   0
  r =   5  ->  s =  82
  r =  20  ->  s = 140
  r = 100  ->  s = 212
  r = 255  ->  s = 255

Q2 · Power-law (gamma) transform

a4q2_gamma.py
# Assignment 4, Q2: Power-law (gamma) transformation   s = c * r^gamma,  c = 1
import cv2
import numpy as np

IMG_PATH = "hubble.png"

img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")

gamma = float(input("Enter gamma (> 0; <1 brightens, >1 darkens): "))
if gamma <= 0:
    raise ValueError("Gamma must be positive")
c = 1

# 1. Normalise to [0, 1] so that r^gamma also stays in [0, 1]
r = img.astype(np.float64) / 255.0

# 2. Apply the power law to every pixel
s = c * np.power(r, gamma)

# 3. Back to 0-255 for display (c = 1 keeps s inside [0, 1])
out = np.uint8(np.round(255 * np.clip(s, 0, 1)))

print("Mean intensity: before =", round(img.mean(), 1), "| after =", round(out.mean(), 1))
print("Pixel 64 ->", round(255 * (64 / 255) ** gamma), "| pixel 192 ->", round(255 * (192 / 255) ** gamma))

cv2.imshow("Original", img)
cv2.imshow(f"Gamma = {gamma}", out)
cv2.imwrite("a4_gamma.png", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
Enter gamma (> 0; <1 brightens, >1 darkens): 0.4
Mean intensity: before = 19.4 | after = 84.6
Pixel 64 -> 147 | pixel 192 -> 228

Q3 · Contrast stretching

a4q3_stretch.py
# Assignment 4, Q3: Contrast stretching (piecewise-linear intensity mapping)
#   Input range [r1, r2] is mapped to output range [s1, s2]  (e.g. 80-120 -> 50-150).
#   Levels below r1 are mapped linearly to [0, s1], levels above r2 to [s2, 255],
#   so the mapping stays continuous and never reverses the order of grey levels.
import cv2
import numpy as np

IMG_PATH = "moon.png"                # low-contrast image

img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")

r1, r2 = map(int, input("Input intensity range  (r1 r2): ").split())
s1, s2 = map(int, input("Output intensity range (s1 s2): ").split())
if not (0 <= r1 < r2 <= 255 and 0 <= s1 <= s2 <= 255):
    raise ValueError("Need 0 <= r1 < r2 <= 255 and 0 <= s1 <= s2 <= 255")


def stretch(r):
    """Piecewise-linear transfer function through (0,0), (r1,s1), (r2,s2), (255,255)."""
    r = r.astype(np.float64)
    s = np.zeros_like(r)
    low = r < r1
    mid = (r >= r1) & (r <= r2)
    high = r > r2
    if r1 > 0:                                   # segment 1: 0..r1  -> 0..s1
        s[low] = (s1 / r1) * r[low]
    s[mid] = s1 + (s2 - s1) / (r2 - r1) * (r[mid] - r1)            # segment 2 (the stretch)
    if r2 < 255:                                 # segment 3: r2..255 -> s2..255
        s[high] = s2 + (255 - s2) / (255 - r2) * (r[high] - r2)
    return s


# A point operation depends only on the grey level, so compute it ONCE for
# all 256 levels (a look-up table) and then apply the table to the image.
lut = np.uint8(np.round(stretch(np.arange(256))))
out = cv2.LUT(img, lut)                          # same as lut[img]

print(f"Slope inside [{r1}, {r2}] = {(s2 - s1) / (r2 - r1):.2f}  (>1 means contrast increases)")
print("Before: min", img.min(), "max", img.max(), "std", round(img.std(), 1))
print("After : min", out.min(), "max", out.max(), "std", round(out.std(), 1))

cv2.imshow("Original", img)
cv2.imshow("Contrast stretched", out)
cv2.imwrite("a4_stretch.png", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
Input intensity range  (r1 r2): 80 120
Output intensity range (s1 s2): 50 150
Slope inside [80, 120] = 2.50  (>1 means contrast increases)
Before: min 0 max 255 std 13.3
After : min 0 max 255 std 22.2
Why the guard clauses if r1 > 0 and if r2 < 255

If the user enters r1 = 0, the first segment has no pixels and s1 / r1 would divide by zero. If r2 = 255, the last segment's slope divides by 255 − r2 = 0. The guards skip those segments when they are empty.

03Output images

Q1 · Log transform

Input: hubble.png (Hubble deep-field, grayscale), mean 19.4: very dark
Input: hubble.png (Hubble deep-field, grayscale), mean 19.4: very dark
Log transform, c = 1, scaled to 0–255: mean 127.7
Log transform, c = 1, scaled to 0–255: mean 127.7

What changed: most of this image is near-black sky (median 13), with faint galaxies only a few grey levels brighter. The log curve is extremely steep near 0, so those small differences are stretched enormously (13 → about 120). Hundreds of faint galaxies that were invisible are now clearly visible.

The cost: the background noise in the sky is stretched too, so the sky turns mid-grey and grainy. The bright stars, already near 255, barely change, so they lose contrast relative to each other (the curve is flat there).

Q2 · Gamma, γ = 0.4

Input, mean 19.4
Input, mean 19.4
γ = 0.4: mean 84.6
γ = 0.4: mean 84.6

γ < 1 bends the curve above the diagonal, so dark pixels brighten most: 64 → 147, while 192 → 228. Compared with the log result, γ = 0.4 is gentler. Faint galaxies appear but the sky stays darker, because the gamma curve is less steep at the very bottom. Changing γ lets you choose the balance; the log transform has no such control.

Q3 · Contrast stretching, 80–120 → 50–150

Input: moon.png, std 13.3: flat and grey
Input: moon.png, std 13.3: flat and grey
Stretched 80–120 → 50–150: std 22.2
Stretched 80–120 → 50–150: std 22.2
Left: the user's transfer function (red) has slope 2.5 between the two dots. Right: the histogram before and after; the narrow peak near 110 is spread over a wider range.
Left: the user's transfer function (red) has slope 2.5 between the two dots. Right: the histogram before and after; the narrow peak near 110 is spread over a wider range.

What changed: almost all lunar-surface pixels lie inside 80–120. Stretching that range ×2.5 makes crater rims, ridges and shadows clearly distinct. The standard deviation (a simple measure of contrast) rises from 13.3 to 22.2.

Min and max are still 0 and 255, because the moon image contains a few pure black and white pixels. Min/max alone would wrongly suggest nothing changed. The std and the histogram show the real effect.

Say this when you show the output

"The log transform expands dark levels, so the faint galaxies become visible. With c = 1 the output only reaches 5.5, so I scale it to 0–255. Gamma 0.4 does a similar but controllable brightening. For contrast stretching, most of the moon lies between 80 and 120, and I map that range to 50–150 with slope 2.5, which increases the contrast there by 2.5 times."

04Code walkthrough

Q1 · Log

r = img.astype(np.float64)
s = c * np.log(1 + r)

Converts to float so the logarithm can produce decimals (on uint8, 1 + r would also overflow at r = 255: 1 + 255 = 0). np.log is the natural log, applied element-wise to the whole matrix.

s_scaled = s * 255 / np.log(1 + 255)
out = np.uint8(np.round(s_scaled))

Divides by the largest possible value, log(256), so r = 255 maps to exactly 255. Then it rounds and converts to 8-bit for display. An alternative is cv2.normalize(s, None, 0, 255, cv2.NORM_MINMAX), which stretches the image's own min to 0 and max to 255.

cv2.normalize(src, dst, alpha, beta, norm_type) → dst

With norm_type=cv2.NORM_MINMAX: linearly maps the smallest value to alpha and the largest to beta (usually 0 and 255). Pass None as dst. Add dtype=cv2.CV_8U to get uint8 directly.

Q2 · Gamma

r = img.astype(np.float64) / 255.0
s = c * np.power(r, gamma)
out = np.uint8(np.round(255 * np.clip(s, 0, 1)))

Three steps: normalise to [0, 1], raise every pixel to the power γ (np.power(r, g) is the same as r ** g), then scale back to 0–255. np.clip is a safety net; with c = 1 it never triggers.

Q3 · Contrast stretching

r1, r2 = map(int, input(...).split())
if not (0 <= r1 < r2 <= 255 and 0 <= s1 <= s2 <= 255):
    raise ValueError(...)

Reads two numbers on one line. Validation ensures the ranges are inside 0–255, the input range is not empty (r1 < r2, otherwise the slope divides by zero), and the output is increasing.

low = r < r1
mid = (r >= r1) & (r <= r2)
high = r > r2

Three boolean masks split the levels into the three segments. Use & (element-wise AND) with brackets round each condition. Python's and does not work on arrays.

s[mid] = s1 + (s2 - s1) / (r2 - r1) * (r[mid] - r1)

The straight-line equation through (r1, s1) and (r2, s2): start at s1 and add slope × distance from r1. s[mid] = ... writes only the positions where the mask is True.

lut = np.uint8(np.round(stretch(np.arange(256))))
out = cv2.LUT(img, lut)

np.arange(256) = [0, 1, …, 255]. Passing it through stretch builds a 256-entry table: lut[r] is the output for level r. cv2.LUT replaces every pixel by its table entry. That is 256 calculations instead of 262,144. lut[img] (NumPy fancy indexing) does the same thing.

cv2.LUT(src, lut) → dst

src: 8-bit image. lut: array of 256 values (uint8 for a uint8 result). Each pixel value v is replaced by lut[v]. For a colour image the same table is applied to all channels, unless the table itself has 3 channels.

Common mistakes
  • Log on uint8: np.log(1 + img) with img as uint8 wraps 255 + 1 to 0, so log(0) = −inf for white pixels.
  • Displaying the c = 1 log result without scaling gives an almost black image (shown in Part 5).
  • Gamma on 0–255 values without normalising: values overflow or collapse.
  • Using Python and/or on arrays: "truth value of an array is ambiguous". Use & / |.
  • Integer division traps: in Python 3, / is float division, so (150−50)/(120−80) = 2.5 is correct. Using // would give 2.

05"What if" questions

What if we display the c = 1 log output without rescaling?
uint8 of log(1 + r): values only 1–5
uint8 of log(1 + r): values only 1–5
Scaled to 0–255
Scaled to 0–255

The raw values lie between 1.6 and 5.5. As 8-bit grey levels that is nearly black (a fully black image would be 0). The transform worked; the values are simply in the wrong range for display.

Why is the log transform used to display Fourier spectra?
|F(u,v)| scaled linearly: only the centre dot is visible
|F(u,v)| scaled linearly: only the centre dot is visible
log(1 + |F(u,v)|): the full structure appears
log(1 + |F(u,v)|): the full structure appears

The centre (DC) value of cameraman's spectrum is 33.8 million (the sum of all pixels), while most other coefficients are thousands of times smaller. Linear scaling maps almost everything to 0. The log compresses this enormous range, so you can see the spectrum's structure, such as the bright lines from strong edges like the tripod legs.

What if γ is changed: 0.2, 1, 2.5?
Original
Original
γ = 0.2: very bright, noisy sky
γ = 0.2: very bright, noisy sky
γ = 0.4
γ = 0.4
γ = 2.5: even darker, only bright stars remain
γ = 2.5: even darker, only bright stars remain

γ = 1 returns the original (r1 = r). The further γ is below 1, the stronger the brightening, and the more noise appears in dark areas. γ > 1 darkens, which makes this dark image worse. It suits washed-out images (next question).

When does γ > 1 help? (washed-out image)
Original cameraman
Original cameraman
Washed-out version (simulated with γ = 0.4): mean 181.7
Washed-out version (simulated with γ = 0.4): mean 181.7
After γ = 2.5: detail restored
After γ = 2.5: detail restored

A washed-out (hazy, over-exposed) image has its values crowded into the bright range. γ > 1 spreads the bright levels apart and pulls the image down. Because 0.4 × 2.5 = 1, γ = 2.5 exactly undoes γ = 0.4 (average error 0.34 grey levels from rounding): (r0.4)2.5 = r. This is the idea behind gamma correction.

What if γ is 0 or negative?

γ = 0: r0 = 1 for every pixel (NumPy also gives 00 = 1), so the output is completely white. γ < 0: rγ = 1/r|γ|, which is greater than 1 and infinite at r = 0 (division-by-zero warning), and after clipping the image is mostly white. The program rejects γ ≤ 0.

What if pixels outside [r1, r2] are left unchanged instead of mapped linearly?
Piecewise linear (continuous)
Piecewise linear (continuous)
Outside 80–120 left unchanged
Outside 80–120 left unchanged

The transfer function then jumps: r = 120 maps to 150, but r = 121 stays 121 (dashed orange line in the plot above). Grey-level order is no longer preserved. Pixels just above 120 become darker than pixels just below it, which can create false contours. For the moon it looks similar because few pixels are above 120, but it is the wrong design in general.

What if we stretch an even narrower range to the full 0–255 (95–125 → 0–255)?
80–120 → 50–150 (slope 2.5)
80–120 → 50–150 (slope 2.5)
95–125 → 0–255 (slope 8.5)
95–125 → 0–255 (slope 8.5)

Slope 8.5 makes the moon look dramatic and high-contrast. Everything below 95 is now pure black and everything above 125 pure white. Those regions are clipped and their detail is lost. Stretch harder only if the detail you care about is inside the range.

What does true intensity-level slicing look like?
Approach 1: levels ≥ 125 → 255, everything else → 0
Approach 1: levels ≥ 125 → 255, everything else → 0
Approach 2: levels ≥ 125 → 255, everything else unchanged
Approach 2: levels ≥ 125 → 255, everything else unchanged

Slicing highlights a range of interest (here the brightest 4% of the moon: sunlit crater walls). Approach 1 is a binary map (like a two-sided threshold); approach 2 marks the range while keeping context. It is used in medicine and satellite imaging to pick out, for example, blood vessels or water bodies at a known intensity.

What if we use min-max stretching (cv2.normalize) on the moon instead?

Nothing changes. Min-max stretching maps the image's own min (0) to 0 and max (255) to 255, and this image already contains a few 0 and 255 pixels. A handful of outlier pixels can defeat min-max stretching. That is why a user-chosen range (as in this assignment) or a percentile stretch (for example the 2nd–98th percentile → 0–255) works better.

What if the input range is reversed (r1 > r2) or s1 > s2?

r1 ≥ r2 makes the slope divide by zero or become negative, so the program rejects it. s1 > s2 gives a decreasing middle segment: the range is stretched and also inverted, like a partial negative (Assignment 3). That is valid maths but not "stretching", so the program asks for s1 ≤ s2.

What if we apply these to a colour image?

Applying the same curve to B, G and R separately works for gamma and log (all channels change the same way, so hue is mostly kept), but it can shift colours slightly. The cleaner approach is to convert to HSV or YCrCb, transform only the brightness channel (V or Y), and convert back.

06Viva / evaluation angle

30-second explanation

"All three are point transformations s = T(r). For the log, I compute log(1 + r) on a float copy with c = 1 and scale the result to 0–255 for display. It brightens dark detail. For gamma, I normalise to 0–1, raise to the power γ given by the user, and scale back. γ below 1 brightens and above 1 darkens. For contrast stretching, I read the input and output ranges and build a piecewise-linear lookup table through (r1, s1) and (r2, s2). The middle slope, 2.5 here, is how much the contrast increases. Then I apply the table with cv2.LUT."

What is a point operation? Give examples.

The output pixel depends only on the input pixel at the same location: s = T(r). Examples: negative, log, gamma, contrast stretching, thresholding, slicing.

Why log(1 + r) and not log(r)?

log(0) is −∞. Adding 1 maps black to 0 and keeps all outputs finite and non-negative.

What does the log transform do to dark and bright regions?

It expands dark levels (steep slope) and compresses bright levels (flat slope).

With c = 1, why is the output dark, and how did you fix it?

The output range is only 0–5.55. I multiply by 255/log(256) (or min-max normalise) to use the full 0–255 range.

What is gamma correction?

Displays respond to input as roughly a power of 2.2. Applying s = r1/2.2 beforehand compensates, so the displayed brightness is correct.

Effect of γ < 1, γ = 1, γ > 1?

Brighten (expands dark levels), no change, darken (expands bright levels).

Why normalise to [0, 1] before applying gamma?

So that rγ stays in [0, 1], keeps 0 → 0 and 1 → 1, and does not overflow.

Log vs gamma: which gives more control?

Gamma. It is a family of curves controlled by γ; the log transform has one fixed shape.

What is contrast stretching?

A piecewise-linear transform that maps a narrow input range [r1, r2] to a wider output range [s1, s2], increasing contrast there by the slope (s2−s1)/(r2−r1).

What slope did you get and what does it mean?

2.5 for 80–120 → 50–150. Differences between grey levels in that range are multiplied by 2.5.

How is contrast stretching related to thresholding?

Thresholding is the limiting case: r1 = r2 = T, s1 = 0, s2 = 255, so the slope is infinite and the output is binary.

Difference between contrast stretching and intensity-level slicing?

Stretching remaps a range continuously to improve contrast. Slicing highlights a range (sets it to a high value), leaving the rest at a low value or unchanged.

What is a lookup table and why use it?

A 256-entry array giving the output for every possible input level. A point operation is computed once per level instead of once per pixel; cv2.LUT applies it.

What is bit-plane slicing?

Separating the image into 8 binary images, one per bit. The high-order bits carry most of the visual information. Code: (img >> k) & 1.

Assignment 5 · Histogram processing

Histogram equalization · Histogram matching

Q1: enhance the contrast of a grayscale image using histogram equalization. Display the original and equalized images.

Q2: perform histogram matching of the input image with a reference image, using histogram equalization.

01Concept explanation

1.1 Histogram, PDF and CDF

From Assignment 1, the histogram counts pixels per grey level. Dividing by the total number of pixels turns it into a probability distribution.

Formula · Histogram, PDF, CDF h(r_k) = n_k count of pixels with level r_k p(r_k) = n_k / (M·N) PDF (normalised histogram), Σ p = 1 c(r_k) = Σ_{j=0..k} p(r_j) CDF (cumulative), rises from p(r_0) to 1

The CDF at level k answers: "what fraction of pixels are at or below level k?" It always increases (never decreases) and ends at 1. A low-contrast image has a narrow histogram, so its CDF climbs steeply over a short range and is flat everywhere else.

What the histogram shape tells you: dark image → histogram bunched on the left; bright → on the right; low contrast → narrow peak; high contrast → spread over the whole range. Histogram processing changes this shape directly.

Q1 · 1.2 Histogram equalization: the idea

Goal: transform the image so its histogram is (approximately) flat / uniform, meaning every grey level is used about equally. That automatically spreads a narrow histogram over the full 0–255 range and increases contrast. Unlike Assignment 4, there are no parameters: the transformation is computed from the image itself.

The key trick: use the image's own CDF as the transfer function.

Formula · Histogram equalization Continuous: s = T(r) = (L − 1) ∫_0^r p_r(w) dw → p_s(s) = 1/(L−1) (perfectly uniform) Discrete: s_k = T(r_k) = (L − 1) · Σ_{j=0..k} p_r(r_j) = (L − 1) · CDF(r_k) k = 0 … L−1 then round s_k to the nearest integer

Why the CDF works: where many pixels share similar levels (a tall histogram peak), the CDF rises steeply, so T has a large slope there and those crowded levels are pushed apart. Where few pixels exist, the CDF is flat, so those levels are squeezed together. Contrast is given to the grey ranges that are actually used. The CDF is non-decreasing, so the order of grey levels is preserved.

1.3 Step by step (with a tiny worked example)

  1. Compute the histogram nk for k = 0 … 255.
  2. Divide by M·N to get p(rk).
  3. Running sum → CDF.
  4. Multiply by L − 1 = 255 and round → mapping table sk.
  5. Replace every pixel r by s = table[r].

Example, a 3-bit image (L = 8) with 64 pixels:

rk01234567
nk0082424800
p(rk)00.125.375.375.12500
CDF00.125.5.875111
7 × CDF000.8753.56.125777
sk (rounded)00146777

The input used only levels 2–5. The output uses 1, 4, 6 and 7, spread across the range. Note that the output histogram is not perfectly flat (still four bars of 8, 24, 24, 8 pixels): equalization can move a level but cannot split pixels that share a level. Discrete equalization only approximates a uniform histogram.

Q2 · 1.4 Histogram matching (specification)

Equalization always aims at a flat histogram. Sometimes that over-enhances, or we want an image to look like another one (same lighting style, consistent images for comparison). Histogram matching transforms the input so its histogram resembles a chosen reference histogram.

Idea: equalization turns any image into the same (uniform) histogram. So equalize both images. Their equalized versions are directly comparable, and we can go "input → uniform → reference" by applying the reference's equalization in reverse.

Formula · Matching via equalization 1. Equalize the input: s_k = T(r_k) = (L−1) · CDF_input(r_k) 2. Equalize the reference: v_q = G(z_q) = (L−1) · CDF_ref(z_q) 3. Invert G: for each s_k, find z_q such that G(z_q) is closest to s_k → z = G⁻¹(s) 4. Map: every input pixel r_k → z = G⁻¹( T(r_k) )

In discrete form G is a table, so "G⁻¹" means searching the table for the nearest value. If several z give the same closest value, take the smallest z (the textbook convention; np.argmin does this automatically).

Uses: making medical or satellite images taken under different conditions comparable, stitching photos into a panorama or mosaic with consistent brightness, and colour/tone transfer between photos.

Syllabus · Local histogram processing (CLAHE)

Global equalization uses one histogram for the whole image, so a large uniform region (sky, background) dominates the CDF. Local / adaptive equalization computes a separate mapping for each small region (tile).

CLAHE (Contrast-Limited Adaptive HE) adds two refinements: (1) each tile's histogram is clipped at a limit before computing the CDF, so contrast in flat areas, which is mostly noise, cannot be over-amplified; (2) tile mappings are bilinearly interpolated so tile boundaries do not show.

In OpenCV: clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)); out = clahe.apply(img). See Part 5 for the image.

1.5 Comparison table

Contrast stretching (A4)Histogram equalizationHistogram matchingCLAHE
Targetuser's rangesflat histogramreference histogramflat per tile, clipped
Parametersr1, r2, s1, s2nonereference imageclip limit, tile size
Mappinglinear piecesCDF of imageG⁻¹(T(r))CDF per tile, interpolated
Global or localglobalglobalgloballocal
Riskclipping outside rangeover-enhancement, noise amplification, false contoursdepends on referenceslower, can look unnatural
Best forknown intensity rangeautomatic enhancement of low-contrast imagesmaking images consistentuneven lighting, medical images

02Solution

Q1 · Histogram equalization (manual + OpenCV)

a5q1_histeq.py
# Assignment 5, Q1: Histogram equalization
#   s_k = (L - 1) * sum_{j=0..k} p(r_j)      (scaled CDF of the image)
import cv2
import numpy as np
import matplotlib.pyplot as plt

IMG_PATH = "moon.png"
L = 256

img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")

# ---------------- Manual equalization ----------------
hist = np.bincount(img.ravel(), minlength=L)    # n_k: pixel count of each level
pdf = hist / img.size                           # p(r_k) = n_k / MN
cdf = np.cumsum(pdf)                            # running total, ends at 1.0
lut = np.uint8(np.round((L - 1) * cdf))         # s_k for every level k
eq_manual = lut[img]                            # map every pixel through the table

# ---------------- OpenCV built-in ----------------
eq_cv = cv2.equalizeHist(img)
print("Max difference manual vs OpenCV:", int(np.abs(eq_manual.astype(int) - eq_cv).max()))
print("Std (contrast) before:", round(img.std(), 1), "| after:", round(eq_cv.std(), 1))

# ---------------- Display images + histograms ----------------
fig, ax = plt.subplots(2, 2, figsize=(10, 7))
ax[0, 0].imshow(img, cmap="gray", vmin=0, vmax=255); ax[0, 0].set_title("Original")
ax[0, 1].imshow(eq_manual, cmap="gray", vmin=0, vmax=255); ax[0, 1].set_title("Equalized")
ax[1, 0].hist(img.ravel(), 256, range=(0, 256)); ax[1, 0].set_title("Original histogram")
ax[1, 1].hist(eq_manual.ravel(), 256, range=(0, 256)); ax[1, 1].set_title("Equalized histogram")
for a in ax[0]:
    a.axis("off")
plt.tight_layout()
plt.show()

cv2.imwrite("a5_eq_manual.png", eq_manual)
cv2.imwrite("a5_eq_cv.png", eq_cv)
Max difference manual vs OpenCV: 1
Std (contrast) before: 13.3 | after: 74.0
Why manual and OpenCV differ by 1 level

cv2.equalizeHist uses a slightly different scaling: it subtracts the count of the darkest occupied level so that level maps exactly to 0, i.e. (cdf − cdf_min) / (N − cdf_min) × 255. Rounding then differs by at most 1 level. Both are correct equalization. Mention this if your manual result doesn't match OpenCV pixel for pixel.

Q2 · Histogram matching (via equalization)

a5q2_match.py
# Assignment 5, Q2: Histogram matching (specification) using histogram equalization
#   1. Equalize the input:      s = T(r) = (L-1) * CDF_input(r)
#   2. Equalize the reference:  v = G(z) = (L-1) * CDF_ref(z)
#   3. For each s, find z whose G(z) is closest to s:  z = G^-1(s)
#   4. Map every input pixel r -> z
import cv2
import numpy as np
import matplotlib.pyplot as plt

INPUT_PATH = "moon.png"
REF_PATH = "cameraman.png"
L = 256

inp = cv2.imread(INPUT_PATH, cv2.IMREAD_GRAYSCALE)
ref = cv2.imread(REF_PATH, cv2.IMREAD_GRAYSCALE)
if inp is None or ref is None:
    raise FileNotFoundError("Check both image paths")


def equalization_map(image):
    """Return T(k) = round((L-1) * CDF(k)) for k = 0..L-1."""
    hist = np.bincount(image.ravel(), minlength=L)
    cdf = np.cumsum(hist) / image.size
    return np.round((L - 1) * cdf)


T = equalization_map(inp)          # step 1: r -> s
G = equalization_map(ref)          # step 2: z -> v

# Step 3: invert G. For each s_k pick the z with G(z) nearest to s_k.
# np.argmin returns the FIRST (smallest) z when several are equally close.
mapping = np.array([np.argmin(np.abs(G - s_k)) for s_k in T], dtype=np.uint8)

matched = mapping[inp]             # step 4: apply r -> z to every pixel

print("Mean  input / reference / matched:",
      round(inp.mean(), 1), round(ref.mean(), 1), round(matched.mean(), 1))

fig, ax = plt.subplots(2, 3, figsize=(13, 7))
for k, (im, name) in enumerate([(inp, "Input"), (ref, "Reference"), (matched, "Matched")]):
    ax[0, k].imshow(im, cmap="gray", vmin=0, vmax=255); ax[0, k].set_title(name); ax[0, k].axis("off")
    ax[1, k].hist(im.ravel(), 256, range=(0, 256)); ax[1, k].set_title(name + " histogram")
plt.tight_layout()
plt.show()

cv2.imwrite("a5_matched.png", matched)
Mean  input / reference / matched: 112.2 129.1 134.2
Cross-check with a library (optional)
from skimage.exposure import match_histograms
matched_sk = match_histograms(inp, ref)     # uses CDF interpolation instead of rounding
# differs from the manual result by 0.62 grey levels on average

03Output images

Q1 · Equalization

Original moon.png: std 13.3
Original moon.png: std 13.3
Equalized (manual): std 74.0
Equalized (manual): std 74.0
Black line = CDF. Before: a tall narrow peak near 110 and a CDF that jumps from ~0 to ~1 between 95 and 125. After: the histogram is spread over 0–255 and the CDF is nearly a straight diagonal line, which is the signature of a uniform histogram.
Black line = CDF. Before: a tall narrow peak near 110 and a CDF that jumps from ~0 to ~1 between 95 and 125. After: the histogram is spread over 0–255 and the CDF is nearly a straight diagonal line, which is the signature of a uniform histogram.

What changed: the narrow band 95–125 that held 90% of the pixels is now spread across almost the whole 0–255 range. Craters, ridges and the dark maria that were barely visible now stand out strongly. The standard deviation rose from 13.3 to 74.0, far more than the contrast stretch in A4 (22.2), and no parameters were needed.

Why the histogram has gaps: the output histogram looks like a comb, with spikes separated by empty levels. Steep parts of the CDF jump several output levels at a time (e.g. input 112 → output 113, but 113 → 134: a jump of 21 levels), and the levels in between receive no pixels. This is normal for discrete equalization.

Side effects: the result looks harsh and grainy. Equalization amplified small noise variations as well as the real detail.

Q2 · Matching moon to cameraman's histogram

Input: moon
Input: moon
Reference: cameraman (bimodal histogram)
Reference: cameraman (bimodal histogram)
Matched: moon with cameraman's tonal distribution
Matched: moon with cameraman's tonal distribution
The matched histogram (right) copies the reference's shape: a peak of dark pixels and a large bright mass. Its CDF matches the reference CDF to within 0.086 at every level, the closest a discrete mapping can get.
The matched histogram (right) copies the reference's shape: a peak of dark pixels and a large bright mass. Its CDF matches the reference CDF to within 0.086 at every level, the closest a discrete mapping can get.

What changed: the moon now uses the tones of cameraman. Cameraman has a big cluster of very dark pixels (the coat) and a bright cluster (sky). The darkest ~20% of the moon (crater shadows, maria) has become near-black, and the rest has been pushed bright. Compared with equalization, the result is brighter and more two-toned, because the target was cameraman's histogram, not a flat one. Mean: input 112.2 → matched 134.2 (reference 129.1).

Say this when you show the output

"The moon's histogram is a narrow peak, so the image is low-contrast. Equalization uses the CDF as the mapping: steep where pixels are crowded, so those levels are spread across 0 to 255. The CDF becomes almost a straight line, which means the histogram is roughly uniform. For matching, I equalize both images, then for every equalized input value I find the reference level whose equalized value is closest. That maps the input onto the reference's histogram."

04Code walkthrough

Q1

hist = np.bincount(img.ravel(), minlength=L)

img.ravel() flattens the 2-D image into one long 1-D array. np.bincount counts how many times each value 0, 1, 2, … appears. minlength=256 guarantees 256 bins even if the brightest levels are unused. hist[k] = nk.

cv2.calcHist([images], [channels], mask, [histSize], [ranges]) → hist

OpenCV's histogram function, an alternative to bincount: cv2.calcHist([img], [0], None, [256], [0, 256]). All arguments are lists. channels [0] = first channel; mask None = whole image; histSize [256] bins; ranges [0, 256] (upper bound exclusive). Returns a 256×1 float32 array.

pdf = hist / img.size
cdf = np.cumsum(pdf)

img.size = M·N, the total pixel count. np.cumsum gives running totals: [p0, p0+p1, p0+p1+p2, …]. The last value is 1.0.

lut = np.uint8(np.round((L - 1) * cdf))
eq_manual = lut[img]

Builds the equalization table sk = round(255·CDF(k)). lut[img] is NumPy fancy indexing: every pixel value is used as an index into the table, so each pixel is replaced in one step (same as cv2.LUT).

cv2.equalizeHist(src) → dst

Built-in global histogram equalization. src must be 8-bit single-channel. A colour image raises an error, so equalize channels or the Y/V channel separately. No other parameters.

fig, ax = plt.subplots(2, 2, figsize=(10, 7))
ax[0, 0].imshow(img, cmap="gray", vmin=0, vmax=255)
ax[1, 0].hist(img.ravel(), 256, range=(0, 256))

A 2×2 grid of plots: images on top, histograms below. cmap="gray" shows the image in grey, not false colour. vmin=0, vmax=255 stops Matplotlib from auto-stretching the display, which would hide the contrast difference you are trying to show. hist(data, bins, range) plots the histogram.

Q2

def equalization_map(image):
    hist = np.bincount(image.ravel(), minlength=L)
    cdf = np.cumsum(hist) / image.size
    return np.round((L - 1) * cdf)

T = equalization_map(inp)
G = equalization_map(ref)

One reusable function computes the equalization table for any image (Q1's steps in three lines). T maps input level → equalized value; G maps reference level → equalized value.

mapping = np.array([np.argmin(np.abs(G - s_k)) for s_k in T],
                   dtype=np.uint8)

The inversion of G. For each of the 256 values sk in T: np.abs(G - s_k) is the distance from sk to every G(z), and np.argmin returns the index z of the smallest distance, i.e. the first z in a tie. So mapping[r] = z = G⁻¹(T(r)).

matched = mapping[inp]

Applies the final r → z table to every input pixel, again with fancy indexing.

Common mistakes
  • Forgetting to normalise the histogram (dividing by M·N): the CDF ends at 262,144 instead of 1, and every sk saturates at 255.
  • Using np.histogram(img, 256) without a range: it chooses bins from the image's min to max, not 0–255, so the bins are misaligned. Use bins=256, range=(0, 256) or bincount.
  • Passing a colour image to cv2.equalizeHist: error. Convert to grayscale first.
  • Matching by equalizing the input and then applying G (not G⁻¹): this goes the wrong direction. The reference table must be inverted.
  • Expecting a perfectly flat output histogram: discrete equalization only approximates it.

05"What if" questions

What if we equalize an image twice?

Almost nothing changes (in our test the maximum change was 1 level). After the first pass the CDF is already close to a straight line, so the second mapping is close to the identity. Equalization is (nearly) idempotent.

What if the image already has good contrast (cameraman)?
Original cameraman
Original cameraman
Equalized cameraman
Equalized cameraman

The gain is small, and some regions get worse. The huge bright cluster (sky and grass) takes up most of the CDF, so it gets stretched, and the grass becomes noisy and harsh. Equalization is not always an improvement: it maximises use of the grey scale, not visual quality.

What if we use CLAHE instead of global equalization?
Global equalization: harsh, grainy
Global equalization: harsh, grainy
CLAHE (clip 2.0, 8×8 tiles): natural, detailed
CLAHE (clip 2.0, 8×8 tiles): natural, detailed

CLAHE improves local detail (crater edges) without blowing up the flat regions, because the clip limit caps how steep any tile's mapping can be. A higher clip limit gives a stronger effect; smaller tiles make it more local.

What if we equalize a colour image channel by channel?
Original
Original
B, G, R equalized separately: colours change
B, G, R equalized separately: colours change
Only Y (brightness) of YCrCb equalized
Only Y (brightness) of YCrCb equalized

Equalizing each channel independently changes the ratio between R, G and B, so hues shift: the red saucer turns almost black and the warm orange wood turns a cold, pale grey-white. Equalizing only the luminance channel (Y in YCrCb, or V in HSV) improves contrast while keeping the colours.

What if the reference image is very dark?
Input
Input
Reference: hubble (dark)
Reference: hubble (dark)
Matched: the moon becomes a dark image
Matched: the moon becomes a dark image

The result takes on the reference's distribution. Matching to a dark image makes the input dark. This proves matching is not "enhancement" by itself: the result is only as good as the reference you choose.

What if the input and reference are the same image?

Then T = G and G⁻¹(T(r)) = r, so the output equals the input (up to rounding where several levels share one equalized value). This is a useful sanity test for your matching code.

What if the reference histogram is flat (uniform)?

A uniform reference has a straight-line CDF, so G is the identity and G⁻¹ is too. Matching then reduces to plain equalization. Equalization is a special case of matching.

What if we use a mask, or the image has a large uniform background?

A big uniform background (e.g. 60% black) puts a huge jump at one level of the CDF. Global equalization then spends most of the grey range on the background. Fixes: compute the histogram only over the region of interest (calcHist has a mask argument), or use CLAHE.

Does equalization create or destroy information?

Neither, in theory: it is a monotonic remapping. In practice it can merge levels (several inputs rounding to one output, so information is lost) and it amplifies noise. It cannot create detail that was not in the image; it only makes existing differences more visible.

06Viva / evaluation angle

30-second explanation

"For equalization, I compute the histogram with bincount, divide by the number of pixels to get the PDF, take the cumulative sum for the CDF, and multiply by 255 to get a lookup table. Mapping every pixel through it spreads the crowded grey levels over the full range. I compare with cv2.equalizeHist, and the results differ by at most 1. For matching, I compute equalization tables T for the input and G for the reference. For every T value I find the reference level whose G is closest, which is the inverse of G, and apply that mapping. The matched histogram then follows the reference's shape."

What is histogram equalization?

A point transform that uses the image's CDF as the mapping, sk = (L−1)·CDF(rk), so the output histogram is approximately uniform and contrast increases.

Why is the CDF used as the transformation?

It is monotonic (keeps grey-level order) and steep exactly where pixels are crowded, so it spreads those levels apart. In the continuous case it produces a perfectly uniform PDF.

Is the output histogram perfectly flat? Why not?

No. Pixels at the same level must map to the same output, so peaks cannot be split. Some output levels stay empty, giving a comb shape.

Does equalization need parameters?

No. It is fully automatic, computed from the image's own histogram.

What is histogram matching? Why is it needed?

Transforming an image so its histogram resembles a specified reference. Needed when a flat histogram is not desired, or to make images consistent with each other.

Steps of histogram matching?

Equalize the input (T); equalize the reference (G); for each T value find z with G(z) closest (G⁻¹); map r → G⁻¹(T(r)).

Is equalization a special case of matching?

Yes: matching to a uniform histogram is equalization.

Disadvantages of histogram equalization?

Over-enhancement, noise amplification, unnatural look, false contours from merged levels, dominated by large uniform regions, and it changes colours if done per channel.

What is CLAHE?

Contrast-Limited Adaptive Histogram Equalization: tile-wise equalization with the histogram clipped at a limit (avoiding noise amplification) and bilinear interpolation between tiles.

How do you equalize a colour image correctly?

Convert to YCrCb (or HSV), equalize only Y (or V), and convert back, so colours are preserved.

Equalization vs contrast stretching?

Stretching is linear with user-chosen ranges. Equalization is non-linear (follows the CDF) and automatic.

What does cv2.equalizeHist require as input?

An 8-bit, single-channel image.

Assignment 6 · Neighbourhood processing · Lowpass filtering

Smooth an image: averaging, weighted max(|x|,|y|), Gaussian

Smooth the input image using (1) an averaging (unweighted) filter, (2) a weighted filter h(x, y) = max(|x|, |y|), (3) a Gaussian filter.

Take the filter size, other parameters such as σ for the Gaussian, and the padding method (replication, zero padding, etc.) from the user.

01Concept explanation

1.1 From point to neighbourhood processing

Assignments 1–5 were point operations: each output pixel depended on one input pixel. Smoothing is a neighbourhood operation. Each output pixel is computed from a small window (e.g. 3×3 or 5×5) of input pixels around it. The window of weights is called a kernel, mask or filter.

1.2 Spatial filtering: correlation and convolution

Formula · Spatial correlation (what the code computes) Correlation: g(x, y) = Σ_{s=−a..a} Σ_{t=−b..b} w(s, t) · f(x + s, y + t) kernel size m × n, a = (m−1)/2, b = (n−1)/2 Convolution: g(x, y) = Σ Σ w(s, t) · f(x − s, y − t) (= correlation with the kernel rotated 180°)

In words: place the kernel centre on a pixel, multiply each kernel weight by the pixel under it, add the products, and write the sum to the output at the centre position. Slide to the next pixel and repeat.

Correlation vs convolution: convolution flips the kernel by 180° first. For symmetric kernels (box, max(|x|,|y|), Gaussian, Laplacian) the two give the same result. cv2.filter2D actually computes correlation.

1.3 Why smoothing works, and what "lowpass" means

Noise is mostly rapid, random pixel-to-pixel variation. Averaging a neighbourhood cancels much of it out: random positive and negative deviations average towards zero. Averaging N independent noisy values reduces the noise standard deviation by √N, so a 5×5 box reduces it by up to 5×.

The cost is that real rapid changes, i.e. edges and fine detail, are averaged too, so the image gets blurred. In frequency terms, sharp changes are high frequencies and smooth regions are low frequencies. A smoothing filter lets low frequencies pass and attenuates high ones, so it is a lowpass filter.

Rule · Smoothing kernels are normalised

All weights are non-negative and sum to 1. Then a flat region of value 100 stays 100 (average brightness is preserved). If the weights summed to 2, the image would double in brightness; if 0.5, it would darken.

1.4 Filter 1: averaging (box) filter

Formula · Box filter w(s, t) = 1 / (n·n) for every cell 3×3: (1/9) · [1 1 1; 1 1 1; 1 1 1]

Every neighbour counts equally. It is simple and fast, but it has two weaknesses. Because the weights stop abruptly at the window edge, it produces slightly "blocky" blur. And a pixel 2 steps away counts as much as the centre, so edges blur more than necessary.

1.5 Filter 2: weighted filter h(x, y) = max(|x|, |y|)

Here (x, y) are coordinates relative to the kernel centre (from −k to +k, with k = n // 2). max(|x|, |y|) is the chessboard distance D8 from the centre (Assignment 3), so the weight equals "which ring" the cell is in:

5×5, before normalising: after normalising (÷ sum = 40): 2 2 2 2 2 .05 .05 .05 .05 .05 2 1 1 1 2 .05 .025 .025 .025 .05 2 1 0 1 2 .05 .025 0 .025 .05 2 1 1 1 2 ... 2 2 2 2 2 Sum of weights = Σ_{d=1..k} 8d · d = 8 · Σ d² → 3×3: 8, 5×5: 40, 7×7: 112

What makes this kernel unusual: the centre weight is 0, and weights grow with distance. Each output pixel ignores its own value and is dominated by the outer ring. It still smooths (all weights ≥ 0, summing to 1), but it blurs more than a box of the same size and preserves less detail. That is the opposite of the usual "weighted average" idea, where the centre counts most. Part 5 compares it with a centre-heavy version.

Reading the formula (state this assumption)

The sheet prints "max(|x|.|y|)". Read the dot as a comma, max(|x|, |y|), because the max of a single product would be meaningless. Also mention that the weights must be normalised by their sum. Without that, a 5×5 kernel would multiply brightness by 40.

For comparison, the textbook's standard weighted average gives the centre the most weight:

(1/16) · [1 2 1; 2 4 2; 1 2 1] ← approximately a small Gaussian

1.6 Filter 3: Gaussian filter

Formula · 2-D Gaussian kernel G(x, y) = (1 / 2πσ²) · e^( −(x² + y²) / 2σ² ) then divide by the sum so the weights add to 1 σ controls the spread: small σ → narrow bell → mild blur; large σ → wide bell → strong blur Rule of thumb: kernel size ≈ 6σ (rounded up to odd), e.g. σ = 1 → 5×5 or 7×7
  • Weights fall off smoothly with distance, so nearby pixels count most. This blurs edges less than a box of the same strength.
  • Rotationally symmetric: it blurs equally in all directions.
  • Separable: G(x, y) = g(x)·g(y). A 2-D filter of size n×n can be done as a 1-D horizontal pass then a 1-D vertical pass, costing 2n instead of n² operations per pixel. OpenCV does this internally.
  • Its Fourier transform is also a Gaussian, so it has no ripples ("ringing") in the frequency domain (see the syllabus box below).
  • The 1/(2πσ²) factor normalises the continuous Gaussian. A truncated discrete kernel does not sum exactly to 1, so we divide by the actual sum instead.

1.7 Padding: what happens at the image border

An n×n kernel centred on an edge pixel overhangs the image by p = n // 2 pixels. Assignment 3 covered how to fill those pixels. The user's choice changes the output only near the border:

PaddingPatternEffect after smoothing
Zero (BORDER_CONSTANT, 0)000|abcd|000Black pixels get averaged in, so a dark frame appears; worse for bigger kernels
Replicateaaa|abcd|dddEdges stay the right brightness; may streak slightly
Reflectcba|abcd|dcbMost natural continuation; usually the best choice
Wrap (circular)bcd|abcd|abcOpposite edge leaks in (e.g. sky at the bottom). Matches the DFT's periodic assumption.

1.8 Comparing the filters

Box (average)max(|x|,|y|) weightedGaussianMedian (for reference; Assignment 9)
Typelinearlinearlinearnon-linear (order statistic)
Weightsall equal 1/n²0 at centre, rising outwardsbell-shaped, highest at centreno weights: takes the middle value
Parameter(s)nnn, σn
Edge preservationpoorpoorestbettergood
Gaussian noise (MSE vs clean, 5×5)155.8186.9103.4 (σ = 1)—
Salt-and-pepper noisepoor (spreads dots into blobs)poorpoorexcellent
Speedfastest (running sums)n² productsfast (separable)slower (sorting)
Syllabus · Frequency domain, DFT and lowpass filtering

2-D DFT: any image can be written as a sum of 2-D sinusoids of different frequencies. The DFT gives the amount (and phase) of each:

F(u, v) = Σ_{x=0..M−1} Σ_{y=0..N−1} f(x, y) · e^( −j2π(ux/M + vy/N) ) f(x, y) = (1/MN) Σ_u Σ_v F(u, v) · e^( +j2π(ux/M + vy/N) ) (inverse DFT)

Properties of the 2-D DFT to know:

  • F(0, 0), the DC term, equals the sum of all pixels = MN × mean (33,832,495 for cameraman).
  • Conjugate symmetry: |F(u, v)| = |F(−u, −v)| for real images.
  • Periodicity: the DFT assumes the image repeats in tiles, which is the reason for zero padding before frequency filtering.
  • Shifting: np.fft.fftshift (equivalently, multiplying f by (−1)x+y) moves F(0, 0) to the centre for display.
  • Separability: a 2-D DFT is 1-D DFTs on rows then columns.
  • Linearity and rotation: rotating the image rotates the spectrum.

Convolution theorem: spatial convolution equals multiplication in frequency, f * h ⇔ F · H. So filtering can be done as: DFT → multiply by a filter H(u, v) → inverse DFT.

Frequency-domain lowpass filters (D = distance from the centre, D0 = cut-off):

Ideal LPF: H = 1 if D ≤ D0, else 0 sharp cut → "ringing" ripples near edges Butterworth LPF: H = 1 / (1 + (D/D0)^(2n)) order n controls the sharpness of the cut Gaussian LPF: H = e^( −D² / 2D0² ) smooth → no ringing
a6_freq_lpf.py
import cv2
import numpy as np

img = cv2.imread("cameraman.png", 0).astype(np.float64)
M, N = img.shape

F = np.fft.fftshift(np.fft.fft2(img))         # DFT, low frequencies moved to the centre

u = np.arange(M) - M // 2                       # frequency coordinates
v = np.arange(N) - N // 2
V, U = np.meshgrid(v, u)
D = np.sqrt(U ** 2 + V ** 2)                    # distance from the centre
D0 = 30                                         # cut-off frequency

H_ideal = (D <= D0).astype(np.float64)          # 1 inside the circle, 0 outside
H_gauss = np.exp(-D ** 2 / (2 * D0 ** 2))       # smooth fall-off

def apply(H):
    g = np.fft.ifft2(np.fft.ifftshift(F * H))   # multiply, undo shift, inverse DFT
    return np.uint8(np.clip(np.real(g), 0, 255))

cv2.imwrite("ideal_lpf.png", apply(H_ideal))
cv2.imwrite("gauss_lpf.png", apply(H_gauss))
Spectrum |F| (log scale): low frequencies at the centre
Spectrum |F| (log scale): low frequencies at the centre
Ideal LPF, D0 = 30: blur + ringing (ripples around the coat and tripod)
Ideal LPF, D0 = 30: blur + ringing (ripples around the coat and tripod)
Gaussian LPF, D0 = 30: clean blur, no ringing
Gaussian LPF, D0 = 30: clean blur, no ringing

Ringing happens because the ideal filter's sharp edge in frequency corresponds to a sinc function (with ripples) in space. The Gaussian's transform is another Gaussian, with no ripples. That is the frequency-domain reason the spatial Gaussian filter is preferred.

02Solution

One program builds all three kernels, applies them with its own filtering function (so the user's padding choice is used exactly), and checks the result against OpenCV's built-in functions. The input is cameraman with added Gaussian noise (σ = 20) so the smoothing effect is easy to see.

a6_smoothing.py
# Assignment 6: Smoothing with
#   1. Averaging (box) filter          h = 1 / (n*n)
#   2. Weighted filter                 h(x, y) = max(|x|, |y|), normalised
#   3. Gaussian filter                 h(x, y) = exp(-(x^2 + y^2) / (2 sigma^2)), normalised
# Filter size, sigma and the padding method come from the user.
import cv2
import numpy as np

IMG_PATH = "cameraman_noisy.png"

img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")

# ---------------- User inputs ----------------
n = int(input("Filter size n (odd, >= 3): "))
if n < 3 or n % 2 == 0:
    raise ValueError("Filter size must be an odd number >= 3")

PADDING = {"1": ("zero padding", cv2.BORDER_CONSTANT),
           "2": ("replicate", cv2.BORDER_REPLICATE),
           "3": ("reflect", cv2.BORDER_REFLECT),
           "4": ("wrap (circular)", cv2.BORDER_WRAP)}
choice = input("Padding: 1 = zero, 2 = replicate, 3 = reflect, 4 = wrap : ").strip()
if choice not in PADDING:
    raise ValueError("Choose 1, 2, 3 or 4")
pad_name, border = PADDING[choice]

sigma = float(input("Sigma for the Gaussian filter (> 0): "))
if sigma <= 0:
    raise ValueError("Sigma must be positive")


# ---------------- Building the kernels ----------------
half = n // 2
coords = np.arange(-half, half + 1)            # e.g. n = 5 -> [-2 -1 0 1 2]
X, Y = np.meshgrid(coords, coords)             # x and y of every kernel cell

box = np.ones((n, n)) / (n * n)                # 1. every weight equal

weighted = np.maximum(np.abs(X), np.abs(Y)).astype(np.float64)
weighted /= weighted.sum()                     # 2. normalise so weights add to 1

gauss = np.exp(-(X ** 2 + Y ** 2) / (2 * sigma ** 2))
gauss /= gauss.sum()                           # 3. normalise (replaces 1/(2*pi*sigma^2))


# ---------------- Filtering (correlation) with the chosen padding ----------------
def apply_filter(image, kernel, border_type):
    k = kernel.shape[0]
    p = k // 2                                 # padding needed on each side
    padded = cv2.copyMakeBorder(image, p, p, p, p, border_type, value=0).astype(np.float64)
    rows, cols = image.shape
    out = np.zeros((rows, cols), np.float64)
    # Add up shifted copies of the image, each multiplied by one kernel weight.
    # This equals sliding the kernel over every pixel, but needs only n*n loop steps.
    for i in range(k):
        for j in range(k):
            out += kernel[i, j] * padded[i:i + rows, j:j + cols]
    return np.uint8(np.clip(np.round(out), 0, 255))


out_box = apply_filter(img, box, border)
out_weighted = apply_filter(img, weighted, border)
out_gauss = apply_filter(img, gauss, border)

np.set_printoptions(precision=3, suppress=True)
print(f"\nPadding: {pad_name}")
print("Weighted kernel (before normalising):\n", np.maximum(np.abs(X), np.abs(Y)))
print("Gaussian kernel:\n", gauss)

# ---------------- Check against OpenCV's built-ins ----------------
# (cv2.blur and cv2.filter2D reject BORDER_WRAP with an assertion error, so skip the check then)
if border != cv2.BORDER_WRAP:
    ref_box = cv2.blur(img, (n, n), borderType=border)
    ref_w = cv2.filter2D(img, -1, weighted, borderType=border)
    ref_g = cv2.GaussianBlur(img, (n, n), sigma, borderType=border)
    for name, a, b in [("box", out_box, ref_box), ("weighted", out_weighted, ref_w),
                       ("gaussian", out_gauss, ref_g)]:
        print(f"max |mine - OpenCV| for {name}: {np.abs(a.astype(int) - b).max()}")

cv2.imshow("Noisy input", img)
cv2.imshow("1. Averaging", out_box)
cv2.imshow("2. Weighted max(|x|,|y|)", out_weighted)
cv2.imshow("3. Gaussian", out_gauss)
cv2.imwrite("a6_box.png", out_box)
cv2.imwrite("a6_weighted.png", out_weighted)
cv2.imwrite("a6_gauss.png", out_gauss)
cv2.waitKey(0)
cv2.destroyAllWindows()

Console output (inputs: size 5, padding 2 = replicate, σ = 1.0):

Filter size n (odd, >= 3): 5
Padding: 1 = zero, 2 = replicate, 3 = reflect, 4 = wrap : 2
Sigma for the Gaussian filter (> 0): 1.0

Padding: replicate
Weighted kernel (before normalising):
 [[2 2 2 2 2]
 [2 1 1 1 2]
 [2 1 0 1 2]
 [2 1 1 1 2]
 [2 2 2 2 2]]
Gaussian kernel:
 [[0.003 0.013 0.022 0.013 0.003]
 [0.013 0.06  0.098 0.06  0.013]
 [0.022 0.098 0.162 0.098 0.022]
 [0.013 0.06  0.098 0.06  0.013]
 [0.003 0.013 0.022 0.013 0.003]]
max |mine - OpenCV| for box: 0
max |mine - OpenCV| for weighted: 1
max |mine - OpenCV| for gaussian: 1

The manual results match OpenCV to within 1 grey level (rounding), which proves the kernels and padding are right.

Shorter version using only built-ins (if the examiner allows it)
out_box   = cv2.blur(img, (n, n), borderType=border)                  # = filter2D with ones/n²
out_w     = cv2.filter2D(img, -1, weighted, borderType=border)        # any custom kernel
out_gauss = cv2.GaussianBlur(img, (n, n), sigma, borderType=border)

cv2.blur and cv2.filter2D refuse BORDER_WRAP (assertion error), which is one reason the solution uses its own filtering function.

03Output images

Input: cameraman + Gaussian noise (σ = 20) · MSE vs clean = 373.3
Input: cameraman + Gaussian noise (σ = 20) · MSE vs clean = 373.3
1. Averaging 5×5 · MSE 155.8
1. Averaging 5×5 · MSE 155.8
2. Weighted max(|x|,|y|) 5×5 · MSE 186.9
2. Weighted max(|x|,|y|) 5×5 · MSE 186.9
3. Gaussian 5×5, σ = 1 · MSE 103.4
3. Gaussian 5×5, σ = 1 · MSE 103.4
The three 5×5 kernels as heat maps (darker = larger weight). Box: flat. max(|x|,|y|): empty centre, heavy outer ring. Gaussian: concentrated at the centre.
The three 5×5 kernels as heat maps (darker = larger weight). Box: flat. max(|x|,|y|): empty centre, heavy outer ring. Gaussian: concentrated at the centre.

What changed: all three remove most of the grainy noise in the sky and on the coat, and all three blur the edges (tripod legs, buildings, face). MSE is the average squared difference from the clean original, so lower is better. Every filter more than halves it.

Why the Gaussian wins (MSE 103.4): with σ = 1 most of its weight is on the centre and the nearest neighbours, so it averages away noise while keeping edges relatively sharp.

Why the box is in the middle (155.8): all 25 pixels count equally, so pixels 2 steps away, possibly across an edge, blur the edge more.

Why max(|x|,|y|) is the blurriest (186.9): its centre weight is 0 and 80% of the weight (32 of 40) is in the outer ring, 2 pixels away. Each output is mostly an average of distant pixels, so edges smear the most. The thin tripod legs are visibly softer than in the box result.

Say this when you show the output

"All three are lowpass filters: they average a neighbourhood, so random noise cancels out but edges blur too. The box gives every pixel equal weight. The given weighted filter max(|x|,|y|) gives the centre zero weight and the outer ring the most, so it blurs the most. The Gaussian gives the centre the most weight with a smooth fall-off, so it removes noise with the least blurring. Its error against the clean image is the lowest. I padded with replication, so there is no dark border."

04Code walkthrough

n = int(input("Filter size n (odd, >= 3): "))
if n < 3 or n % 2 == 0:
    raise ValueError(...)

The size must be odd so the kernel has a single centre pixel. An even size (4×4) has no centre and shifts the image by half a pixel. n = 1 would make the max(|x|,|y|) kernel all zeros (sum 0), so we divide by zero.

PADDING = {"1": ("zero padding", cv2.BORDER_CONSTANT), ...}
pad_name, border = PADDING[choice]

A dictionary maps the menu number to a readable name and the matching OpenCV constant. This is cleaner than a chain of if/elif.

half = n // 2
coords = np.arange(-half, half + 1)
X, Y = np.meshgrid(coords, coords)

Creates the kernel coordinate grid centred at 0. For n = 5, coords = [−2, −1, 0, 1, 2]. np.meshgrid returns two 5×5 arrays: X holds each cell's x (column offset) and Y its y (row offset). Both kernel formulas use these.

box = np.ones((n, n)) / (n * n)

An n×n array of ones divided by n², so each weight is 1/25 for n = 5 and the sum is 1.

weighted = np.maximum(np.abs(X), np.abs(Y)).astype(np.float64)
weighted /= weighted.sum()

np.maximum takes the element-wise larger of the two arrays (different from np.max, which returns one number for the whole array). This gives the ring pattern. Dividing by the sum (40 for 5×5) normalises it.

gauss = np.exp(-(X ** 2 + Y ** 2) / (2 * sigma ** 2))
gauss /= gauss.sum()

The Gaussian formula evaluated at every (x, y). Normalising by the sum replaces the 1/(2πσ²) constant and guarantees an exact sum of 1. OpenCV builds the same kernel with k = cv2.getGaussianKernel(n, sigma); k @ k.T (separable: outer product of two 1-D kernels).

p = k // 2
padded = cv2.copyMakeBorder(image, p, p, p, p, border_type, value=0)

Pads by p = n // 2 on each side, the exact overhang of the kernel, using the user's border type (Assignment 3). Converted to float so the weighted sums keep decimals.

for i in range(k):
    for j in range(k):
        out += kernel[i, j] * padded[i:i + rows, j:j + cols]

The heart of the filter. Instead of looping over 262,144 pixels and, at each, 25 kernel cells, it loops over the 25 kernel cells only. For cell (i, j), padded[i:i+rows, j:j+cols] is the whole image shifted by (i − p, j − p), i.e. the neighbour at that offset for every pixel at once. Multiply it by that cell's weight and add. After all cells, out holds Σ w·f for every pixel, which is exactly correlation, and it is fast.

return np.uint8(np.clip(np.round(out), 0, 255))

Round, clip and convert to 8-bit. With normalised non-negative kernels the result is always in 0–255 already; the clip is a safety net.

cv2.filter2D(src, ddepth, kernel, anchor=(-1,-1), delta=0, borderType=BORDER_DEFAULT) → dst

ddepth: output depth. -1 = same as input (uint8 → uint8, clipped); use cv2.CV_64F to keep negative values (needed for sharpening in A7). kernel: float array, any size. anchor: kernel centre, default (−1, −1) = middle. delta: constant added to the result. borderType: padding (no WRAP). Computes correlation.

cv2.blur(src, ksize, borderType=...) → dst

Box filter. ksize is a tuple (width, height), e.g. (5, 5); it can be non-square, e.g. (9, 1) for horizontal-only blur.

cv2.GaussianBlur(src, ksize, sigmaX, sigmaY=0, borderType=...) → dst

ksize: (w, h), both odd and positive, or (0, 0) to compute the size from σ. sigmaX: σ in x; sigmaY = 0 means "same as sigmaX". If sigmaX = 0, σ is computed from ksize as 0.3·((ksize−1)·0.5 − 1) + 0.8 (5 → σ = 1.1). Typical: (3,3)–(7,7), σ 0.5–2.

np.meshgrid(x, y) → X, Y

Turns two 1-D coordinate arrays into two 2-D grids, so a formula in x and y can be evaluated for every cell without loops.

Common mistakes
  • Not normalising the max(|x|,|y|) or Gaussian kernel: the output becomes very bright and saturated (×40 for 5×5).
  • Filtering in uint8 by hand: products and sums overflow. Convert to float first.
  • Even kernel size: no centre pixel, so the output shifts.
  • Too-small size for a large σ (e.g. 3×3 with σ = 5): the bell is cut off and the filter behaves like a box. Use size ≈ 6σ.
  • Confusing np.max and np.maximum: max returns one number; maximum compares element by element.
  • Forgetting borderType in the built-ins: OpenCV silently uses REFLECT_101, not the user's choice.

05"What if" questions

What if we increase the filter size (3, 9, 15)?
Box 3×3 · MSE 117.9
Box 3×3 · MSE 117.9
Box 9×9 · MSE 269.3
Box 9×9 · MSE 269.3
Box 15×15 · MSE 397.0
Box 15×15 · MSE 397.0

A bigger window averages more pixels, so it removes more noise but blurs more. Past a point the blur error outweighs the noise removed: 15×15 is worse than the noisy input (397 vs 373). For this noise level, 3×3 is the best box size. Choose the size by the scale of the noise relative to the detail you need to keep.

What if we change σ for the Gaussian (1, 3, 6 at 25×25)?
σ = 1 · MSE 104.0
σ = 1 · MSE 104.0
σ = 3 · MSE 257.5
σ = 3 · MSE 257.5
σ = 6 · MSE 408.3
σ = 6 · MSE 408.3

σ, not the kernel size, controls the amount of blur. With a 25×25 kernel and σ = 1, the weights beyond ±3 are practically zero, so the result is the same as the 5×5 version (MSE 104.0 vs 103.4). Doubling σ roughly doubles the blur radius. If σ is large relative to the window, the bell is truncated and the filter starts behaving like a box.

What if we change the padding (zero / replicate / reflect / wrap)?

With a large 41×41 box filter on the clean image so the border effect is obvious:

Zero padding: dark frame
Zero padding: dark frame
Replicate: edges keep their brightness
Replicate: edges keep their brightness
Reflect: natural edges
Reflect: natural edges
Wrap: dark ground leaks into the top and bright sky into the bottom
Wrap: dark ground leaks into the top and bright sky into the bottom

The centre of the image is identical in all four. Only a band of width n // 2 = 20 pixels near the border differs. With a 3×3 kernel the difference is a single pixel ring and hard to see. Zero padding darkens because black pixels are averaged in. Wrap brings the opposite edge in (sky at the bottom, ground at the top).

What if the centre weight is the largest instead (pyramid kernel (k+1) − max(|x|,|y|))?
Given kernel max(|x|,|y|), centre 0 · MSE 186.9
Given kernel max(|x|,|y|), centre 0 · MSE 186.9
Box · MSE 155.8
Box · MSE 155.8
Pyramid 3 − max(|x|,|y|), centre heaviest · MSE 129.5
Pyramid 3 − max(|x|,|y|), centre heaviest · MSE 129.5

Turning the given kernel "inside out" (5×5 weights 3 at the centre, 2 in ring 1, 1 in ring 2) keeps more of each pixel's own value, so edges stay sharper and the error drops below the box. This shows the general rule: centre-weighted kernels preserve detail better. That is the idea behind the textbook's [1 2 1; 2 4 2; 1 2 1]/16 and the Gaussian.

What if the noise is salt-and-pepper instead of Gaussian?
Salt & pepper, 8% of pixels · MSE 1726
Salt & pepper, 8% of pixels · MSE 1726
3×3 box · MSE 302: dots smeared into grey blobs
3×3 box · MSE 302: dots smeared into grey blobs
3×3 median · MSE 68: dots removed
3×3 median · MSE 68: dots removed

A linear filter averages the extreme 0/255 values into the neighbours, so each dot becomes a grey smudge. The median sorts the 9 values and takes the middle one. Extreme outliers end up at the ends of the sorted list and are simply ignored. This is why non-linear order-statistic filters are used for impulse noise (Assignments 9 and 10).

What if we smooth a colour image?

All three methods work unchanged on a 3-channel image if you use the OpenCV built-ins (each channel is filtered with the same kernel). The manual function would need to loop over channels or use padded[..., c]. Blurring channels independently is fine for smoothing, because the same kernel keeps the colour balance.

What if we apply the 3×3 box filter twice?

Two box passes equal one pass with the convolution of the two kernels: a 5×5 pyramid-shaped kernel (1 2 3 2 1 profile). Repeating box filters converges towards a Gaussian (central limit theorem). That is a fast way to approximate Gaussian blur.

What if the filter is applied in the frequency domain instead?

By the convolution theorem the result is the same as spatial convolution (with circular, wrap-around padding, unless you zero-pad). It is faster for large kernels, since the FFT cost does not grow with kernel size. The ideal lowpass filter creates ringing; the Gaussian does not (see the syllabus box in Part 1).

What if the weights don't sum to 1?

Brightness scales by the sum: a kernel summing to 1.2 brightens by 20% and saturates highlights; one summing to 0.8 darkens. A kernel summing to 0 (positive and negative weights) is no longer a smoothing filter. It is a derivative/edge filter, the topic of Assignment 7.

06Viva / evaluation angle

30-second explanation

"I read the filter size, the padding method and σ from the user. I build three kernels on a coordinate grid centred at zero: a box of 1/n², the given weights max(|x|,|y|), and a Gaussian. Each is normalised so its weights sum to 1. My filter function pads the image by n//2 with the chosen border type, then adds up shifted copies of the image multiplied by each kernel weight. That is correlation. The results match OpenCV's blur, filter2D and GaussianBlur to within 1 grey level. The Gaussian removes the noise with the least blurring."

What is spatial filtering?

Computing each output pixel as a weighted sum of a neighbourhood of input pixels, using a kernel. It is a neighbourhood operation.

Why is smoothing called lowpass filtering?

It keeps slowly varying (low-frequency) content and attenuates rapid changes (high frequencies: noise and edges).

Why must smoothing kernels sum to 1?

So that a constant region keeps its value, i.e. average brightness is preserved.

Correlation vs convolution?

Convolution rotates the kernel by 180° before sliding it. They are identical for symmetric kernels. filter2D computes correlation.

Why should the kernel size be odd?

So there is a unique centre pixel and the output is not shifted.

How much padding does an n×n filter need?

n // 2 on each side (2 for 5×5).

Effect of zero padding vs replication?

Zero padding darkens the borders (black is averaged in). Replication keeps border brightness.

What is special about the max(|x|,|y|) kernel?

It is the chessboard distance from the centre, so the centre weight is 0 and the weights grow outwards. It smooths more and keeps less detail than a box of the same size. It must be normalised by its sum (8, 40, 112 for 3, 5, 7).

Why is the Gaussian preferred over the box?

Smooth, centre-weighted fall-off blurs edges less for the same noise reduction; it is rotationally symmetric, separable (fast) and has no ringing in frequency.

What does σ do? How do you pick the kernel size?

σ sets the spread (amount of blur). Size ≈ 6σ rounded up to odd, so the bell isn't truncated.

What is a separable filter?

A 2-D kernel that equals the outer product of two 1-D kernels. It can be applied as two 1-D passes: 2n instead of n² operations per pixel. Box and Gaussian are separable.

Mean vs median filter?

Mean is linear, good for Gaussian noise, and blurs edges. Median is non-linear, excellent for salt-and-pepper noise, and preserves edges better.

What is the convolution theorem?

Convolution in space equals multiplication in frequency: f * h ⇔ F·H.

Why does the ideal lowpass filter cause ringing?

Its sharp cut-off in frequency corresponds to a sinc (rippled) function in space. The Gaussian's transform is a Gaussian, so there are no ripples.

Assignment 7 · Highpass filtering · Edge detection

Sharpen an image: Laplacian, Sobel & Canny, unsharp masking

1. Laplacian filter.

2. Gradient operators: Sobel, and the Canny edge detector.

3. Unsharp masking. To obtain the blurred image, use a Gaussian filter of size 5×5 and σ = 3.

01Concept explanation

1.1 Sharpening is the opposite of smoothing

Smoothing (Assignment 6) averages, which is like integration, and removes rapid changes. Sharpening highlights rapid changes in intensity, i.e. edges and fine detail, which is like differentiation. In frequency terms it boosts high frequencies, so sharpening filters are highpass filters. Their kernels have positive and negative weights that sum to 0: a flat region gives 0 (no edge), and only changes give a response.

1.2 First and second derivatives of a digital image

Formula · Discrete derivatives First derivative: ∂f/∂x = f(x + 1) − f(x) Second derivative: ∂²f/∂x² = f(x + 1) + f(x − 1) − 2f(x)

Take one row crossing a ramp edge (dark → bright), e.g. 10 10 10 20 30 40 40 40:

f1010102030404040
1st derivative0010101000
2nd derivative01000−100
  • First derivative (gradient) is non-zero all along the ramp, so it gives thick edges. It measures how strong the edge is.
  • Second derivative (Laplacian) is non-zero only at the start and end of the ramp, with opposite signs (+10 then −10): a double edge with a zero crossing between. It gives thin edges and responds strongly to fine detail, but also to noise.
  • Both are 0 in flat regions.

Q1 · 1.3 The Laplacian

Formula · Laplacian and Laplacian sharpening ∇²f = ∂²f/∂x² + ∂²f/∂y² = f(x+1,y) + f(x−1,y) + f(x,y+1) + f(x,y−1) − 4f(x,y) 4-neighbour 8-neighbour (adds diagonals) 0 1 0 1 1 1 1 −4 1 1 −8 1 0 1 0 1 1 1 Sharpening: g(x, y) = f(x, y) + c · ∇²f(x, y) c = −1 (centre negative, as above) c = +1 (if using the negated kernels with +4 / +8 centre) Combined kernel for c = −1: [0 −1 0; −1 5 −1; 0 −1 0] 8-neighbour: [−1 −1 −1; −1 9 −1; −1 −1 −1]
  • Isotropic: it responds equally to edges in every direction (90° rotation invariant for the 4-neighbour kernel, 45° for the 8-neighbour one).
  • Why subtracting it sharpens: on the dark side of an edge the Laplacian is positive, so subtracting makes it darker. On the bright side it is negative, so subtracting makes it brighter. The edge gets an "overshoot" on both sides, which the eye sees as sharper.
  • Negative values: the Laplacian of cameraman ranges from −424 to +281. It must be computed in a signed float type, not uint8.

Q2 · 1.4 The gradient and the Sobel operator

Formula · Gradient ∇f = [Gx, Gy] = [∂f/∂x, ∂f/∂y] Magnitude: M(x, y) = √(Gx² + Gy²) (approximation: |Gx| + |Gy|) Direction: α(x, y) = atan2(Gy, Gx) edge is perpendicular to the gradient Sobel Gx: [−1 0 1; −2 0 2; −1 0 1] Gy: [−1 −2 −1; 0 0 0; 1 2 1]
  • Gx (horizontal change) responds to vertical edges; Gy responds to horizontal edges.
  • The 2 in the middle row/column gives a smoothing weight [1 2 1] across the derivative, so Sobel is derivative + smoothing and less sensitive to noise than a bare difference.
  • The magnitude is always ≥ 0 and is largest at edges. The largest possible |Gx| is 4 × 255 = 1020; cameraman's maximum magnitude is 930.
  • Sharpening with the gradient: adding a scaled magnitude, g = f + α·M, brightens edges. Unlike the Laplacian it does not darken the other side, because M is never negative. It is better described as edge enhancement.
OperatorGxGyNotes
Roberts (2×2)[−1 0; 0 1][0 −1; 1 0]Diagonal differences; smallest, most noise-sensitive
Prewitt (3×3)[−1 0 1; −1 0 1; −1 0 1][−1 −1 −1; 0 0 0; 1 1 1]Derivative + box smoothing
Sobel (3×3)[−1 0 1; −2 0 2; −1 0 1][−1 −2 −1; 0 0 0; 1 2 1]Derivative + weighted smoothing; most common

Q2 · 1.5 The Canny edge detector

Canny is an edge detection algorithm, not a single kernel. It produces a binary map of thin, connected edges. It was designed for three goals: low error (find real edges, ignore noise), good localisation (edges in the right place) and a single response per edge (1 pixel wide).

  1. Gaussian smoothing to reduce noise. OpenCV's cv2.Canny does not do this itself, so blur first.
  2. Gradient with Sobel: magnitude M and direction α.
  3. Non-maximum suppression (NMS): thin thick edges to 1 pixel. A pixel is kept only if its magnitude is larger than both neighbours along the gradient direction (direction rounded to 0°, 45°, 90° or 135°).
  4. Double thresholding: M ≥ high → strong edge; low ≤ M < high → weak edge; M < low → discarded.
  5. Edge tracking by hysteresis: keep weak pixels only if they are connected (8-neighbours) to a strong pixel. This joins broken edges while rejecting isolated noise.

Typical thresholds have a ratio of high:low between 2:1 and 3:1 (e.g. 50 / 150).

Q3 · 1.6 Unsharp masking and high-boost filtering

Formula · Unsharp masking 1. Blur: f̄(x, y) = Gaussian(f) (5×5, σ = 3 here) 2. Mask: g_mask(x, y) = f(x, y) − f̄(x, y) = the detail that blurring removed 3. Add back: g(x, y) = f(x, y) + k · g_mask(x, y) k = 1 : unsharp masking k > 1 : high-boost filtering 0 < k < 1 : gentle sharpening
  • The name comes from darkroom photography: a blurred ("unsharp") negative was used as a mask to sharpen prints.
  • f − blur = highpass: blur keeps low frequencies, so subtracting it leaves only the high frequencies (edges and texture). The mask is positive on the bright side of an edge and negative on the dark side, just like −∇²f. Unsharp masking and Laplacian sharpening are closely related.
  • About "5×5, σ = 3": the 6σ rule would suggest a 19×19 kernel, so a 5×5 window truncates the bell heavily. The weights only range from 0.032 (corner) to 0.050 (centre), making it almost a box filter. That is worth mentioning in the viva.
Syllabus · "Whole edges": LoG, DoG and the Hough transform

LoG (Laplacian of Gaussian, Marr–Hildreth): the Laplacian is very noise-sensitive, so first smooth with a Gaussian, then take the Laplacian (equivalently, convolve with the single kernel ∇²G, the "Mexican hat"). Edges are the zero crossings of the result, so they are thin and closed. σ sets the scale of edges detected.

DoG (Difference of Gaussians): Gσ1*f − Gσ2*f with σ2 ≈ 1.6·σ1 closely approximates LoG and is cheaper (two blurs and a subtraction). DoG is also the core of SIFT's keypoint detector (syllabus: whole-image features).

a7_log_dog.py
# LoG (Marr-Hildreth) and DoG edge detection
import cv2
import numpy as np

img = cv2.imread("cameraman.png", 0).astype(np.float64)

# ---- LoG: Gaussian smoothing, then Laplacian ----
smooth = cv2.GaussianBlur(img, (0, 0), 2)              # sigma = 2, size chosen from sigma
log = cv2.Laplacian(smooth, cv2.CV_64F, ksize=3)

# Edges = zero crossings: neighbouring LoG values with opposite signs
# and a big enough jump between them (threshold removes weak, noisy crossings)
sign = np.sign(log)
edges = np.zeros(img.shape, np.uint8)
horiz = (sign[:, 1:] * sign[:, :-1] < 0) & (np.abs(log[:, 1:] - log[:, :-1]) > 4)
vert = (sign[1:, :] * sign[:-1, :] < 0) & (np.abs(log[1:, :] - log[:-1, :]) > 4)
edges[:, 1:][horiz] = 255
edges[1:, :][vert] = 255

# ---- DoG: difference of two Gaussians (approximates LoG; sigma ratio ~1.6) ----
dog = cv2.GaussianBlur(img, (0, 0), 1) - cv2.GaussianBlur(img, (0, 0), 1.6)

cv2.imwrite("a7_log.png", np.uint8(np.clip(128 + 8 * log, 0, 255)))   # 0 -> mid-grey
cv2.imwrite("a7_log_zc.png", edges)
cv2.imwrite("a7_dog.png", np.uint8(np.clip(128 + 6 * dog, 0, 255)))
LoG response (σ = 2), grey = 0
LoG response (σ = 2), grey = 0
LoG zero crossings = edges (thin, closed contours)
LoG zero crossings = edges (thin, closed contours)
DoG (σ = 1 and 1.6): nearly the same as LoG
DoG (σ = 1 and 1.6): nearly the same as LoG

Hough transform (concept): it finds straight lines (or circles) from an edge map. Each edge pixel (x, y) "votes" for every line through it, written as ρ = x·cosθ + y·sinθ. Votes are counted in a (ρ, θ) accumulator, and peaks correspond to lines supported by many edge pixels. It works even when the edges are broken. In OpenCV: cv2.HoughLines / cv2.HoughLinesP on a Canny output.

Frequency-domain highpass: any lowpass filter gives a highpass one as HHP = 1 − HLP (ideal, Butterworth, Gaussian). The Laplacian also has a frequency form, H = −4π²(u² + v²).

a7_freq_hpf.py
# Gaussian highpass filter in the frequency domain:  H_HP = 1 - H_LP
import cv2
import numpy as np

img = cv2.imread("cameraman.png", 0).astype(np.float64)
M, N = img.shape
F = np.fft.fftshift(np.fft.fft2(img))
V, U = np.meshgrid(np.arange(N) - N // 2, np.arange(M) - M // 2)
D = np.sqrt(U ** 2 + V ** 2)
H_hp = 1 - np.exp(-D ** 2 / (2 * 30 ** 2))          # D0 = 30

g = np.real(np.fft.ifft2(np.fft.ifftshift(F * H_hp)))   # mean ~0: only edges and detail
cv2.imwrite("a7_gauss_hpf.png", np.uint8(np.clip(128 + g, 0, 255)))
Gaussian highpass (D0 = 30): only edges and texture remain (grey = 0)
Gaussian highpass (D0 = 30): only edges and texture remain (grey = 0)

1.7 Comparing the sharpening methods

LaplacianSobel gradientCannyUnsharp masking
Derivative2nd1st1st + NMS + hysteresisimplicit (f − blur)
Outputsigned detail map → added to fmagnitude (≥ 0) → edge mapbinary, 1-pixel edgessharpened image
DirectionisotropicGx, Gy separate; direction availableuses direction for thinningisotropic (Gaussian)
Edge widththin, double edgethickthinnest—
Noise sensitivityvery highmoderate (built-in smoothing)low (Gaussian + hysteresis)moderate; amplified for large k
Parameterskernel (4 or 8)ksize, αlow, high thresholdsblur size, σ, k
Main usesharpening fine detailedge strength, feature extractionclean edge maps for segmentationphoto sharpening (used in printing and photo editors)

02Solution

Q1 · Laplacian sharpening

a7q1_laplacian.py
# Assignment 7, Q1: Sharpening with the Laplacian
#   Laplacian (4-neighbour):  d2f = f(x+1,y) + f(x-1,y) + f(x,y+1) + f(x,y-1) - 4 f(x,y)
#   Sharpened image:          g = f + c * d2f,   c = -1 because the centre weight is negative
import cv2
import numpy as np

IMG_PATH = "cameraman.png"

img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")
f = img.astype(np.float64)          # float: the Laplacian has NEGATIVE values

k4 = np.array([[0, 1, 0],
               [1, -4, 1],
               [0, 1, 0]], dtype=np.float64)       # 4-neighbour Laplacian
k8 = np.array([[1, 1, 1],
               [1, -8, 1],
               [1, 1, 1]], dtype=np.float64)       # 8-neighbour (adds diagonals)

lap4 = cv2.filter2D(f, -1, k4)      # ddepth -1: output has the input's type (float64)
lap8 = cv2.filter2D(f, -1, k8)

c = -1                              # centre coefficient is negative -> subtract
sharp4 = np.uint8(np.clip(f + c * lap4, 0, 255))
sharp8 = np.uint8(np.clip(f + c * lap8, 0, 255))

# Built-in check: cv2.Laplacian with ksize=1 uses the same 4-neighbour kernel
lap_cv = cv2.Laplacian(f, cv2.CV_64F, ksize=1)
print("filter2D == cv2.Laplacian:", np.allclose(lap4, lap_cv))
print("Laplacian range:", round(lap4.min(), 1), "to", round(lap4.max(), 1))

# To DISPLAY the Laplacian itself, shift and scale it into 0-255 (0 becomes mid-grey)
lap_disp = np.uint8(np.clip(lap4 * 2 + 128, 0, 255))

cv2.imshow("Original", img)
cv2.imshow("Laplacian (scaled)", lap_disp)
cv2.imshow("Sharpened (4-neighbour)", sharp4)
cv2.imshow("Sharpened (8-neighbour)", sharp8)
cv2.imwrite("a7_lap_disp.png", lap_disp)
cv2.imwrite("a7_sharp4.png", sharp4)
cv2.imwrite("a7_sharp8.png", sharp8)
cv2.waitKey(0)
cv2.destroyAllWindows()
filter2D == cv2.Laplacian: True
Laplacian range: -424.0 to 281.0

Q2 · Sobel gradient and Canny

a7q2_sobel_canny.py
# Assignment 7, Q2: Gradient (Sobel) sharpening and Canny edge detection
#   Gradient magnitude  M = sqrt(Gx^2 + Gy^2)
#   Gradient sharpening g = f + alpha * M     (brightens edges)
import cv2
import numpy as np

IMG_PATH = "cameraman.png"

img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")
f = img.astype(np.float64)

# ---------------- Sobel gradients ----------------
# Gx kernel: [-1 0 1; -2 0 2; -1 0 1]   (responds to vertical edges)
# Gy kernel: [-1 -2 -1; 0 0 0; 1 2 1]   (responds to horizontal edges)
gx = cv2.Sobel(f, cv2.CV_64F, 1, 0, ksize=3)     # dx = 1, dy = 0
gy = cv2.Sobel(f, cv2.CV_64F, 0, 1, ksize=3)     # dx = 0, dy = 1
mag = np.sqrt(gx ** 2 + gy ** 2)                 # gradient magnitude (>= 0)
print("Gradient magnitude range: 0 to", round(mag.max(), 1))

mag_disp = np.uint8(np.round(255 * mag / mag.max()))          # scaled for display
gx_disp = np.uint8(np.clip(np.abs(gx) / 4, 0, 255))           # |Gx|, divided by 4 (max kernel gain)
gy_disp = np.uint8(np.clip(np.abs(gy) / 4, 0, 255))

alpha = 0.5
sharp_sobel = np.uint8(np.clip(f + alpha * mag_disp, 0, 255))

# ---------------- Canny edge detector ----------------
low = int(input("Canny lower threshold (e.g. 50): "))
high = int(input("Canny upper threshold (e.g. 150): "))
blurred = cv2.GaussianBlur(img, (5, 5), 1.4)     # step 1: smooth (OpenCV's Canny does not)
edges = cv2.Canny(blurred, low, high)            # steps 2-5 inside: gradient, NMS, hysteresis
print("Edge pixels:", np.count_nonzero(edges), f"({100 * np.count_nonzero(edges) / edges.size:.1f}%)")

# Show the thin Canny edges on top of the image in red
overlay = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
overlay[edges > 0] = (0, 0, 255)

cv2.imshow("|Gx|", gx_disp)
cv2.imshow("|Gy|", gy_disp)
cv2.imshow("Sobel magnitude", mag_disp)
cv2.imshow("Sobel-sharpened", sharp_sobel)
cv2.imshow("Canny edges", edges)
cv2.imshow("Canny overlay", overlay)
for name, im in [("gx", gx_disp), ("gy", gy_disp), ("mag", mag_disp),
                 ("sharp_sobel", sharp_sobel), ("canny", edges), ("canny_overlay", overlay)]:
    cv2.imwrite(f"a7_{name}.png", im)
cv2.waitKey(0)
cv2.destroyAllWindows()
Gradient magnitude range: 0 to 930.1
Canny lower threshold (e.g. 50): 50
Canny upper threshold (e.g. 150): 150
Edge pixels: 7517 (2.9%)

Q3 · Unsharp masking

a7q3_unsharp.py
# Assignment 7, Q3: Unsharp masking (and high-boost filtering)
#   blurred = Gaussian(f), 5x5, sigma = 3
#   mask    = f - blurred           (the detail that blurring removed)
#   g       = f + k * mask          k = 1: unsharp masking,  k > 1: high-boost
import cv2
import numpy as np

IMG_PATH = "cameraman.png"

img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")
f = img.astype(np.float64)

k = float(input("Weight k (1 = unsharp masking, >1 = high-boost) [default 1]: ") or 1)

blurred = cv2.GaussianBlur(f, (5, 5), 3)        # kernel size (5, 5), sigmaX = 3
mask = f - blurred                              # positive on the bright side of an edge,
                                                # negative on the dark side
g = f + k * mask
out = np.uint8(np.clip(g, 0, 255))

print("Mask range:", round(mask.min(), 1), "to", round(mask.max(), 1))
print("Std (contrast) before:", round(img.std(), 1), "| after:", round(out.std(), 1))

mask_disp = np.uint8(np.clip(mask * 4 + 128, 0, 255))      # 0 -> mid-grey, amplified to be visible

cv2.imshow("Original", img)
cv2.imshow("Blurred (5x5, sigma 3)", np.uint8(blurred))
cv2.imshow("Mask (scaled)", mask_disp)
cv2.imshow(f"Sharpened, k = {k}", out)
cv2.imwrite("a7_blurred.png", np.uint8(np.round(blurred)))
cv2.imwrite("a7_mask.png", mask_disp)
cv2.imwrite("a7_unsharp.png", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
Weight k (1 = unsharp masking, >1 = high-boost) [default 1]: 1
Mask range: -99.1 to 128.5
Std (contrast) before: 73.6 | after: 76.4

03Output images

Q1 · Laplacian

Input
Input
Laplacian (×2 + 128; grey = 0)
Laplacian (×2 + 128; grey = 0)
Sharpened, 4-neighbour
Sharpened, 4-neighbour
Sharpened, 8-neighbour
Sharpened, 8-neighbour

Zoomed in (2.5×) on the face and camera:

Original
Original
Laplacian: bright/dark pairs along every edge
Laplacian: bright/dark pairs along every edge
4-neighbour sharpened
4-neighbour sharpened
8-neighbour sharpened: stronger
8-neighbour sharpened: stronger

Laplacian image: flat areas (sky, coat) are mid-grey, meaning 0. Every edge shows as a pair of a bright and a dark line, the double response of the second derivative. Fine texture (hair, grass) also lights up.

Sharpened: subtracting the Laplacian adds that pair to the image, so each edge gets a dark undershoot and a bright overshoot. Hair strands, the camera's outline and the grass become crisper. The 8-neighbour kernel includes diagonals and has a larger centre weight (−8), so its response is stronger: sharper, but noisier and harsher. Smooth regions are unchanged, because the Laplacian is 0 there.

Q2 · Sobel gradient

|Gx|: vertical edges (tripod legs, building sides)
|Gx|: vertical edges (tripod legs, building sides)
|Gy|: horizontal edges (horizon, shoulders)
|Gy|: horizontal edges (horizon, shoulders)
Magnitude √(Gx² + Gy²), scaled
Magnitude √(Gx² + Gy²), scaled
Sobel-sharpened f + 0.5·M
Sobel-sharpened f + 0.5·M

|Gx| lights up vertical structures and |Gy| horizontal ones. Each misses the edges the other finds, and the magnitude combines both. Edges in the magnitude are thick (several pixels), because the first derivative is non-zero along the whole ramp. Adding half the magnitude to the image brightens outlines (the coat edge, tripod and camera get a light rim). It does not create a dark side, so the effect is "edge glow" rather than true crispening.

Q2 · Canny (low 50, high 150)

Canny edges: binary, 1 pixel wide, 2.9% of pixels
Canny edges: binary, 1 pixel wide, 2.9% of pixels
Overlay: edges in red on the image
Overlay: edges in red on the image

Compared with the Sobel magnitude, the Canny edges are thin (non-maximum suppression), connected (hysteresis) and clean. Most grass texture is rejected, because its gradient mostly falls below the low threshold or is not connected to a strong edge. The main outlines (man, camera, tripod, buildings) are traced as continuous curves.

Q3 · Unsharp masking (5×5, σ = 3, k = 1)

Original f
Original f
Blurred f̄
Blurred f̄
Mask f − f̄ (×4 + 128)
Mask f − f̄ (×4 + 128)
Result f + 1·mask
Result f + 1·mask
Original (zoom)
Original (zoom)
k = 1, unsharp masking
k = 1, unsharp masking
k = 3, high-boost
k = 3, high-boost

The mask looks like a highpass image: grey (0) in flat areas, light and dark rims along edges. It ranges from −99 to +128, so a lot of detail was lost by blurring. Adding it back with k = 1 crisps the edges (eye, ear, camera body) without the harsh, noisy look of the 8-neighbour Laplacian. Contrast (std) rises from 73.6 to 76.4. With k = 3 the edges become much more pronounced. That is high-boost filtering, and light halos start to appear around dark objects.

Say this when you show the output

"Sharpening highlights intensity changes using derivatives. The Laplacian is a second derivative. It gives a bright-dark pair at each edge, and subtracting it from the image adds overshoot on both sides, so edges look crisper. Sobel computes the first-derivative gradient in x and y. The magnitude shows edge strength but gives thick edges. Canny thins those edges with non-maximum suppression and uses two thresholds with hysteresis to keep only connected real edges. Unsharp masking subtracts a Gaussian-blurred copy to get the detail, then adds it back; with k greater than 1 it becomes high-boost."

04Code walkthrough

Q1 · Laplacian

f = img.astype(np.float64)

Converts to float before filtering. The Laplacian has negative values (down to −424 here) and values above 255. In uint8 these are clipped to 0–255 and half the edge information is lost (Part 5).

k4 = np.array([[0, 1, 0],
               [1, -4, 1],
               [0, 1, 0]], dtype=np.float64)
lap4 = cv2.filter2D(f, -1, k4)

Writes the kernel explicitly, which is easy to explain, and applies it with filter2D. Because the input is float64, ddepth=-1 keeps the output float64 with its negative values. The weights sum to 0, so flat regions give 0.

c = -1
sharp4 = np.uint8(np.clip(f + c * lap4, 0, 255))

g = f − ∇²f. The sign c = −1 matches the negative centre of the kernel. The result can exceed 0–255 at strong edges, so it is clipped before converting to uint8. Plain astype(np.uint8) without clipping would wrap (e.g. 300 → 44, −20 → 236), giving speckled artefacts.

lap_cv = cv2.Laplacian(f, cv2.CV_64F, ksize=1)
lap_disp = np.uint8(np.clip(lap4 * 2 + 128, 0, 255))

The built-in check gives identical values. To display a signed image, shift it so 0 becomes mid-grey (+128) and scale it to make it visible (×2).

cv2.Laplacian(src, ddepth, ksize=1, scale=1, delta=0, borderType=...) → dst

ddepth: use cv2.CV_64F (or CV_16S) to keep negatives. ksize: 1 → the 3×3 kernel [0 1 0; 1 −4 1; 0 1 0]; 3, 5, 7 → larger Sobel-based second-derivative kernels (smoother, stronger). scale/delta: multiply/add to the result.

Q2 · Sobel and Canny

gx = cv2.Sobel(f, cv2.CV_64F, 1, 0, ksize=3)
gy = cv2.Sobel(f, cv2.CV_64F, 0, 1, ksize=3)
mag = np.sqrt(gx ** 2 + gy ** 2)

Derivative in x (dx = 1, dy = 0) and in y (dx = 0, dy = 1), in float64 because derivatives are signed. The magnitude combines them (Pythagoras). cv2.magnitude(gx, gy) does the same thing.

cv2.Sobel(src, ddepth, dx, dy, ksize=3, scale=1, delta=0, borderType=...) → dst

ddepth: CV_64F / CV_32F / CV_16S. With CV_8U, negative gradients become 0, so you lose every dark-to-bright edge in one direction. dx, dy: order of the derivative in x and y (1, 0 or 0, 1; 1, 1 for mixed). ksize: 1, 3, 5 or 7 (3 = the standard Sobel kernels; −1 = Scharr, a more accurate 3×3).

mag_disp = np.uint8(np.round(255 * mag / mag.max()))
gx_disp = np.uint8(np.clip(np.abs(gx) / 4, 0, 255))

Display scaling. The magnitude is divided by its maximum (930) so the strongest edge is 255. |Gx| is divided by 4, the kernel's maximum gain (1+2+1), so it fits 0–255.

sharp_sobel = np.uint8(np.clip(f + alpha * mag_disp, 0, 255))

Gradient-based enhancement: add a fraction (α = 0.5) of the edge-strength map to the original, so edges brighten. Larger α gives stronger outlines but a washed-out look.

blurred = cv2.GaussianBlur(img, (5, 5), 1.4)
edges = cv2.Canny(blurred, low, high)

Step 1 (smoothing) is done by us, because OpenCV's Canny starts directly with the Sobel gradient. 5×5 with σ = 1.4 is the classic choice. cv2.Canny then does gradient → non-maximum suppression → double threshold → hysteresis and returns a binary uint8 image (0 / 255).

cv2.Canny(image, threshold1, threshold2, apertureSize=3, L2gradient=False) → edges

image: 8-bit. threshold1 = low, threshold2 = high (order doesn't matter; OpenCV uses the smaller as low). Typical ratio 1:2 to 1:3, e.g. 50/150 or 100/200. apertureSize: Sobel kernel size (3, 5, 7). L2gradient: True = use √(Gx²+Gy²), more accurate; False = |Gx|+|Gy|, faster.

overlay = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
overlay[edges > 0] = (0, 0, 255)

Converts to 3 channels (Assignment 3) and paints every edge pixel red (BGR = 0, 0, 255) using a boolean mask. This shows where the edges sit on the original.

Q3 · Unsharp masking

k = float(input("...") or 1)

If the user just presses Enter, input() returns an empty string, which is "falsy", so or 1 supplies the default k = 1.

blurred = cv2.GaussianBlur(f, (5, 5), 3)
mask = f - blurred
g = f + k * mask
out = np.uint8(np.clip(g, 0, 255))

The three steps from the formula, exactly as specified (5×5, σ = 3). Everything is float so the mask keeps its negative values. Clipping handles overshoot at strong edges.

Common mistakes
  • Using cv2.CV_8U in Laplacian/Sobel: negative responses are clipped to 0 and half the edges vanish.
  • Adding instead of subtracting the Laplacian for a negative-centre kernel: this blurs instead of sharpening (Part 5).
  • astype(np.uint8) without np.clip: values wrap around and produce salt-and-pepper-like speckles at edges.
  • Running Canny without blurring: noise and texture create many false edges.
  • Calling Canny "sharpening": it outputs a binary edge map, not an enhanced image. Present it as edge detection used to locate and emphasise edges.
  • Computing the unsharp mask in uint8: img - blurred wraps negative values to large positives.

05"What if" questions

What if we add the Laplacian instead of subtracting it (wrong sign)?
Correct: f − ∇²f
Correct: f − ∇²f
Wrong sign: f + ∇²f, softer and blurred
Wrong sign: f + ∇²f, softer and blurred

Adding the Laplacian of a negative-centre kernel reduces the difference across each edge: the dark side gets brighter and the bright side darker. The image looks smoother and duller. The sign c must match the sign of the kernel's centre (c = −1 for −4/−8 centres, c = +1 for +4/+8).

What if we compute the Laplacian with output type cv2.CV_8U?
Float Laplacian (signed, displayed with offset)
Float Laplacian (signed, displayed with offset)
cv2.Laplacian(img, cv2.CV_8U): negatives clipped to 0
cv2.Laplacian(img, cv2.CV_8U): negatives clipped to 0

All negative responses become 0, so only one side of each edge survives, and it looks almost black. Sharpening with this incomplete Laplacian gives wrong results. Always use CV_64F (or CV_16S) and clip only at the end.

What if the image is noisy before sharpening?
Noisy input (σ = 20)
Noisy input (σ = 20)
Laplacian-sharpened: noise greatly amplified
Laplacian-sharpened: noise greatly amplified

Noise is high-frequency, so a second-derivative filter boosts it as strongly as real detail. The usual fix is to smooth first, then sharpen (LoG), or use unsharp masking, whose built-in blur limits noise. Order matters: sharpen-then-smooth would undo the sharpening.

What if we change the Canny thresholds?
Low 20 / high 60: many edges, including grass texture
Low 20 / high 60: many edges, including grass texture
50 / 150 (used)
50 / 150 (used)
100 / 250: only the strongest outlines; some gaps
100 / 250: only the strongest outlines; some gaps

Lower thresholds accept weaker gradients, giving more detail but also more noise and texture. Higher ones keep only strong edges, so outlines may break. The high threshold decides where edges start; the low threshold decides how far they can be extended through weaker pixels (hysteresis).

What if we skip the Gaussian blur before Canny?
With 5×5 blur, σ = 1.4
With 5×5 blur, σ = 1.4
No blur: grass and noise produce many false edges
No blur: grass and noise produce many false edges

Without smoothing, small intensity fluctuations produce gradient peaks above the threshold. The grass turns into a mesh of tiny edges. More blur (larger σ) gives cleaner but less precisely placed edges.

What if k is large in unsharp masking (high-boost k = 6)?
k = 1
k = 1
k = 3
k = 3
k = 6: halos, noise, clipping
k = 6: halos, noise, clipping

Larger k exaggerates the overshoot: bright halos around dark objects, dark halos around bright ones, grainy texture, and clipping at 0/255. Values of k between 0.5 and 2 are typical. Extreme k is used only when the whole image is too dark or blurry and needs strong boosting.

What if we use a larger blur (e.g. 19×19 with σ = 3) for unsharp masking?

The mask then contains a wider band of frequencies (medium-scale detail as well as fine edges), so sharpening affects larger structures and halos get wider. With the specified 5×5 window the σ = 3 Gaussian is truncated to an almost flat kernel, so the mask holds mainly fine detail. The size of the blur controls the scale of detail that gets sharpened.

What if we use |Gx| + |Gy| instead of √(Gx² + Gy²)?

It is a cheaper approximation that avoids squares and a square root. It slightly overestimates diagonal edges (by up to √2) and is not perfectly isotropic, but the edge maps look almost the same. Canny's L2gradient=False default uses this L1 version.

What if we apply sharpening to a colour image?

Filtering B, G and R separately works (the same kernel keeps colours balanced), but it amplifies colour noise. Better: convert to YCrCb or HSV, sharpen only Y or V, and convert back. Canny needs a single-channel image (convert to grayscale first).

What if we use the Laplacian kernel with ksize = 3 or 5 in cv2.Laplacian?

Larger apertures use Sobel-based second derivatives over a bigger window. The response is stronger and somewhat smoother (less sensitive to single-pixel noise) but less precise for fine detail. ksize = 1 is the classic 3×3 Laplacian from the textbook.

06Viva / evaluation angle

30-second explanation

"Sharpening uses derivatives to highlight edges. For the Laplacian, I convert to float, convolve with [0 1 0; 1 −4 1; 0 1 0] and subtract the result from the image, which adds overshoot on both sides of each edge. I clip and convert back. For Sobel, I compute Gx and Gy in float, take the magnitude, and add half of it to brighten edges. For Canny, I blur with a 5×5 Gaussian and call cv2.Canny with the user's two thresholds, which gives thin, connected binary edges. For unsharp masking, I blur with a 5×5, σ = 3 Gaussian, subtract to get the mask, and add k times the mask back."

Why do sharpening kernels sum to zero?

So flat regions give 0 and only intensity changes (edges) produce a response.

First vs second derivative for edges?

First: thick edges and edge strength (gradient). Second: thin double edges with a zero crossing; better for fine detail but more noise-sensitive.

Write the Laplacian kernel. Why subtract it?

[0 1 0; 1 −4 1; 0 1 0]. The centre is negative, so g = f − ∇²f darkens the dark side and brightens the bright side of each edge.

4-neighbour vs 8-neighbour Laplacian?

The 8-neighbour version includes diagonals (centre −8): stronger sharpening, isotropic in 45° steps, and more noise.

Why use float (CV_64F) for derivatives?

Derivatives are signed and can exceed 255. uint8 clips the negatives and loses half the edges.

Write the Sobel kernels. Which edges does each detect?

Gx = [−1 0 1; −2 0 2; −1 0 1] detects vertical edges. Gy = [−1 −2 −1; 0 0 0; 1 2 1] detects horizontal edges.

Why does Sobel have 2 in the middle?

It weights the centre row/column for smoothing, making Sobel less noise-sensitive than Prewitt.

Gradient magnitude and direction formulas?

M = √(Gx² + Gy²) (or |Gx| + |Gy|); α = atan2(Gy, Gx). The edge is perpendicular to α.

Steps of the Canny edge detector?

Gaussian smoothing → Sobel gradient (magnitude, direction) → non-maximum suppression → double threshold → hysteresis edge tracking.

What is non-maximum suppression?

Keeping a pixel only if its gradient magnitude is a local maximum along the gradient direction, which thins edges to 1 pixel.

What is hysteresis thresholding?

Strong pixels (≥ high) are edges. Weak pixels (between low and high) are kept only if connected to a strong pixel. This joins edges and rejects isolated noise.

What is unsharp masking? High-boost?

g = f + k(f − blur(f)). k = 1 is unsharp masking; k > 1 is high-boost filtering.

Is a 5×5 window enough for σ = 3?

No. The 6σ rule suggests about 19×19. At 5×5 the Gaussian is truncated to a nearly flat (box-like) kernel, with weights from 0.032 to 0.050.

What is LoG? DoG?

LoG: Gaussian smoothing followed by the Laplacian; edges are the zero crossings (Marr–Hildreth). DoG: difference of two Gaussian blurs (σ ratio ≈ 1.6), a cheap approximation of LoG.

How does unsharp masking relate to highpass filtering?

f − lowpass(f) = highpass(f). The mask is the highpass part, and adding it back boosts high frequencies.

Assignment 8 · Image restoration · Noise models

Generate noise from probability density functions

Generate the following noises using equations derived from the PDFs of the noise distributions. Compare your output with noise generated by the built-in function imnoise. Plot histograms of the generated noise to see the shape of each distribution.

1. Uniform · 2. Gaussian · 3. Erlang · 4. Exponential · 5. Rayleigh

01Concept explanation

1.1 Where noise fits: the degradation model

Image restoration tries to recover the original image f from a degraded observation g, using knowledge of how it was degraded. This differs from enhancement (A4–A7), which only tries to make the image look better.

Formula · Degradation model Spatial: g(x, y) = h(x, y) * f(x, y) + η(x, y) * = convolution Frequency: G(u, v) = H(u, v) · F(u, v) + N(u, v) h / H = degradation function (blur from motion, defocus, atmosphere) η / N = additive noise Noise only (h = identity): g(x, y) = f(x, y) + η(x, y) ← this assignment

To remove noise well, you first need a model of it. Noise is random, so it is described by the probability density function (PDF) of its values. This assignment generates each of the textbook noise PDFs and checks their shapes with histograms.

Assumptions in these models: the noise is independent of the image content and of position (spatially uncorrelated). Speckle noise (Assignment 9) breaks the first assumption, because it is multiplicative.

1.2 The five noise PDFs

NoisePDF p(z)MeanVarianceWhere it occurs
Uniform1/(b − a) for a ≤ z ≤ b, else 0(a + b)/2(b − a)²/12Quantization error; used as the basis for generating other noises
Gaussian(1/√(2π)σ) · e−(z − z̄)²/2σ²z̄σ²Sensor/electronic circuit noise, poor lighting, high temperature
Erlang (Gamma)ab zb−1 e−az / (b − 1)! for z ≥ 0b/ab/a²Laser imaging
Exponentiala · e−az for z ≥ 01/a1/a²Laser imaging; Erlang with b = 1
Rayleigh(2/b)(z − a) e−(z − a)²/b for z ≥ aa + √(πb/4)b(4 − π)/4Range imaging (radar); a skewed distribution

Shapes to remember: uniform is a flat box; Gaussian is a symmetric bell; exponential starts at its maximum at z = 0 and decays; Erlang and Rayleigh start at 0, rise to a peak and have a long right tail (skewed). Only uniform and Gaussian can be zero-mean. The other three are always positive, so they also brighten the image on average.

Other noise types in the restoration unit
  • Impulse (salt-and-pepper): a random fraction of pixels is set to 0 (pepper) or 255 (salt). Its PDF has two spikes. Caused by faulty sensor elements or transmission errors. Removed with median filters (Assignment 10).
  • Periodic noise: sinusoidal interference from electrical sources. It appears as bright spikes in the Fourier spectrum and is removed in the frequency domain with notch/band-reject filters.
  • Speckle (multiplicative): g = f + f·n, in ultrasound and radar (Assignment 9).

Estimating the noise from a real image: take a flat region (constant intensity), look at its histogram, recognise the shape, and estimate the mean and variance from it. That is exactly why this assignment uses a flat test pattern.

1.3 Generating noise from its PDF: three methods

A computer's basic random generator gives uniform numbers U in (0, 1). Every other distribution is made by transforming U. That is what "equations derived from the PDFs" means.

(a) Inverse-CDF (inverse transform) method. If F(z) is the CDF of the noise, then z = F⁻¹(U) has exactly that distribution. Derivation for each:

Derivations · inverse CDF Uniform: F(z) = (z − a)/(b − a) → z = a + (b − a) · U Exponential: F(z) = 1 − e^(−az) → U = 1 − e^(−az) z = −(1/a) · ln(1 − U) Rayleigh: F(z) = 1 − e^(−(z − a)²/b) → (z − a)² = −b · ln(1 − U) z = a + √( −b · ln(1 − U) )

(b) Box–Muller transform (Gaussian). The Gaussian CDF has no closed-form inverse, so a different trick is used. Two independent uniforms U1 and U2 give a standard normal Z ~ N(0, 1):

Z = √(−2 ln U1) · cos(2π U2) then z = z̄ + σ · Z

(c) Sum of exponentials (Erlang). An Erlang(a, b) variable is the sum of b independent Exponential(a) variables. This is why b must be a positive integer, and why Erlang with b = 1 is exactly exponential:

z = Σ_{i=1..b} −(1/a) · ln(1 − U_i)

1.4 Step by step

  1. Read a test image with a few flat grey levels (here 40, 120 and 200).
  2. For each noise type, generate an array of noise values the size of the image, using the formula from U(0, 1).
  3. Generate the same noise with the built-in generator.
  4. Compare the mean and variance with the theory, and plot both histograms against the theoretical PDF.
  5. Add the noise to the image (g = f + η), clip to 0–255, and look at the image and its histogram.
"imnoise" in Python

imnoise is a MATLAB function. Python's closest equivalent is skimage.util.random_noise, which supports Gaussian, salt-and-pepper, speckle, Poisson and local-variance noise only. For uniform, Erlang, exponential and Rayleigh the built-in comparison is NumPy's generators: rng.uniform, rng.normal, rng.gamma, rng.exponential, rng.rayleigh. Mention this if the examiner says "imnoise".

02Solution

a8_noise.py
# Assignment 8: Generate noise from the equations of each PDF, compare with
# built-in generators, and plot histograms to see the shape of each distribution.
#   Every "formula" generator starts from uniform random numbers U ~ U(0, 1) and
#   transforms them (inverse-CDF method, Box-Muller, or sums).
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage.util import random_noise

IMG_PATH = "test_pattern.png"        # 3 flat grey levels: noise shape is easy to see
img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")
shape = img.shape
rng = np.random.default_rng(0)       # seeded so results are repeatable

# ---------------- Parameters (Gonzalez & Woods notation) ----------------
UA, UB = -40, 40                     # Uniform:     a <= z <= b
MEAN, SIGMA = 0, 20                  # Gaussian:    mean, standard deviation
EA, EB = 0.1, 3                      # Erlang:      a > 0, b = positive integer
XA = 0.05                            # Exponential: a > 0
RA, RB = 0, 400                      # Rayleigh:    a, b > 0


# ---------------- 1. Noise from the equations ----------------
def uniform(a, b):
    U = rng.random(shape)                        # U(0, 1)
    return a + (b - a) * U                       # stretch to [a, b]


def gaussian(mean, sigma):
    U1, U2 = rng.random(shape), rng.random(shape)
    U1 = np.maximum(U1, 1e-12)                   # avoid log(0)
    Z = np.sqrt(-2 * np.log(U1)) * np.cos(2 * np.pi * U2)   # Box-Muller -> N(0, 1)
    return mean + sigma * Z


def exponential(a):
    U = rng.random(shape)
    return -np.log(1 - U) / a                    # inverse of CDF F(z) = 1 - e^(-az)


def erlang(a, b):
    # Erlang(a, b) = sum of b independent Exponential(a) variables
    return sum(exponential(a) for _ in range(b))


def rayleigh(a, b):
    U = rng.random(shape)
    return a + np.sqrt(-b * np.log(1 - U))       # inverse of F(z) = 1 - e^(-(z-a)^2 / b)


mine = {
    "Uniform": uniform(UA, UB),
    "Gaussian": gaussian(MEAN, SIGMA),
    "Erlang": erlang(EA, EB),
    "Exponential": exponential(XA),
    "Rayleigh": rayleigh(RA, RB),
}

# ---------------- 2. Built-in generators for comparison ----------------
# (MATLAB's imnoise covers only some types; NumPy has a generator for each.)
builtin = {
    "Uniform": rng.uniform(UA, UB, shape),
    "Gaussian": rng.normal(MEAN, SIGMA, shape),
    "Erlang": rng.gamma(shape=EB, scale=1 / EA, size=shape),        # Erlang = gamma, integer shape
    "Exponential": rng.exponential(scale=1 / XA, size=shape),
    "Rayleigh": RA + rng.rayleigh(scale=np.sqrt(RB / 2), size=shape),  # numpy sigma^2 = b / 2
}
# skimage.util.random_noise is the closest Python equivalent of imnoise (Gaussian here)
sk = random_noise(img, mode="gaussian", mean=0, var=(SIGMA / 255) ** 2, rng=0)
sk_noise = sk * 255 - img                        # its noise only (clipped at 0 and 1)

# Theoretical mean and variance of each PDF
theory = {
    "Uniform": ((UA + UB) / 2, (UB - UA) ** 2 / 12),
    "Gaussian": (MEAN, SIGMA ** 2),
    "Erlang": (EB / EA, EB / EA ** 2),
    "Exponential": (1 / XA, 1 / XA ** 2),
    "Rayleigh": (RA + np.sqrt(np.pi * RB / 4), RB * (4 - np.pi) / 4),
}

print(f"{'Noise':12s} {'theory mean/var':>20s} {'formula mean/var':>20s} {'built-in mean/var':>20s}")
for name in mine:
    m, b = mine[name], builtin[name]
    tm, tv = theory[name]
    print(f"{name:12s} {tm:8.2f} / {tv:8.1f}   {m.mean():8.2f} / {m.var():8.1f}   {b.mean():8.2f} / {b.var():8.1f}")
print(f"skimage Gaussian noise: mean {sk_noise.mean():.2f}, var {sk_noise.var():.1f}")

# ---------------- 3. Add noise to the image and plot histograms ----------------
fig, ax = plt.subplots(2, 5, figsize=(20, 7))
for k, name in enumerate(mine):
    noisy = np.uint8(np.clip(img + mine[name], 0, 255))     # additive noise, clipped
    cv2.imwrite(f"a8_{name.lower()}.png", noisy)
    ax[0, k].hist(mine[name].ravel(), 200, density=True, alpha=0.6, label="formula")
    ax[0, k].hist(builtin[name].ravel(), 200, density=True, histtype="step", label="built-in")
    ax[0, k].set_title(f"{name} noise")
    ax[0, k].legend()
    ax[1, k].hist(noisy.ravel(), 256, range=(0, 256))
    ax[1, k].set_title(f"Noisy image histogram ({name})")
plt.tight_layout()
plt.show()

Console output:

Noise             theory mean/var     formula mean/var    built-in mean/var
Uniform          0.00 /    533.3      -0.02 /    532.8      -0.01 /    533.5
Gaussian         0.00 /    400.0       0.02 /    399.7      -0.04 /    399.2
Erlang          30.00 /    300.0      30.01 /    299.9      29.98 /    300.2
Exponential     20.00 /    400.0      19.96 /    397.2      19.91 /    397.7
Rayleigh        17.72 /     85.8      17.74 /     86.2      17.77 /     86.5
skimage Gaussian noise: mean 0.12, var 389.9

All five formula generators match the theoretical mean and variance (and the built-in generators) to within about 1%, using 262,144 samples each. The skimage Gaussian has slightly lower variance (389.9) because it clips the noisy image to [0, 1], which cuts off part of the noise at the dark and bright levels.

Parameter choices

The parameters were chosen to give noise of similar strength (standard deviation about 9–23 grey levels), so the histograms are comparable: uniform a = −40, b = 40; Gaussian σ = 20; Erlang a = 0.1, b = 3; exponential a = 0.05; Rayleigh a = 0, b = 400. In the exam you may be asked to enter them with input(). The functions already take them as arguments.

03Output images

Noise histograms: formula vs built-in vs theory

Blue = noise from the formulas; orange outline = NumPy's built-in generator; red = the theoretical PDF. In all five, the three agree.
Blue = noise from the formulas; orange outline = NumPy's built-in generator; red = the theoretical PDF. In all five, the three agree.

What the shapes show: uniform is a flat box from −40 to 40. Gaussian is a symmetric bell centred at 0. Erlang (b = 3) starts at 0, peaks at (b − 1)/a = 20 and has a long right tail. Exponential is highest at 0 and decays. Rayleigh rises from 0 to a peak at √(b/2) ≈ 14 and then falls. These are exactly the textbook curves, so the generators are correct.

Noise added to the test pattern

Clean test pattern: 3 flat levels (40, 120, 200)
Clean test pattern: 3 flat levels (40, 120, 200)
Uniform
Uniform
Gaussian
Gaussian
Erlang
Erlang
Exponential
Exponential
Rayleigh
Rayleigh
Histogram of each noisy image. The clean image has three spikes; adding noise turns each spike into a copy of the noise PDF, shifted to that grey level.
Histogram of each noisy image. The clean image has three spikes; adding noise turns each spike into a copy of the noise PDF, shifted to that grey level.

Why a test pattern: by eye, the five noisy images look very similar. The histogram tells them apart. A flat region of value v becomes v + η, so its histogram is the noise PDF shifted to v. With three flat levels you see the noise shape three times. This is how the noise type is identified in a real image: find a flat patch and look at its histogram.

Positive noises (Erlang, exponential, Rayleigh) shift every level to the right: the background 40 becomes about 70 with Erlang (mean 30). The image looks brighter and slightly washed out. The noise's mean adds a constant offset as well as grain.

Clipping: on the background (40), uniform noise reaches exactly 0, and Gaussian noise occasionally goes below 0, so a small spike piles up at 0. That is the clipping that the skimage generator also applies.

cameraman (clean)
cameraman (clean)
+ Gaussian noise (σ = 20)
+ Gaussian noise (σ = 20)
+ Rayleigh noise: grainy and brighter
+ Rayleigh noise: grainy and brighter
Say this when you show the output

"Every generator starts from uniform random numbers. For uniform, exponential and Rayleigh I invert the CDF. For Gaussian I use the Box–Muller transform. Erlang is the sum of b exponentials. The histograms of my noise match the built-in generators and the theoretical PDF, and the mean and variance agree with the formulas. On the three-level test pattern each spike in the histogram spreads into the shape of the noise PDF. That is how you identify noise in a real image."

04Code walkthrough

rng = np.random.default_rng(0)
U = rng.random(shape)

Creates NumPy's random generator with a fixed seed (0), so the program gives the same noise every run. That matters when you need to reproduce your output in the exam. rng.random(shape) returns uniform numbers in [0, 1), one per pixel.

def uniform(a, b):
    U = rng.random(shape)
    return a + (b - a) * U

Stretches [0, 1) to [a, b): multiplying by (b − a) sets the width and adding a sets the start.

U1 = np.maximum(U1, 1e-12)
Z = np.sqrt(-2 * np.log(U1)) * np.cos(2 * np.pi * U2)
return mean + sigma * Z

Box–Muller. −2 ln U1 gives the squared radius and 2π U2 a random angle. The cosine projects onto one axis, giving N(0, 1). Then scale by σ and shift by the mean. np.maximum(U1, 1e-12) protects against log(0) if U1 happens to be exactly 0.

def exponential(a):
    U = rng.random(shape)
    return -np.log(1 - U) / a

Inverse CDF of the exponential. 1 − U is used (not U) because rng.random can return 0 but never 1, so 1 − U is never 0 and the log is always finite.

def erlang(a, b):
    return sum(exponential(a) for _ in range(b))

Adds b independent exponential arrays element by element. Python's sum over a generator of arrays gives one array.

def rayleigh(a, b):
    U = rng.random(shape)
    return a + np.sqrt(-b * np.log(1 - U))

Inverse CDF of Rayleigh (derivation in Part 1). −b ln(1 − U) is always ≥ 0, so the square root is real and z ≥ a.

"Erlang": rng.gamma(shape=EB, scale=1 / EA, size=shape)
"Rayleigh": RA + rng.rayleigh(scale=np.sqrt(RB / 2), size=shape)

Built-ins use different parameter names, so they have to be converted. Erlang is a gamma distribution with shape = b and scale = 1/a. NumPy's Rayleigh uses scale σ, with PDF (z/σ²)e−z²/2σ². Matching that to the textbook (2/b)z e−z²/b gives b = 2σ², so σ = √(b/2). Exponential uses scale = 1/a.

skimage.util.random_noise(image, mode='gaussian', mean=0, var=0.01, amount=0.05, rng=None, clip=True)

Python's counterpart to MATLAB's imnoise. Works on images scaled to [0, 1], so σ = 20 grey levels becomes var = (20/255)². mode: 'gaussian', 's&p', 'salt', 'pepper', 'speckle', 'poisson', 'localvar'. amount = fraction of pixels for s&p. Returns float in [0, 1] (clipped); multiply by 255 for 8-bit.

noisy = np.uint8(np.clip(img + mine[name], 0, 255))

The degradation model g = f + η, done in float (uint8 image + float noise gives float), then clipped and converted. Without the clip, values below 0 or above 255 would wrap around (Part 5).

ax[0, k].hist(mine[name].ravel(), 200, density=True, ...)

density=True scales the histogram so its area is 1. It can then be compared directly with a PDF curve and with another histogram that has a different sample count.

Common mistakes
  • Adding noise to a uint8 image with integer arithmetic: values wrap around (250 + 10 → 4).
  • Using np.log(U) when U can be 0: −inf. Use 1 − U or clamp U.
  • Mixing up parameterisations: Gonzalez's Rayleigh b is not NumPy's scale; the exponential's a is a rate, while NumPy wants scale = 1/a.
  • Non-integer b for Erlang: Erlang needs an integer b (otherwise it is the general gamma distribution, which needs a different generator).
  • Histogram without density=True: the theoretical PDF curve will not line up.

05"What if" questions

What if we don't clip before converting to uint8?
Clipped (correct)
Clipped (correct)
Not clipped: −3 becomes 253, 260 becomes 4
Not clipped: −3 becomes 253, 260 becomes 4

Negative values wrap to bright and values over 255 wrap to dark. The dark coat fills with white dots and the bright sky with black dots. This looks like salt-and-pepper noise, but it is a bug.

What if σ of the Gaussian changes (5 vs 50)?
σ = 5: barely visible
σ = 5: barely visible
σ = 20
σ = 20
σ = 50: heavy grain, much clipping
σ = 50: heavy grain, much clipping

σ is the noise strength: about 68% of noise values lie within ±σ and 99.7% within ±3σ. With σ = 50 many pixels clip at 0 or 255, so the noise is no longer truly Gaussian in the image.

What if b = 1 in the Erlang generator?

The sum has one term, so Erlang(a, 1) is exactly Exponential(a): mean 1/a, variance 1/a². As b grows, the sum of many exponentials looks more and more Gaussian (central limit theorem), so the Erlang histogram becomes more symmetric.

What if we remove the seed?

Each run gives different noise values. The histograms, means and variances stay statistically the same, but the exact images change. Keep the seed when you want reproducible outputs to show the examiner.

What if we want zero-mean Rayleigh or Erlang noise?

Subtract the mean after generating (e.g. Rayleigh − (a + √(πb/4))). The shape (skew) is unchanged but the image is no longer brightened on average. Textbook figures usually add the noise directly, so the brightening is part of the observed effect.

What does salt-and-pepper noise look like, and how is it different?
5% pepper + 5% salt
5% pepper + 5% salt

It is not additive: affected pixels are replaced by 0 or 255, and all other pixels are untouched. Its histogram has two spikes at the extremes. Linear filters smear it; the median removes it (Assignment 10).

Can we remove the blur if h is known? (inverse filtering, syllabus)

The inverse filter divides by the degradation in the frequency domain:

F̂(u, v) = G(u, v) / H(u, v) = F(u, v) + N(u, v) / H(u, v)

Without noise this recovers F exactly. But H is tiny at high frequencies (a Gaussian blur gives H ≈ 10−32 at the corners), so even very weak noise (σ = 1) is divided by a near-zero number and explodes. The fix is a pseudo-inverse: divide only inside a radius R where H is not too small, and leave the rest unchanged.

a8_inverse.py
# Degradation model g = h * f + n, then restoration by inverse filtering
import cv2
import numpy as np

f = cv2.imread("cameraman.png", 0).astype(np.float64)
M, N = f.shape
V, U = np.meshgrid(np.arange(N) - N // 2, np.arange(M) - M // 2)
D2 = U ** 2 + V ** 2                                # squared distance from the centre
H = np.exp(-D2 / (2 * 30 ** 2))                     # known degradation: Gaussian blur, D0 = 30

F = np.fft.fftshift(np.fft.fft2(f))
rng = np.random.default_rng(0)
g = np.real(np.fft.ifft2(np.fft.ifftshift(F * H)))  # blurred image (h * f)
g = g + rng.normal(0, 1, f.shape)                   # + very weak noise n (sigma = 1)
G = np.fft.fftshift(np.fft.fft2(g))


def to_img(spectrum):
    return np.uint8(np.clip(np.real(np.fft.ifft2(np.fft.ifftshift(spectrum))), 0, 255))


def psnr(a, b):
    return 10 * np.log10(255 ** 2 / np.mean((a.astype(np.float64) - b) ** 2))


full = to_img(G / H)                                # F_hat = G / H = F + N / H  -> N/H explodes
print("Smallest H:", H.min())                       # ~1e-32 at the corners
print("PSNR degraded:", round(psnr(np.uint8(np.clip(g, 0, 255)), f), 2),
      "| full inverse:", round(psnr(full, f), 2))
for R in (40, 60, 90):                              # pseudo-inverse: divide only inside radius R
    limited = to_img(np.where(D2 <= R ** 2, G / H, G))
    print(f"PSNR inverse limited to radius {R}:", round(psnr(limited, f), 2))
    cv2.imwrite(f"a8_inv_r{R}.png", limited)

cv2.imwrite("a8_degraded.png", np.uint8(np.clip(g, 0, 255)))
cv2.imwrite("a8_inv_full.png", full)
Smallest H: 2.3748759345351484e-32
PSNR degraded: 24.2 | full inverse: 4.77
PSNR inverse limited to radius 40: 24.75
PSNR inverse limited to radius 60: 25.96
PSNR inverse limited to radius 90: 25.34
Blurred + σ = 1 noise (24.2 dB)
Blurred + σ = 1 noise (24.2 dB)
Full inverse: destroyed by N/H (4.8 dB)
Full inverse: destroyed by N/H (4.8 dB)
Radius 40 (24.8 dB)
Radius 40 (24.8 dB)
Radius 60: best (26.0 dB)
Radius 60: best (26.0 dB)
Radius 90: sharper but ringing/noise (25.3 dB)
Radius 90: sharper but ringing/noise (25.3 dB)

A larger radius restores more detail but lets more amplified noise through. This trade-off is why the Wiener filter (which also uses the noise level) is preferred in practice.

06Viva / evaluation angle

30-second explanation

"I generate each noise from uniform random numbers. Uniform is a + (b − a)U. Exponential and Rayleigh use the inverse of their CDFs. Gaussian uses Box–Muller. Erlang is a sum of b exponentials. I compare each with NumPy's built-in generator and with the theoretical mean and variance, and they agree within about 1%. I plot the histograms with the theoretical PDF on top. I also add each noise to a three-level test pattern, where the histogram of every flat region takes the shape of the noise PDF."

Write the image degradation model.

g(x, y) = h(x, y) * f(x, y) + η(x, y); in frequency G = H·F + N.

Enhancement vs restoration?

Enhancement is subjective (make it look better). Restoration is objective: recover the original using a model of the degradation.

Write the Gaussian / Rayleigh / exponential PDFs and their means.

Gaussian: (1/√(2π)σ)e−(z−z̄)²/2σ², mean z̄. Rayleigh: (2/b)(z−a)e−(z−a)²/b, mean a + √(πb/4). Exponential: a·e−az, mean 1/a.

What is the inverse transform method?

If U is uniform on (0, 1), then F⁻¹(U) follows the distribution with CDF F. It is used here for uniform, exponential and Rayleigh.

How do you generate Gaussian noise without a built-in function?

Box–Muller: Z = √(−2 ln U1)·cos(2πU2) is N(0, 1); then z = mean + σZ.

How is Erlang related to exponential?

Erlang(a, b) is the sum of b independent Exponential(a) variables; b = 1 gives the exponential itself.

Which noises are skewed / always positive?

Erlang, exponential and Rayleigh. They are non-negative and right-skewed, so they also raise the mean brightness.

Why use a flat test pattern?

In a flat region, the histogram of the noisy image is the noise PDF shifted to that grey level, so the noise type and its parameters can be read off directly.

What is Python's equivalent of imnoise?

skimage.util.random_noise (Gaussian, s&p, speckle, Poisson, local variance). The other distributions come from NumPy's random generators.

Where does each noise occur?

Gaussian: sensor/electronic noise. Rayleigh: range imaging. Exponential/Erlang: laser imaging. Uniform: quantization. Impulse: faulty pixels and transmission errors.

What is inverse filtering and why does it fail with noise?

F̂ = G/H. The noise term becomes N/H, which explodes where H is near zero (high frequencies). The fix is to limit the division to a radius (pseudo-inverse), or use a Wiener filter.

Assignment 9 · Texture features · Noise removal

Local Binary Pattern · Wiener, median, Gaussian and bilateral denoising

Q1: implement the local binary pattern on a grayscale image.

Q2: denoise an image corrupted by Gaussian and speckle noise using (a) Wiener, (b) median, (c) Gaussian and (d) bilateral filters, with a 3×3 or 5×5 window.

01Concept explanation

Q1 · 1.1 Features and texture

A feature is a compact set of numbers that describes something useful about an image or region, so images can be compared, matched or classified without comparing raw pixels. Texture is the repeating local pattern of intensity variation, such as brick, grass, fabric or skin. Texture is hard to capture with single pixel values but easy to capture by describing each pixel's relationship to its neighbours. That is what LBP does.

1.2 The basic LBP operator (3×3)

  1. Take the 3×3 neighbourhood of a pixel; call the centre value gc.
  2. Compare each of the 8 neighbours gp with the centre: 1 if gp ≥ gc, otherwise 0.
  3. Read the 8 bits in a fixed order (here clockwise from the top-left) as one 8-bit binary number.
  4. That number (0–255) is the LBP code of the pixel. Doing this for every pixel gives the LBP image.
  5. The histogram of the LBP image (256 bins) is the texture feature vector.
Formula · LBP LBP(x_c, y_c) = Σ_{p=0..7} s(g_p − g_c) · 2^p s(t) = 1 if t ≥ 0, else 0 Worked example (patch from cameraman, row 300, col 250): 7 6 6 1 1 1 clockwise from top-left: 1 1 1 1 1 1 0 1 6 6 6 → 1 · 1 binary 11111101 = 128+64+32+16+8+4+0+1 = 253 5 7 7 0 1 1

What the codes mean: 255 (all ones) means every neighbour is ≥ the centre, i.e. a flat region or a local minimum. 0 means the centre is a local maximum (a bright spot). Codes with one block of 1s and one block of 0s represent edges and corners. On cameraman, code 255 is the most common (19% of pixels), mainly the flat sky.

1.3 Why LBP is a good texture feature

  • Invariant to monotonic illumination changes: if every pixel is transformed by an increasing function (brighter, more contrast), the comparisons gp ≥ gc do not change, so the LBP codes are identical (demonstrated in Part 5).
  • Very cheap: only comparisons, with no multiplications.
  • Local: it captures micro-patterns (spots, edges, corners, flat areas), and the histogram summarises how often each one occurs.
  • Not rotation-invariant in the basic form: rotating the image shifts the bit order and changes the codes. The variants below fix this.
  • Sensitive to noise in flat regions: a ±1 change can flip a comparison.
Syllabus · LBP and its variants
  • Circular LBP (P, R): P sample points on a circle of radius R around the centre, with off-grid points bilinearly interpolated. Basic LBP is close to (8, 1). Larger R captures coarser texture; using several R values gives multi-scale LBP.
  • Uniform LBP: a pattern is uniform if its circular bit string has at most 2 transitions between 0 and 1 (e.g. 00011100). Uniform patterns are about 90% of codes in natural textures. All non-uniform patterns are lumped into one bin, so for P = 8 there are 59 bins instead of 256: shorter and less noisy.
  • Rotation-invariant LBP (ri): rotate the bit string to its minimum value, so all rotations of a pattern share one code (36 codes for P = 8).
  • Rotation-invariant uniform (riu2): uniform patterns labelled by their number of 1s (0–8), plus one bin for non-uniform, giving P + 2 = 10 bins. This is what skimage's method="uniform" computes.
  • Spatially enhanced LBP (e.g. face recognition): split the image into cells, compute an LBP histogram per cell, and concatenate them, so the descriptor knows where each pattern occurs. Histograms are compared with the chi-square distance Σ (h₁ − h₂)²/(h₁ + h₂).
  • Other variants: CLBP (completed LBP, adds sign and magnitude), LTP (local ternary pattern, with a tolerance band against noise), and LBP-TOP for video.
a9_lbp_uniform.py
# LBP variants with scikit-image: circular (P, R) and "uniform" rotation-invariant patterns
import cv2
import numpy as np
from skimage.feature import local_binary_pattern

P, R = 8, 1
for name in ["brick", "grass", "gravel"]:
    img = cv2.imread(f"{name}.png", 0)
    codes = local_binary_pattern(img, P, R, method="uniform")   # values 0 .. P+1
    hist = np.bincount(codes.astype(int).ravel(), minlength=P + 2) / codes.size
    print(f"{name:7s}", np.round(hist, 3))
brick   [0.031 0.066 0.017 0.087 0.189 0.155 0.058 0.089 0.189 0.121]
grass   [0.091 0.086 0.062 0.095 0.144 0.114 0.079 0.082 0.087 0.158]
gravel  [0.057 0.069 0.067 0.131 0.223 0.127 0.079 0.077 0.061 0.11 ]

Q2 · 1.4 Two noise models

Gaussian (additive)Speckle (multiplicative)
Modelg = f + n, n ~ N(0, σ²)g = f + f·n = f(1 + n), n ~ N(0, σ²)
Depends on the image?No: same strength everywhereYes: stronger in bright regions, almost none in dark ones
Measured here (noise std, dark vs bright areas)17.8 vs 19.8 (same)5.5 vs 36.9
Occurs insensor/electronic noiseultrasound, synthetic-aperture radar (SAR), laser imaging (coherent illumination)

1.5 The four denoising filters

(a) Wiener filter (adaptive / local). A linear filter that minimises mean squared error. The spatial, adaptive version (MATLAB wiener2, SciPy wiener) estimates the local mean μ and variance σ² in each window and decides how much to smooth:

Formula · Adaptive Wiener (Lee) filter μ = local mean, σ² = local variance (in a k × k window), ν² = noise variance (estimated as the mean of all σ²) f̂(x, y) = μ + max(σ² − ν², 0) / max(σ², ν²) · ( g(x, y) − μ ) flat area: σ² ≈ ν² → gain ≈ 0 → output = μ (full smoothing) edge: σ² ≫ ν² → gain ≈ 1 → output ≈ g (keep the pixel, edge preserved)

The frequency-domain Wiener filter used for restoration (Assignment 8's degradation model) is F̂ = [H* / (|H|² + K)] · G, where K ≈ noise-to-signal power ratio. It is a regularised inverse filter that does not blow up where H → 0.

(b) Median filter. A non-linear order-statistic filter: sort the k×k values and output the middle one. It removes outliers completely and preserves edges better than averaging. It is best for impulse noise, and only moderate for Gaussian noise, where averaging is statistically better.

(c) Gaussian filter. A linear weighted average with Gaussian weights (Assignment 6). It is the best simple linear choice for Gaussian noise, but it blurs edges.

(d) Bilateral filter. A Gaussian average in which each neighbour's weight also depends on how similar its intensity is to the centre pixel:

Formula · Bilateral filter f̂(p) = (1 / W_p) Σ_q G_σs(‖p − q‖) · G_σr(|g(p) − g(q)|) · g(q) G_σs : spatial Gaussian (nearby pixels count more) → sigmaSpace G_σr : range Gaussian (similar intensities count more) → sigmaColor W_p : sum of the weights (normalisation)

Across an edge, the intensity difference is large, so Gσr ≈ 0 and pixels from the other side are ignored. The filter smooths within regions but not across edges. It is edge-preserving and non-linear, because the weights depend on the image.

1.6 Comparison: PSNR results (dB, higher = better)

FilterGaussian noise (σ = 20), noisy = 22.41Speckle noise (σ = 0.2), noisy = 19.20Linear?Edges
3×35×53×35×5
Wiener28.2828.7624.3725.91locally adaptivepreserved (adaptive gain)
Median26.9526.8424.8025.75nogood
Gaussian28.0427.8625.9726.59yesblurred
Bilateral (75, 75)27.6728.6924.4326.29nobest visually

Reading the table: for Gaussian noise the Wiener filter wins, because its noise model (additive, constant variance) matches the noise. For speckle noise it falls behind the plain Gaussian filter, because speckle's variance changes with brightness, while Wiener assumes one global noise variance ν². In bright areas it under-smooths and in dark ones it over-smooths. The median is never the best here: it is designed for impulse noise. PSNR measures average error, not edge sharpness. The bilateral filter's visual advantage (sharp edges) is clearer in the zoomed images than in its PSNR.

02Solution

Q1 · Local binary pattern

a9q1_lbp.py
# Assignment 9, Q1: Local Binary Pattern (basic 3x3 LBP) of a grayscale image
#   For each pixel: compare the 8 neighbours with the centre,
#   neighbour >= centre -> 1, else 0; read the 8 bits as one number 0..255.
import cv2
import numpy as np
import matplotlib.pyplot as plt

IMG_PATH = "cameraman.png"

img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")
H, W = img.shape

# Neighbours in clockwise order starting top-left; the first gets the highest bit (2^7)
OFFSETS = [(-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1)]


def lbp_pixel(patch):
    """LBP code of the centre of one 3x3 patch (used to explain / check)."""
    c = patch[1, 1]
    code = 0
    for bit, (dy, dx) in enumerate(OFFSETS):
        if patch[1 + dy, 1 + dx] >= c:
            code += 2 ** (7 - bit)
    return code


def lbp_image(image):
    """Basic LBP for every pixel at once, using shifted copies of the image."""
    p = cv2.copyMakeBorder(image, 1, 1, 1, 1, cv2.BORDER_REPLICATE)
    center = p[1:H + 1, 1:W + 1]
    codes = np.zeros((H, W), np.uint8)
    for bit, (dy, dx) in enumerate(OFFSETS):
        neighbour = p[1 + dy:1 + dy + H, 1 + dx:1 + dx + W]       # every pixel's neighbour at (dy, dx)
        codes |= (neighbour >= center).astype(np.uint8) << (7 - bit)   # set this bit where true
    return codes


lbp = lbp_image(img)

# Worked example on one 3x3 patch
y, x = 300, 250
patch = img[y - 1:y + 2, x - 1:x + 2]
print("Patch:\n", patch)
print("Bits (>= centre):\n", (patch >= patch[1, 1]).astype(int))
print("LBP code by hand:", lbp_pixel(patch), "| from lbp_image:", lbp[y, x])

# The LBP histogram (256 bins) is the texture feature vector
hist = np.bincount(lbp.ravel(), minlength=256) / lbp.size
top = np.argsort(hist)[::-1][:5]
print("Most frequent codes:", [(int(c), format(int(c), "08b"), round(float(hist[c]), 3)) for c in top])

fig, ax = plt.subplots(1, 3, figsize=(15, 4.5))
ax[0].imshow(img, cmap="gray"); ax[0].set_title("Input"); ax[0].axis("off")
ax[1].imshow(lbp, cmap="gray"); ax[1].set_title("LBP image"); ax[1].axis("off")
ax[2].bar(range(256), hist); ax[2].set_title("LBP histogram (feature vector)")
plt.tight_layout()
plt.show()
cv2.imwrite("a9_lbp.png", lbp)
Patch:
 [[7 6 6]
 [6 6 6]
 [5 7 7]]
Bits (>= centre):
 [[1 1 1]
 [1 1 1]
 [0 1 1]]
LBP code by hand: 253 | from lbp_image: 253
Most frequent codes: [(255, '11111111', 0.19), (0, '00000000', 0.045), (191, '10111111', 0.019), (223, '11011111', 0.018), (239, '11101111', 0.017)]

(The centre of the "bits" matrix is 1 only because the centre is compared with itself; it is not part of the code.)

Q2 · Denoising

a9q2_denoise.py
# Assignment 9, Q2: Denoise images corrupted by Gaussian and speckle noise using
#   (a) Wiener filter  (b) median filter  (c) Gaussian filter  (d) bilateral filter
#   with a 3x3 or 5x5 window, and compare them using PSNR.
import cv2
import numpy as np
from scipy.signal import wiener as scipy_wiener

IMG_PATH = "cameraman.png"
clean = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if clean is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")

k = int(input("Window size (3 or 5): "))
if k not in (3, 5):
    raise ValueError("Window size must be 3 or 5")

rng = np.random.default_rng(0)
f = clean.astype(np.float64)

# ---------------- Add noise ----------------
# Gaussian (additive):    g = f + n,       n ~ N(0, 20^2)
gauss_noisy = np.uint8(np.clip(f + rng.normal(0, 20, f.shape), 0, 255))
# Speckle (multiplicative): g = f + f * n,  n ~ N(0, 0.2^2)  -> stronger in bright areas
speckle_noisy = np.uint8(np.clip(f + f * rng.normal(0, 0.2, f.shape), 0, 255))


def psnr(ref, test):
    mse = np.mean((ref.astype(np.float64) - test.astype(np.float64)) ** 2)
    return float("inf") if mse == 0 else 10 * np.log10(255 ** 2 / mse)


def wiener_filter(img, k, border=cv2.BORDER_REFLECT):
    """Adaptive (local) Wiener filter, as in MATLAB's wiener2."""
    g = img.astype(np.float64)
    local_mean = cv2.blur(g, (k, k), borderType=border)                          # mu in each window
    local_var = cv2.blur(g ** 2, (k, k), borderType=border) - local_mean ** 2    # sigma^2 = E[g^2] - mu^2
    noise_var = np.mean(local_var)                           # estimate of the noise variance
    gain = np.maximum(local_var - noise_var, 0) / np.maximum(local_var, noise_var)
    out = local_mean + gain * (g - local_mean)
    return np.uint8(np.clip(np.round(out), 0, 255))


def denoise_all(noisy):
    return {
        "Wiener": wiener_filter(noisy, k),
        "Median": cv2.medianBlur(noisy, k),
        "Gaussian": cv2.GaussianBlur(noisy, (k, k), 0),           # sigma from k
        "Bilateral": cv2.bilateralFilter(noisy, k, 75, 75),        # d, sigmaColor, sigmaSpace
    }


for noise_name, noisy in [("Gaussian noise", gauss_noisy), ("Speckle noise", speckle_noisy)]:
    print(f"\n{noise_name}, {k}x{k} window   (noisy PSNR = {psnr(clean, noisy):.2f} dB)")
    results = denoise_all(noisy)
    for name, out in results.items():
        print(f"  {name:10s} PSNR = {psnr(clean, out):.2f} dB")
        cv2.imwrite(f"a9_{noise_name.split()[0].lower()}_{name.lower()}_{k}.png", out)
    # Check the hand-written Wiener against SciPy. SciPy pads with zeros, so use
    # zero padding (BORDER_CONSTANT) here to reproduce it exactly.
    sp = np.uint8(np.clip(np.round(scipy_wiener(noisy.astype(np.float64), (k, k))), 0, 255))
    mine_zero = wiener_filter(noisy, k, cv2.BORDER_CONSTANT)
    print(f"  Wiener vs scipy.signal.wiener: max difference {np.abs(sp.astype(int) - mine_zero).max()}")

cv2.imwrite("a9_gauss_noisy.png", gauss_noisy)
cv2.imwrite("a9_speckle_noisy.png", speckle_noisy)
cv2.imshow("Gaussian noisy", gauss_noisy)
cv2.imshow("Speckle noisy", speckle_noisy)
cv2.waitKey(0)
cv2.destroyAllWindows()

Console output (window 5):

Window size (3 or 5): 5

Gaussian noise, 5x5 window   (noisy PSNR = 22.41 dB)
  Wiener     PSNR = 28.76 dB
  Median     PSNR = 26.84 dB
  Gaussian   PSNR = 27.86 dB
  Bilateral  PSNR = 28.69 dB
  Wiener vs scipy.signal.wiener: max difference 0

Speckle noise, 5x5 window   (noisy PSNR = 19.20 dB)
  Wiener     PSNR = 25.91 dB
  Median     PSNR = 25.75 dB
  Gaussian   PSNR = 26.59 dB
  Bilateral  PSNR = 26.29 dB
  Wiener vs scipy.signal.wiener: max difference 0

The hand-written Wiener filter is identical to scipy.signal.wiener when the same (zero) padding is used. Results for the 3×3 window are in the table in Part 1.

03Output images

Q1 · LBP

Input
Input
LBP image (each pixel = its code 0–255)
LBP image (each pixel = its code 0–255)
The LBP histogram is the feature vector. Code 255 (flat or local minimum) is by far the most common because of the large uniform sky; code 0 (local maximum) is second.
The LBP histogram is the feature vector. Code 255 (flat or local minimum) is by far the most common because of the large uniform sky; code 0 (local maximum) is second.

What the LBP image shows: it is not meant to look like the original. Brightness has been replaced by a pattern code. The sky is almost uniformly white (code 255: neighbours ≥ centre in flat areas, since ties count as 1). The grass is a fine random texture, because tiny intensity fluctuations give random codes. The coat and the man's outline show structured patterns along edges. The image's texture, not its brightness, is what has been encoded.

LBP as a texture descriptor

LBP of brick
LBP of brick
LBP of grass
LBP of grass
LBP of gravel
LBP of gravel
Uniform (riu2) LBP histograms, 10 bins each. Brick has a strong peak at bins 4 and 8 (edges and flat mortar); grass is spread evenly with many non-uniform patterns (bin 9); gravel peaks at bin 4. The histograms differ, so a classifier can tell the textures apart.
Uniform (riu2) LBP histograms, 10 bins each. Brick has a strong peak at bins 4 and 8 (edges and flat mortar); grass is spread evenly with many non-uniform patterns (bin 9); gravel peaks at bin 4. The histograms differ, so a classifier can tell the textures apart.

Q2 · Denoising, 5×5 window

Gaussian noise σ = 20 · 22.41 dB
Gaussian noise σ = 20 · 22.41 dB
Wiener · 28.76 dB
Wiener · 28.76 dB
Median · 26.84 dB
Median · 26.84 dB
Gaussian · 27.86 dB
Gaussian · 27.86 dB
Bilateral · 28.69 dB
Bilateral · 28.69 dB
Speckle noise σ = 0.2 · 19.20 dB
Speckle noise σ = 0.2 · 19.20 dB
Wiener · 25.91 dB
Wiener · 25.91 dB
Median · 25.75 dB
Median · 25.75 dB
Gaussian · 26.59 dB
Gaussian · 26.59 dB
Bilateral · 26.29 dB
Bilateral · 26.29 dB

Zoomed (2.5×) on the Gaussian-noise results, where the edge behaviour is visible:

Noisy
Noisy
Wiener: smooth skin, sharp camera edges
Wiener: smooth skin, sharp camera edges
Median: blotchy "painted" look
Median: blotchy "painted" look
Gaussian: everything uniformly soft
Gaussian: everything uniformly soft
Bilateral: flat areas smooth, edges crisp
Bilateral: flat areas smooth, edges crisp

Speckle vs Gaussian noise: in the speckle image the noise is heavy in the bright sky and almost absent on the dark coat (noise std 36.9 vs 5.5), because it is multiplied by the pixel value. Gaussian noise is equally strong everywhere.

Wiener smooths the sky and skin (low local variance, so it outputs the local mean) but leaves edges almost untouched (high local variance). Median turns fine noise into small flat patches, the typical "painted" look. Gaussian blurs noise and edges equally. Bilateral refuses to average across the face/background and camera edges, so edges stay crisp while flat regions are cleaned. For speckle, the sky is still grainy after Wiener and bilateral, because those filters assume constant noise strength, which speckle does not have.

Say this when you show the output

"For LBP, I compare each pixel's 8 neighbours with the centre, write 1 if the neighbour is greater or equal, and read the 8 bits clockwise as a number from 0 to 255. The histogram of these codes is the texture feature. It does not change if the lighting changes monotonically. For denoising, I added Gaussian and speckle noise and compared the four filters by PSNR. Wiener is best for Gaussian noise because it adapts to local variance: it smooths flat areas and keeps edges. Bilateral keeps edges sharpest visually. For speckle, which is multiplicative, the plain Gaussian scores highest, because Wiener assumes constant noise variance."

04Code walkthrough

Q1 · LBP

OFFSETS = [(-1, -1), (-1, 0), (-1, 1), (0, 1),
           (1, 1), (1, 0), (1, -1), (0, -1)]

The 8 neighbours as (row, column) offsets, clockwise from the top-left. Index 0 gets bit 7 (value 128) and index 7 gets bit 0 (value 1). Any fixed order works, but it must be the same for every pixel.

def lbp_pixel(patch):
    c = patch[1, 1]
    code = 0
    for bit, (dy, dx) in enumerate(OFFSETS):
        if patch[1 + dy, 1 + dx] >= c:
            code += 2 ** (7 - bit)
    return code

The definition written literally for one 3×3 patch: compare, and add the bit's place value when the comparison is true. It is used to verify the fast version on one pixel and to explain the method.

p = cv2.copyMakeBorder(image, 1, 1, 1, 1, cv2.BORDER_REPLICATE)
center = p[1:H + 1, 1:W + 1]

Pads by 1 so edge pixels have 8 neighbours (Assignment 3). Replicate padding makes the padded neighbours equal to the edge pixel. center is the original image inside the padding.

neighbour = p[1 + dy:1 + dy + H, 1 + dx:1 + dx + W]
codes |= (neighbour >= center).astype(np.uint8) << (7 - bit)

The same shifted-slice trick as Assignment 6. The slice is the whole image shifted by (dy, dx), so neighbour[y, x] is pixel (y, x)'s neighbour in that direction. The comparison gives 0/1 for every pixel at once. << (7 − bit) shifts the bit into position (1 << 7 = 128), and |= (bitwise OR) sets it in the code. After 8 directions every pixel has its full code.

hist = np.bincount(lbp.ravel(), minlength=256) / lbp.size

The 256-bin normalised histogram, the feature vector (same function as Assignment 5). Normalising makes images of different sizes comparable.

skimage.feature.local_binary_pattern(image, P, R, method='default')

P: number of circular neighbours (8). R: radius (1). method: 'default' (basic, but with circular interpolated sampling, so diagonals are at distance 1 rather than the 3×3 corners; codes differ slightly from the square version), 'ror' (rotation-invariant), 'uniform' (riu2, values 0..P+1), 'nri_uniform' (59 bins), 'var'. Returns a float array.

Q2 · Denoising

speckle_noisy = np.uint8(np.clip(f + f * rng.normal(0, 0.2, f.shape), 0, 255))

Speckle model g = f + f·n. Each pixel's noise is proportional to its own value. This matches random_noise(mode='speckle', var=0.04).

local_mean = cv2.blur(g, (k, k), borderType=border)
local_var = cv2.blur(g ** 2, (k, k), borderType=border) - local_mean ** 2

Local statistics in every k×k window at once. A box filter gives the local mean μ. Variance uses σ² = E[g²] − (E[g])²: box-filter the squared image, then subtract the squared mean. This is fast, with no loop over windows.

noise_var = np.mean(local_var)
gain = np.maximum(local_var - noise_var, 0) / np.maximum(local_var, noise_var)
out = local_mean + gain * (g - local_mean)

If the noise variance ν² is not known, estimate it as the average local variance, as MATLAB/SciPy do. The gain is between 0 and 1: about 0 in flat windows (output = mean) and about 1 at edges (output = original pixel). The two np.maximum calls stop the gain from going negative or dividing by a tiny variance.

cv2.medianBlur(src, ksize) → dst

ksize: odd integer ≥ 3 (a single number, not a tuple). For uint8 images any odd size works; for float, only 3 or 5.

cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace) → dst

d: neighbourhood diameter (here the window size 3 or 5; if ≤ 0 it is computed from sigmaSpace). sigmaColor: range σ, i.e. how different an intensity can be and still be averaged. Small (10–30): only near-identical pixels are mixed, so little smoothing. Large (150+): it behaves like a Gaussian blur. sigmaSpace: spatial σ. Typical values: d = 5–9, sigmaColor = sigmaSpace = 50–100. It is slower than linear filters.

def psnr(ref, test):
    mse = np.mean((ref - test) ** 2)
    return 10 * np.log10(255 ** 2 / mse)

Peak signal-to-noise ratio in decibels. MSE is the mean squared difference from the clean image. PSNR rises as MSE falls, and +6 dB roughly means the error amplitude halved. Typical: about 20 dB looks noisy, 30+ dB looks good, and identical images give ∞. cv2.PSNR(a, b) computes the same thing.

Common mistakes
  • LBP with > instead of >=: flat regions then give code 0 instead of 255. That is a valid variant, but be consistent and say which you used.
  • LBP on uint8 differences: computing neighbour − center in uint8 wraps negatives; compare directly (as here) or use int16.
  • Comparing the LBP image instead of its histogram: the feature is the histogram.
  • Computing the local variance as box(g)² − box(g²): wrong order, so it comes out negative. It is E[g²] − E[g]².
  • Even or tuple ksize for medianBlur: error. It takes one odd integer.
  • Using PSNR alone: two outputs with similar PSNR can look very different (edges vs blur). Look at zoomed images too (or SSIM).

05"What if" questions

What if the illumination changes (brighter, lower contrast)?
0.5·f + 100: lower contrast, brighter
0.5·f + 100: lower contrast, brighter
LBP of the original
LBP of the original
LBP of 0.5·f + 100: identical (0 pixels differ)
LBP of 0.5·f + 100: identical (0 pixels differ)

Any strictly increasing transform keeps every comparison gp ≥ gc the same, so all LBP codes are identical. This is LBP's key strength for faces and textures under different lighting. (Computed in float: rounding to uint8 or clipping at 255 could merge values and change a few codes.)

What if the image is rotated by 90°?

The pixels are the same, but each neighbourhood's bits are read starting from a different neighbour, so the codes change. On cameraman the 256-bin histogram changes by 0.12 (L1 distance). Use rotation-invariant LBP (rotate each code's bits to its minimum value) or riu2 to get the same histogram for rotated textures.

What if the image is noisy?
LBP of clean cameraman
LBP of clean cameraman
LBP after adding noise (σ = 10): the sky becomes random
LBP after adding noise (σ = 10): the sky becomes random

In flat regions the neighbours differ from the centre by only tiny amounts, so noise flips comparisons randomly and the flat sky (code 255) turns into random codes. Remedies: smooth first, use a larger radius, use uniform LBP (noisy, non-uniform codes go into one bin), or use LTP with a tolerance band.

What if we use a 5×5 window instead of 3×3 for denoising?

See the table in Part 1. More pixels are averaged, so noise drops more but detail is lost. For Gaussian noise, Wiener and bilateral improve with 5×5 (28.3 → 28.8, 27.7 → 28.7), while median and Gaussian get slightly worse: the extra blur costs more than the extra noise removed. For the stronger speckle noise, every filter improves with 5×5.

What if we change sigmaColor or d in the bilateral filter?
sigmaColor 25 (d = 5): too strict, noise left · 26.88 dB
sigmaColor 25 (d = 5): too strict, noise left · 26.88 dB
sigmaColor 75 · 28.69 dB
sigmaColor 75 · 28.69 dB
sigmaColor 150: behaves like a Gaussian blur · 27.85 dB
sigmaColor 150: behaves like a Gaussian blur · 27.85 dB

sigmaColor must be larger than the noise amplitude (σ = 20 here), or noisy pixels are treated as "different" and not averaged. If it is much larger than the edge contrast, edges are averaged too and the edge-preserving advantage is lost. A larger d (9) smooths more (27.95 dB) but is slower.

What if we apply the median filter to salt-and-pepper noise instead?

Then the median wins by a large margin: in Assignment 6, a 3×3 median gave MSE 68 vs 302 for the box filter. The linear filters (Wiener, Gaussian) smear each impulse into a grey blotch, and the bilateral filter treats impulses as "edges" and keeps them. The noise type decides the filter.

What if the noise variance is known? Should Wiener still estimate it?

If ν² is known (e.g. 400 for σ = 20), pass it in: scipy.signal.wiener(img, (k, k), noise=400). Estimating it from the mean local variance over-estimates ν² when the image has many edges, because edge windows have large variance, so the filter smooths a bit more than necessary.

What if we filter a colour image?

Median, Gaussian and bilateral work directly on 3-channel images in OpenCV (bilateral uses colour distance, so edges in colour are preserved). The Wiener code here is single-channel. Run it per channel or on the luminance only. cv2.fastNlMeansDenoisingColored is a stronger modern alternative (non-local means).

06Viva / evaluation angle

30-second explanation

"For LBP, I pad the image by one pixel, then for each of the 8 neighbour directions I take a shifted copy of the image, compare it with the centre, and set the matching bit with a left shift and bitwise OR. Each pixel gets a code from 0 to 255, and the histogram of codes is the texture feature. For denoising, I add Gaussian and speckle noise and apply Wiener, median, Gaussian and bilateral filters with the chosen window size, then compare PSNR. My Wiener uses the local mean and variance, and its output matches SciPy exactly."

How is the LBP code computed?

Threshold the 8 neighbours against the centre (≥ → 1), read the bits in a fixed circular order, and convert to decimal (0–255).

What is the LBP feature vector?

The (normalised) histogram of LBP codes: 256 bins for basic LBP, 59 for uniform, 10 for riu2.

Why is LBP invariant to illumination?

It only uses the sign of differences. Any monotonic grey-level change preserves every comparison.

What is a uniform pattern?

A circular bit string with at most two 0/1 transitions (e.g. 00111000). They represent edges, corners, spots and flat areas, and make up most codes in real textures.

How do you make LBP rotation-invariant?

Circularly rotate each code's bits and take the minimum value (ri), or count the 1s in uniform patterns (riu2).

Where is LBP used?

Texture classification, face recognition, facial expression analysis, medical image texture and surface inspection.

Gaussian vs speckle noise?

Gaussian is additive and independent of the signal. Speckle is multiplicative (g = f + f·n), stronger in bright regions, and occurs in ultrasound and radar.

How does the adaptive Wiener filter work?

It estimates the local mean and variance. Output = mean + (σ² − ν²)/σ² × (pixel − mean): full smoothing in flat areas, little at edges.

How does the bilateral filter preserve edges?

Each weight is the product of a spatial Gaussian and an intensity-difference Gaussian. Pixels across an edge differ a lot in intensity and get near-zero weight.

Why is the median filter non-linear?

Its output is a sorted (order-statistic) value, not a weighted sum, so median(a + b) ≠ median(a) + median(b).

What is PSNR?

10·log₁₀(255²/MSE) in dB. Higher means closer to the original.

Which filter is best for which noise?

Gaussian noise: Wiener / Gaussian / bilateral. Speckle: Gaussian (or log-transform then filter; specialised Lee/Frost filters). Salt-and-pepper: median / adaptive median.

Assignment 10 · Order-statistic filtering · Segmentation

Adaptive median filter · Otsu's global thresholding

Q1: denoise the input image using the adaptive median filter. Take the initial window size and the maximum window size (Smax) from the user. Compare the median filter and the adaptive median filter using PSNR.

Q2: threshold the image using Otsu's global threshold to segment a grayscale image.

01Concept explanation

Q1 · 1.1 Why the ordinary median filter is not enough

Salt-and-pepper (impulse) noise sets random pixels to 0 or 255. The median filter (Assignments 6 and 9) sorts the window and takes the middle value, so isolated extremes are ignored. It has two weaknesses:

  • High noise density: if more than half the window is noise, the median itself is 0 or 255, and the noise survives. A 3×3 median works up to about 20% density.
  • It changes every pixel, including the clean ones, so fine detail and thin lines are removed. A larger window handles more noise but blurs more.

The adaptive median filter fixes both: it grows the window only where needed, and it leaves a pixel unchanged if it does not look like an impulse.

1.2 The algorithm (Gonzalez & Woods)

Notation for the current window Sxy centred on (x, y): zmin = minimum, zmax = maximum, zmed = median, zxy = the pixel itself, Smax = largest allowed window.

Algorithm · Adaptive median filter Stage A: A1 = z_med − z_min A2 = z_med − z_max if A1 > 0 AND A2 < 0: go to Stage B (z_min < z_med < z_max: the median is NOT an impulse) else: increase the window size (e.g. 3 → 5 → 7) if size ≤ S_max: repeat Stage A else: output z_med Stage B: B1 = z_xy − z_min B2 = z_xy − z_max if B1 > 0 AND B2 < 0: output z_xy (the pixel itself is NOT an impulse: keep it) else: output z_med (the pixel is an impulse: replace it)

Intuition:

  • Stage A asks: "can I trust the median of this window?" If the median equals the min or max, it is probably noise itself, so look at a bigger window that contains more clean pixels.
  • Stage B asks: "is the centre pixel noise?" If it lies strictly between min and max, it is a normal pixel, so keep the original value. Only impulses get replaced.

Three goals: remove impulse noise, smooth other (non-impulse) noise, and reduce distortion such as thinning or thickening of object boundaries.

1.3 Worked example (3×3 window, Smax = 5)

Window: [ 0 255 120 ] sorted: 0 0 118 120 120 122 125 255 255 [ 118 255 120 ] z_min = 0, z_max = 255, z_med = 120, z_xy = 255 (centre) [ 0 122 125 ] Stage A: 120 − 0 > 0 and 120 − 255 < 0 → median is trustworthy → Stage B Stage B: 255 − 0 > 0 but 255 − 255 = 0, not < 0 → centre is an impulse → output 120

If the centre had been 121 instead, Stage B would keep 121. An ordinary median filter would have replaced it with 120 anyway.

1.4 PSNR

Formula · Peak signal-to-noise ratio MSE = (1 / MN) Σ Σ [ f(x, y) − f̂(x, y) ]² PSNR = 10 · log₁₀( MAX² / MSE ) dB MAX = 255 for 8-bit

Higher is better: identical images give ∞; above about 30 dB is generally good; below about 20 dB is visibly degraded. PSNR needs the clean original, so it is used for evaluation experiments like this one, where we added the noise ourselves.

Q2 · 1.5 Otsu's method

Assignment 1 thresholded with the mean or a user value. Otsu chooses T automatically and optimally from the histogram alone. It tries every k and picks the one that best separates the pixels into two classes: background C1 (levels 0…k) and foreground C2 (levels k+1…255).

"Best separated" means the class means are far apart relative to the spread, i.e. the between-class variance σB² is largest. Equivalently, the within-class variance (how spread out each class is) is smallest, because the two always add up to the fixed global variance.

Formula · Otsu (Gonzalez & Woods notation) p_i = n_i / MN normalised histogram P1(k) = Σ_{i=0..k} p_i probability of class C1 (P2 = 1 − P1) m(k) = Σ_{i=0..k} i · p_i cumulative mean up to k m_G = Σ_{i=0..L−1} i · p_i global mean σ_B²(k) = [ m_G · P1(k) − m(k) ]² / [ P1(k) · (1 − P1(k)) ] = P1 · P2 · (m1 − m2)² (equivalent form) k* = argmax_k σ_B²(k) (if several k tie, average them) η = σ_B²(k*) / σ_G² separability, 0..1 (1 = perfectly two-valued image)

Step by step: (1) histogram → pi; (2) cumulative sums P1(k) and m(k); (3) global mean mG; (4) σB²(k) for all k; (5) k* = position of the maximum; (6) segment with g = 255 if f > k*, else 0. Every quantity comes from the histogram, so it takes one pass over the image and then just 256 calculations.

1.6 When Otsu works and fails

SituationResultRemedy
Bimodal histogram, comparable class sizesExcellent (coins: η = 0.756)—
Heavy noiseNoisy, speckled mask (modes overlap)Smooth first (Gaussian/median), then Otsu
Object very small relative to backgroundFails: the histogram valley is invisibleCompute the histogram only near edges, or use local methods
Uneven illuminationFails (one T can't fit everywhere)Adaptive thresholding (Assignment 1), or split into tiles
More than two classesMerges classesMulti-level Otsu (k thresholds)
Syllabus · the rest of "Image Segmentation"

Segmentation divides an image into meaningful regions. Methods are based on discontinuity (edges: point/line/edge detection, A7) or similarity (thresholding, region-based, clustering).

  • Point, line and edge detection: point detection with a Laplacian mask and a threshold on |response|; line detection with direction-specific masks (horizontal, vertical, ±45°); edges with gradient/Canny/LoG (A7).
  • Region growing: start from seed pixels and add 8-connected neighbours whose intensity is similar (e.g. within ±T of the seed), until no more pixels qualify.
  • Region splitting and merging: recursively split the image into quadrants (quadtree) while a region is not uniform; then merge adjacent regions that are similar.
  • Clustering (k-means): group pixels by feature (intensity, colour, position) into k clusters by minimising distance to cluster centres.
  • Graph cut: pixels are graph nodes; edge weights encode similarity. Segment by cutting the graph with minimum cost, as in normalised cuts and GrabCut (cv2.grabCut).
  • Texture segmentation: segment by texture features (e.g. LBP histograms from A9) instead of intensity.
  • Motion: difference consecutive frames (|ft − ft−1| > T) or subtract a background model, so moving objects become foreground.
  • Morphological operations (also in this unit) clean binary masks after thresholding. Erosion shrinks white regions and dilation grows them. Opening (erode then dilate) removes small white specks; closing (dilate then erode) fills small holes and gaps.
a10_postprocess.py
# After Otsu: clean the mask with morphology; and two other segmentations
import cv2
import numpy as np
from skimage.filters import threshold_multiotsu

coins = cv2.imread("coins.png", 0)
T, mask = cv2.threshold(coins, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)       # remove small white specks
closed = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel)    # fill small dark holes
n, labels = cv2.connectedComponents(closed)
print("Objects found after cleaning:", n - 1)                 # label 0 = background

# Multi-level Otsu: 2 thresholds -> 3 classes
cam = cv2.imread("cameraman.png", 0)
t1, t2 = threshold_multiotsu(cam, classes=3)
three = np.digitize(cam, [t1, t2]).astype(np.uint8) * 127     # 0, 127, 254
print("Multi-Otsu thresholds:", t1, t2)

# k-means clustering on intensity (k = 3)
data = cam.reshape(-1, 1).astype(np.float32)
crit = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 0.5)
_, lab, centers = cv2.kmeans(data, 3, None, crit, 5, cv2.KMEANS_PP_CENTERS)
kmeans_img = centers[lab.ravel()].reshape(cam.shape).astype(np.uint8)
print("k-means centres:", sorted(int(c) for c in centers.ravel()))

cv2.imwrite("a10_coins_mask.png", mask)
cv2.imwrite("a10_coins_clean.png", closed)
cv2.imwrite("a10_multiotsu.png", three)
cv2.imwrite("a10_kmeans.png", kmeans_img)
Objects found after cleaning: 28
Multi-Otsu thresholds: 87 176
k-means centres: [27, 147, 204]
Otsu mask of coins: specks, hollow coins
Otsu mask of coins: specks, hollow coins
After opening + closing
After opening + closing
Multi-Otsu, 3 classes (T = 87, 176)
Multi-Otsu, 3 classes (T = 87, 176)
k-means, k = 3 (centres 27, 147, 204)
k-means, k = 3 (centres 27, 147, 204)

The image has 24 coins, but 28 objects are counted. A few dark coins at the bottom are only partly above the threshold and break into pieces. Morphology fixes specks and small holes, not objects whose intensity overlaps the background. Multi-Otsu and k-means both separate cameraman into dark (coat), mid (grass) and bright (sky) classes.

02Solution

Q1 · Adaptive median filter vs median filter

a10q1_adaptive_median.py
# Assignment 10, Q1: Adaptive median filter vs ordinary median filter (PSNR comparison)
#   Initial window size and maximum window size S_max come from the user.
import cv2
import numpy as np

IMG_PATH = "cameraman.png"
clean = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if clean is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")

s_init = int(input("Initial window size (odd, >= 3): "))
s_max = int(input("Maximum window size S_max (odd, >= initial): "))
density = float(input("Salt-and-pepper noise density (e.g. 0.3): "))
if s_init < 3 or s_init % 2 == 0 or s_max < s_init or s_max % 2 == 0:
    raise ValueError("Window sizes must be odd, with 3 <= initial <= S_max")

# ---------------- Salt-and-pepper (impulse) noise ----------------
rng = np.random.default_rng(0)
noisy = clean.copy()
r = rng.random(clean.shape)
noisy[r < density / 2] = 0                      # pepper
noisy[r > 1 - density / 2] = 255                # salt


def adaptive_median(img, s_init, s_max):
    pad = s_max // 2
    P = cv2.copyMakeBorder(img, pad, pad, pad, pad, cv2.BORDER_REFLECT)
    out = img.copy()
    rows, cols = img.shape
    for y in range(rows):
        for x in range(cols):
            z_xy = int(img[y, x])
            s = s_init
            while True:
                h = s // 2
                win = P[y + pad - h:y + pad + h + 1, x + pad - h:x + pad + h + 1]
                z_min, z_max, z_med = int(win.min()), int(win.max()), int(np.median(win))
                # Stage A: is the median itself an impulse (equal to min or max)?
                if z_min < z_med < z_max:
                    # Stage B: keep the pixel if it is not an impulse, else use the median
                    out[y, x] = z_xy if z_min < z_xy < z_max else z_med
                    break
                s += 2                                  # median unreliable: grow the window
                if s > s_max:
                    out[y, x] = z_med                   # give up: output the median
                    break
    return out


def psnr(ref, test):
    mse = np.mean((ref.astype(np.float64) - test.astype(np.float64)) ** 2)
    return float("inf") if mse == 0 else 10 * np.log10(255 ** 2 / mse)


median_out = cv2.medianBlur(noisy, s_init)       # ordinary median, initial size
median_big = cv2.medianBlur(noisy, s_max)        # ordinary median, maximum size
adaptive_out = adaptive_median(noisy, s_init, s_max)

print(f"Noise density {density:.0%}")
rows = [("noisy", noisy), (f"median {s_init}x{s_init}", median_out),
        (f"median {s_max}x{s_max}", median_big), (f"adaptive median ({s_init}..{s_max})", adaptive_out)]
for label, im in rows:
    print(f"PSNR {label:28s}: {psnr(clean, im):6.2f} dB")
print(f"{'cv2.PSNR check (adaptive)':33s}: {cv2.PSNR(clean, adaptive_out):6.2f} dB")

cv2.imshow("Noisy", noisy)
cv2.imshow("Median", median_out)
cv2.imshow("Adaptive median", adaptive_out)
cv2.imwrite("a10_noisy.png", noisy)
cv2.imwrite("a10_median.png", median_out)
cv2.imwrite("a10_median_big.png", median_big)
cv2.imwrite("a10_adaptive.png", adaptive_out)
cv2.waitKey(0)
cv2.destroyAllWindows()

Console output (initial 3, Smax 7, density 0.3). It runs in about 3.5 s:

Initial window size (odd, >= 3): 3
Maximum window size S_max (odd, >= initial): 7
Salt-and-pepper noise density (e.g. 0.3): 0.3
Noise density 30%
PSNR noisy                       :   9.98 dB
PSNR median 3x3                  :  22.59 dB
PSNR median 7x7                  :  25.65 dB
PSNR adaptive median (3..7)      :  30.40 dB
cv2.PSNR check (adaptive)        :  30.40 dB

Q2 · Otsu's threshold

a10q2_otsu.py
# Assignment 10, Q2: Otsu's global threshold for segmentation
#   Choose the k that maximises the between-class variance
#   sigma_B^2(k) = [m_G * P1(k) - m(k)]^2 / [P1(k) * (1 - P1(k))]
import cv2
import numpy as np
import matplotlib.pyplot as plt

IMG_PATH = "coins.png"
img = cv2.imread(IMG_PATH, cv2.IMREAD_GRAYSCALE)
if img is None:
    raise FileNotFoundError(f"Could not read {IMG_PATH}")
L = 256

# 1. Normalised histogram
p = np.bincount(img.ravel(), minlength=L) / img.size

# 2. Cumulative sums for every candidate threshold k
P1 = np.cumsum(p)                      # probability of class 1 (levels 0..k)
m = np.cumsum(np.arange(L) * p)        # cumulative mean up to k
mG = m[-1]                             # global mean

# 3. Between-class variance for every k (skip k where a class is empty)
with np.errstate(divide="ignore", invalid="ignore"):
    sigma_b2 = (mG * P1 - m) ** 2 / (P1 * (1 - P1))
sigma_b2 = np.nan_to_num(sigma_b2)

# 4. Best threshold (if several k tie, average them, as in Gonzalez & Woods)
k_star = int(np.round(np.mean(np.flatnonzero(sigma_b2 == sigma_b2.max()))))
sigma_G2 = np.sum((np.arange(L) - mG) ** 2 * p)       # global variance
eta = sigma_b2[k_star] / sigma_G2                      # separability, 0..1

segmented = np.where(img > k_star, 255, 0).astype(np.uint8)

# OpenCV built-in for comparison
T_cv, seg_cv = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print(f"Otsu threshold (manual) = {k_star} | OpenCV = {T_cv:.0f}")
print(f"Separability eta = {eta:.3f}")
print("Pixels that differ from OpenCV:", int(np.count_nonzero(segmented != seg_cv)))

fig, ax = plt.subplots(1, 3, figsize=(15, 4.5))
ax[0].imshow(img, cmap="gray"); ax[0].set_title("Input"); ax[0].axis("off")
ax[1].plot(sigma_b2); ax[1].axvline(k_star, color="r"); ax[1].set_title("Between-class variance")
ax[2].imshow(segmented, cmap="gray"); ax[2].set_title(f"Otsu, T = {k_star}"); ax[2].axis("off")
plt.tight_layout()
plt.show()
cv2.imwrite("a10_otsu.png", segmented)
Otsu threshold (manual) = 107 | OpenCV = 107
Separability eta = 0.756
Pixels that differ from OpenCV: 0

03Output images

Q1 · 30% salt-and-pepper noise

Noisy (30%) · 9.98 dB
Noisy (30%) · 9.98 dB
Median 3×3 · 22.59 dB: noise clusters survive
Median 3×3 · 22.59 dB: noise clusters survive
Median 7×7 · 25.65 dB: clean but blurred
Median 7×7 · 25.65 dB: clean but blurred
Adaptive 3..7 · 30.40 dB: clean and sharp
Adaptive 3..7 · 30.40 dB: clean and sharp
Noisy (zoom)
Noisy (zoom)
Median 3×3
Median 3×3
Median 7×7
Median 7×7
Adaptive median
Adaptive median

Median 3×3: at 30% density, some 3×3 windows contain 5 or more noisy pixels, so their median is itself 0 or 255. Clumps of black and white dots remain.

Median 7×7: a 49-pixel window almost always has a clean median, so the noise is gone. But every pixel is replaced by a 7×7 median, so the face, hair and camera lose fine detail and look painted.

Adaptive median: it starts at 3×3 and grows to 5×5 or 7×7 only where the median is untrustworthy, and keeps every pixel that is not an extreme of its window unchanged. Noise is removed as well as with 7×7, while details stay as sharp as the original: 30.40 dB, about 4.8 dB better than the best fixed median.

PSNR across noise densities

Median 3×3 collapses as density rises; 7×7 is stable but capped by blurring (about 26 dB). The adaptive filter is best at every density. With a larger S_max (11) it holds up even at 60–70% noise.
Median 3×3 collapses as density rises; 7×7 is stable but capped by blurring (about 26 dB). The adaptive filter is best at every density. With a larger S_max (11) it holds up even at 60–70% noise.
Density10%20%30%40%50%60%70%
Median 3×329.526.822.618.314.611.79.4
Median 7×726.125.925.725.224.422.618.2
Adaptive (3..7)33.131.830.428.827.325.221.1
Adaptive (3..11)33.131.830.428.827.526.124.6

Q2 · Otsu on coins.png

Input: coins.png
Input: coins.png
Otsu, T = 107 (η = 0.756)
Otsu, T = 107 (η = 0.756)
The histogram has a dark background mode and a brighter coin mode. σ_B²(k) (red) rises, peaks at k = 107 in the region between the modes, and falls. Otsu's threshold is the location of that peak.
The histogram has a dark background mode and a brighter coin mode. σ_B²(k) (red) rises, peaks at k = 107 in the region between the modes, and falls. Otsu's threshold is the location of that peak.

What happened: every pixel above 107 became white (coin) and the rest black (background). Most coins are clean white discs. The darker coins in the lower rows have parts below 107, so they come out hollow or speckled. Their brightness overlaps the background's, which one global threshold cannot resolve. A separability of η = 0.756 means the two classes are well (but not perfectly) separated. The manual result matches OpenCV pixel for pixel. On cameraman, Otsu gives T = 102, the value seen in Assignment 1.

Say this when you show the output

"The adaptive median filter first checks whether the window's median is itself an impulse. If it is, it enlarges the window up to Smax. Once the median is reliable, it keeps the centre pixel if that pixel is not an impulse, and otherwise replaces it with the median. So it removes noise like a large median but does not blur clean pixels: at 30% noise it gets 30.4 dB against 25.7 dB for the best fixed median. For Otsu, I compute the between-class variance for every threshold from the cumulative histogram and pick the maximum, 107 here. That matches OpenCV."

04Code walkthrough

Q1 · Adaptive median

r = rng.random(clean.shape)
noisy[r < density / 2] = 0
noisy[r > 1 - density / 2] = 255

Each pixel gets a uniform random number. The lowest density/2 fraction become pepper (0) and the highest density/2 become salt (255), so the total corrupted fraction is the density, split equally.

pad = s_max // 2
P = cv2.copyMakeBorder(img, pad, pad, pad, pad, cv2.BORDER_REFLECT)

Pad once, for the largest window, so any window up to Smax fits at every pixel. Pixel (y, x) of the image is at (y + pad, x + pad) in P.

h = s // 2
win = P[y + pad - h:y + pad + h + 1, x + pad - h:x + pad + h + 1]
z_min, z_max, z_med = int(win.min()), int(win.max()), int(np.median(win))

Cuts the current s×s window around the pixel (h = half-size) and computes the three order statistics. int() converts from uint8 so the comparisons can't wrap.

if z_min < z_med < z_max:
    out[y, x] = z_xy if z_min < z_xy < z_max else z_med
    break

Stage A is the chained comparison z_min < z_med < z_max, i.e. A1 > 0 and A2 < 0. If it passes, Stage B runs as one conditional expression: keep zxy if it is strictly between min and max, else use the median. break ends the window-growing loop for this pixel.

s += 2
if s > s_max:
    out[y, x] = z_med
    break

If Stage A fails, grow the window by 2 (keeping it odd). If it would exceed Smax, give up and output the median of the largest window, as the algorithm specifies.

median_out = cv2.medianBlur(noisy, s_init)
median_big = cv2.medianBlur(noisy, s_max)

Two fair baselines: the ordinary median at the initial size and at the maximum size. The adaptive filter should beat both.

cv2.PSNR(src1, src2, R=255.0) → float

PSNR between two same-sized images. R is the maximum pixel value (255 for 8-bit). It returns 361 (a large constant) instead of infinity for identical images.

Q2 · Otsu

p = np.bincount(img.ravel(), minlength=L) / img.size
P1 = np.cumsum(p)
m = np.cumsum(np.arange(L) * p)
mG = m[-1]

All Otsu quantities come from the histogram. P1[k] = fraction of pixels ≤ k. m[k] = Σ i·pi up to k. The last element of m is the global mean. Cumulative sums compute these for every k at once.

with np.errstate(divide="ignore", invalid="ignore"):
    sigma_b2 = (mG * P1 - m) ** 2 / (P1 * (1 - P1))
sigma_b2 = np.nan_to_num(sigma_b2)

The between-class variance formula, evaluated for all 256 values of k in one line. Where a class is empty (P1 = 0 or 1), the denominator is 0, giving 0/0 = NaN. errstate silences the warning and nan_to_num turns NaN into 0, so those k are never chosen.

k_star = int(np.round(np.mean(np.flatnonzero(sigma_b2 == sigma_b2.max()))))
eta = sigma_b2[k_star] / sigma_G2

np.flatnonzero lists every k where σB² reaches its maximum. Usually there is one; if several tie, the textbook averages them. η measures how separable the two classes are.

T_cv, seg_cv = cv2.threshold(img, 0, 255,
                     cv2.THRESH_BINARY + cv2.THRESH_OTSU)

OpenCV's Otsu. The 0 is ignored, and the computed threshold comes back as T_cv. Input must be 8-bit (or 16-bit) single-channel.

Common mistakes
  • Using ≥ / ≤ instead of strict < / > in Stages A and B: a pixel equal to zmax = 255 (salt) would be kept.
  • Padding for the initial window only: larger windows go out of bounds at the image border.
  • Uint8 subtraction for A1, A2, B1, B2: z_med − z_max on uint8 wraps to a large positive number, so the test always fails. Convert to int, or use direct comparisons as here.
  • Comparing to a median filter of a different size only: show both the initial and maximum sizes for a fair comparison.
  • Otsu: dividing by zero where P1 is 0 or 1. Handle the NaN/inf values.
  • Otsu on a colour image: convert to grayscale first.

05"What if" questions

What if the noise density is very high (60%) and Smax is too small?
60% noise
60% noise
Median 7×7 · 22.6 dB
Median 7×7 · 22.6 dB
Adaptive 3..7 · 25.2 dB
Adaptive 3..7 · 25.2 dB
Adaptive 3..11 · 26.1 dB
Adaptive 3..11 · 26.1 dB

At high density even a 7×7 window can be dominated by impulses. Stage A then fails at the maximum size, and the filter outputs a median that may itself be noise. A larger Smax lets it find enough clean pixels. The general rule: the denser the noise, the larger Smax needs to be. At low density, Smax hardly matters (both give 33.1 dB at 10%).

What if the noise is light (10%)?
10% noise
10% noise
Median 3×3 · 29.5 dB
Median 3×3 · 29.5 dB
Adaptive 3..7 · 33.1 dB
Adaptive 3..7 · 33.1 dB

Even here, where a 3×3 median removes nearly all the noise, the adaptive filter is 3.6 dB better. The ordinary median still alters the 90% of pixels that were clean, while the adaptive filter keeps them.

What if we apply both filters to a clean image (no noise)?

Median 7×7 drops to 26.3 dB (it blurs a perfect image). The adaptive median gives 33.75 dB, because almost all pixels pass Stage B and are kept. It still changes some legitimate local minima and maxima (pixels that equal their window's min or max, such as thin dark lines), so it is not perfectly lossless, but it is far less destructive.

What if the noise is Gaussian instead of salt-and-pepper?

Gaussian noise changes every pixel slightly, but only pixels that happen to be their window's min or max fail Stage B. In a test with σ = 20 noise, the filter replaced only 24% of the pixels and raised PSNR from 22.4 to 24.8 dB. The Wiener filter reached 28.8 dB on the same kind of noise in Assignment 9. The adaptive median is designed for impulse noise; for Gaussian noise use Wiener, Gaussian or bilateral filtering.

What if the initial window is already large (e.g. 7)?

With initial size 7 and Smax 7 at 30% noise, PSNR is 30.54 dB, almost the same as 3..7 (30.40 dB). Stage B still decides which pixels change, and clean pixels are kept either way. A large window contains both 0 and 255 almost every time, so zmin and zmax are the impulse values and every non-impulse pixel passes. The main costs are more computation per pixel and less ability to adapt, because there is no smaller window to try first. Starting at 3 is the usual choice.

What if the image is very noisy before Otsu?
Coins + Gaussian noise σ = 40
Coins + Gaussian noise σ = 40
Otsu directly (T = 106): speckled
Otsu directly (T = 106): speckled
7×7 Gaussian blur, then Otsu (T = 105): clean
7×7 Gaussian blur, then Otsu (T = 105): clean

The threshold barely changes (106 vs 105), but the noisy pixels near T fall on either side randomly. Smoothing first narrows each mode of the histogram, so fewer pixels sit in the overlap. This is the standard pipeline: smooth, threshold, then clean up with morphology.

What if the object is tiny compared with the background?
A small bright disc on a large noisy background
A small bright disc on a large noisy background
Otsu (T = 81): splits the background itself, 46.5% white
Otsu (T = 81): splits the background itself, 46.5% white

The disc is less than 2% of the pixels, so its mode is invisible in the histogram. Otsu sees one big mode (the background) and splits it in half. Fix: build the histogram only from pixels near strong edges (where both classes are equally represented), or use local thresholding.

What if the lighting is uneven?

A single global T fails. Part of the background is darker than part of the object (see the page.png example in Assignment 1 → What-if, where Otsu loses the shadowed text and adaptive thresholding recovers it). Alternatives: adaptive thresholding, or correct the illumination first (e.g. divide by a heavily blurred copy).

What if the image has three or more classes?

Single Otsu forces two classes and merges the middle one into one side. Multi-level Otsu maximises the between-class variance over two (or more) thresholds jointly. For cameraman it finds 87 and 176 (coat / grass / sky), as shown in the syllabus box. k-means clustering with k = 3 gives a very similar split.

06Viva / evaluation angle

30-second explanation

"For each pixel I start with the initial window and find the min, max and median. If the median is strictly between min and max, I go to Stage B: keep the pixel if it is also strictly between, otherwise output the median. If the median equals min or max, I grow the window by 2 up to Smax, and at Smax I output the median. I compare with ordinary median filters at the initial and maximum sizes using PSNR. The adaptive one wins because it only changes impulse pixels. For Otsu, I compute P1(k) and m(k) as cumulative sums of the histogram, evaluate the between-class variance for every k, take the maximum as the threshold, and binarise. It matches OpenCV's result."

What are the two stages of the adaptive median filter?

Stage A checks that the median is not an impulse (zmin < zmed < zmax), growing the window if it is. Stage B checks whether the centre pixel is an impulse: keep it if not, otherwise replace it with the median.

Why is it better than an ordinary median filter?

It adapts the window size to the local noise density and leaves non-impulse pixels unchanged, so it removes dense noise with much less blurring.

What happens when the window reaches Smax?

The filter outputs zmed of the Smax window.

How do you choose Smax?

Larger for denser noise (e.g. 7 up to 30–40%, 11+ above 50%). Larger values cost more computation.

Define PSNR and MSE.

MSE = mean of (f − f̂)². PSNR = 10·log₁₀(255²/MSE) dB; higher is better.

What PSNR values did you get?

At 30% noise: noisy 9.98, median 3×3 22.59, median 7×7 25.65, adaptive (3..7) 30.40 dB.

What does Otsu's method maximise?

The between-class variance σB² = P1·P2·(m1 − m2)², which is equivalent to minimising the within-class variance.

Why is maximising between-class variance the same as minimising within-class variance?

σG² = σW² + σB², and the global variance does not depend on k.

What is the separability measure η?

η = σB²(k*)/σG², between 0 and 1; higher means the histogram is more clearly two-class. Coins: 0.756.

Limitations of Otsu?

It assumes a bimodal histogram. It fails with heavy noise (smooth first), tiny objects, uneven illumination (use adaptive) and more than two classes (use multi-Otsu).

Global vs adaptive thresholding?

Global: one T for the whole image (mean, user, Otsu). Adaptive: T computed per pixel from its neighbourhood.

How do you clean an Otsu mask?

Morphological opening (removes small specks) and closing (fills small holes), then connected-component labelling to count objects.

Name other segmentation methods.

Region growing, split-and-merge, k-means clustering, graph cut, edge-based segmentation, texture-based segmentation and motion-based segmentation.