Digital image processing · lab reference

DIP Lab Solutions

11 assignments · 19 questions · Python reference code

Choose an assignment, then copy the complete code directly into your Python environment or Jupyter notebook. Each question includes its own setup.

Installation & reference notes

Install the packages below for Assignments 1–10. Assignment 11 additionally requires PyTorch, torchvision, Pillow and scikit-learn; training requires dataset and model downloads.

pip install numpy opencv-python matplotlib scipy scikit-image

Adapted from the supplied notebooks and assignment sheets. Student identifiers were omitted, random seeds changed to 42, and multi-question code was split into standalone examples. Review notes identify remaining requirement ambiguities. Assignment 11 tasks come from the notebook, not a question sheet.

Assignment 01 / Grayscale to binary thresholding

QUESTION 01 · PYTHON

Grayscale to binary

Convert a grayscale image to binary using (1) mean intensity and (2) a user-defined threshold.

View complete code · 56 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

mean_threshold = float(gray.mean())
user_threshold = ask('Binary threshold, 0 to 255', int, 110)
if not 0 <= user_threshold <= 255:
    raise ValueError('Threshold must be between 0 and 255')
binary_mean = np.where(gray >= mean_threshold, 255, 0).astype(np.uint8)
binary_user = np.where(gray >= user_threshold, 255, 0).astype(np.uint8)
save_grid(1, [('Grayscale input', gray),
              (f'Mean threshold = {mean_threshold:.2f}', binary_mean),
              (f'User threshold = {user_threshold}', binary_user)])
metrics['1'] = {'mean_intensity': round(mean_threshold, 2), 'user_threshold': user_threshold,
                'mean_white_percent': round(100 * np.mean(binary_mean == 255), 2),
                'user_white_percent': round(100 * np.mean(binary_user == 255), 2)}
print('Assignment 1:', metrics['1'])

Assignment 02 / RGB to grayscale conversion

QUESTION 01 · PYTHON

RGB to grayscale

Convert an RGB image to grayscale using (1) the mean of three planes and (2) user-defined R, G and B weights between 0 and 1 whose sum is 1.

View complete code · 54 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

weights = [ask(f'{channel} weight (0 to 1)', float, default)
           for channel, default in zip('RGB', (0.7, 0.2, 0.1))]
if any(not 0 <= w <= 1 for w in weights) or not np.isclose(sum(weights), 1):
    raise ValueError('Each weight must be in [0,1] and weights must sum to 1')
mean_gray = rgb.mean(axis=2).round().astype(np.uint8)
weighted_gray = np.tensordot(rgb.astype(float), weights, axes=([2], [0])).round().astype(np.uint8)
save_grid(2, [('RGB input', rgb), ('Mean of RGB planes', mean_gray),
              (f'Weighted RGB {weights}', weighted_gray)])
metrics['2'] = {'weights': weights, 'mean_gray_average': round(float(mean_gray.mean()), 2),
                'weighted_gray_average': round(float(weighted_gray.mean()), 2)}
print('Assignment 2:', metrics['2'])

Assignment 03 / Image padding and complement

QUESTION 01 · PYTHON

Image padding

Draw a border around both binary and grayscale images. Obtain the border width and color from the user.

View complete code · 55 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

border_width = ask('Border width in pixels', int, 20)
gray_border = ask('Grayscale border value, 0 to 255', int, 180)
binary_border = ask('Binary border value, 0 or 255', int, 255)
if border_width < 0 or not 0 <= gray_border <= 255 or binary_border not in (0, 255):
    raise ValueError('Invalid border width or color')
binary = (gray >= gray.mean()).astype(np.uint8) * 255
padded_gray = cv2.copyMakeBorder(gray, border_width, border_width, border_width,
                                 border_width, cv2.BORDER_CONSTANT, value=gray_border)
padded_binary = cv2.copyMakeBorder(binary, border_width, border_width, border_width,
                                   border_width, cv2.BORDER_CONSTANT, value=binary_border)

save_grid('3_padding', [('Grayscale input', gray), ('Grayscale with border', padded_gray), ('Binary input', binary), ('Binary with border', padded_binary)], cols=2)
QUESTION 02 · PYTHON

Image complement

Find the complement of binary and grayscale images.

View complete code · 47 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

binary = (gray >= gray.mean()).astype(np.uint8) * 255
gray_complement = 255 - gray
binary_complement = 255 - binary
save_grid('3_complement', [('Grayscale input', gray), ('Grayscale complement', gray_complement), ('Binary input', binary), ('Binary complement', binary_complement)], cols=2)

Assignment 04 / Intensity transforms and contrast stretching

QUESTION 01 · PYTHON

Log transformation

Enhance an input image using log transformation with c = 1.

The mathematical transform and display normalization are shown separately.

View complete code · 48 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

unit = gray.astype(np.float64) / 255
c = 1
log_result = c * np.log1p(unit)
log_image = np.uint8(np.rint(255 * log_result / np.log(2)))
save_grid('4_log', [('Grayscale input', gray), ('Log transform, c=1', log_image)], cols=2)
QUESTION 02 · PYTHON

Gamma transformation

Enhance an input image using power-law transformation with c = 1 and user-defined gamma.

View complete code · 49 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

gamma = ask('Gamma value, positive', float, 0.6)
if gamma <= 0:
    raise ValueError('Gamma must be positive')
unit = gray.astype(np.float64) / 255
gamma_image = np.uint8(np.rint(255 * unit ** gamma))             # c=1 on normalized intensity
save_grid('4_gamma', [('Grayscale input', gray), (f'Gamma transform, gamma={gamma}', gamma_image)], cols=2)
QUESTION 03 · PYTHON

Contrast stretching

Obtain the input and desired output intensity ranges from the user and stretch the selected range (for example 80–120 to 50–150).

Endpoint handling adjusted to avoid repeated interpolation points.

View complete code · 58 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

in_low = ask('Input range lower value', int, 80)
in_high = ask('Input range upper value', int, 120)
out_low = ask('Output range lower value', int, 50)
out_high = ask('Output range upper value', int, 150)
if not (0 <= in_low < in_high <= 255 and 0 <= out_low < out_high <= 255):
    raise ValueError('Use valid ascending intensity ranges')
xp, fp = [in_low, in_high], [out_low, out_high]
if in_low > 0:
    xp.insert(0, 0)
    fp.insert(0, 0)
if in_high < 255:
    xp.append(255)
    fp.append(255)
stretched = np.interp(gray, xp, fp).round().astype(np.uint8)
save_grid('4_stretch', [('Grayscale input', gray), ('Contrast stretched', stretched)], cols=2)

Assignment 05 / Histogram equalization and matching

QUESTION 01 · PYTHON

Histogram equalization

Enhance the contrast of a grayscale image using histogram equalization. Display the original and equalized images.

View complete code · 46 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

equalized = exposure.equalize_hist(gray)
equalized_u8 = np.uint8(np.rint(equalized * 255))
save_grid('5_equalization', [('Input image', gray), ('Equalized image', equalized_u8)], cols=2)
QUESTION 02 · PYTHON

Histogram matching

Match the histogram of the input image to that of a reference image using histogram equalization.

View complete code · 53 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

matched = exposure.match_histograms(gray, reference)
matched_u8 = np.uint8(np.rint(np.clip(matched, 0, 255)))
save_grid('5_matching', [('Input image', gray), ('Reference image', reference), ('Histogram matched image', matched_u8)])
fig, ax = plt.subplots(figsize=(8, 3))
for label, image in [('Input', gray), ('Reference', reference), ('Matched', matched_u8)]:
    ax.plot(np.arange(256), np.histogram(image, bins=256, range=(0, 256), density=True)[0], label=label)
ax.set(xlabel='Pixel intensity', ylabel='Probability', title='Intensity histograms')
ax.legend()
fig.tight_layout()
plt.show()

Assignment 06 / Smoothing filters

QUESTION 01 · PYTHON

Smoothing filters

Smooth an image using unweighted averaging, weighted averaging and Gaussian filters. Obtain filter size, sigma and padding method from the user.

The supplied solution interprets the ambiguous weighted-filter formula as max(|x|, |y|). Confirm this interpretation before sharing as a definitive answer.

View complete code · 63 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

size = ask('Odd filter size', int, 5)
sigma = ask('Gaussian sigma, positive', float, 1.2)
padding = ask('Padding: reflect, replicate, or zero', str, 'reflect').lower()
if size < 3 or size % 2 != 1 or sigma <= 0 or padding not in ('reflect', 'replicate', 'zero'):
    raise ValueError('Choose odd size >=3, positive sigma, and a listed padding method')
border_type = {'reflect': cv2.BORDER_REFLECT_101, 'replicate': cv2.BORDER_REPLICATE,
               'zero': cv2.BORDER_CONSTANT}[padding]
average_kernel = np.ones((size, size), np.float32) / (size * size)
coords = np.arange(-(size // 2), size // 2 + 1)
xx, yy = np.meshgrid(coords, coords)
weighted_kernel = np.maximum(np.abs(xx), np.abs(yy)).astype(np.float32)
weighted_kernel /= weighted_kernel.sum()  # h(x,y)=max(|x|,|y|), normalized
average_image = cv2.filter2D(gray, -1, average_kernel, borderType=border_type)
weighted_image = cv2.filter2D(gray, -1, weighted_kernel, borderType=border_type)
gaussian_image = cv2.GaussianBlur(gray, (size, size), sigmaX=sigma, borderType=border_type)
save_grid(6, [('Input image', gray), ('Averaging filter', average_image),
              ('Weighted filter', weighted_image), ('Gaussian filter', gaussian_image)], cols=2)
metrics['6'] = {'size': size, 'sigma': sigma, 'padding': padding,
                'kernel_sum': round(float(weighted_kernel.sum()), 6)}
print('Assignment 6:', metrics['6'])

Assignment 07 / Sharpening and edge detection

QUESTION 01 · PYTHON

Image sharpening

Sharpen an image using Laplacian, Sobel and Canny edge detection, and unsharp masking (Gaussian filter 5 × 5, sigma = 3).

Added Sobel and Canny edge-map enhancement to the supplied solution; Canny enhancement is edge addition rather than a conventional sharpening filter.

View complete code · 60 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

laplacian = cv2.Laplacian(gray, cv2.CV_64F, ksize=3)
laplacian_sharp = np.clip(gray.astype(float) - laplacian, 0, 255).astype(np.uint8)
sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
sobel_edges = np.clip(np.hypot(sobel_x, sobel_y), 0, 255).astype(np.uint8)
canny_edges = cv2.Canny(gray, 80, 160)
sobel_sharp = np.clip(gray.astype(float) + 0.5 * sobel_edges, 0, 255).astype(np.uint8)
canny_sharp = np.clip(gray.astype(float) + 0.3 * canny_edges, 0, 255).astype(np.uint8)
blur_5x5 = cv2.GaussianBlur(gray, (5, 5), sigmaX=3)
unsharp = np.clip(2 * gray.astype(float) - blur_5x5, 0, 255).astype(np.uint8)
save_grid(7, [('Input', gray), ('Laplacian sharpened', laplacian_sharp),
              ('Sobel gradient magnitude', sobel_edges), ('Sobel sharpened', sobel_sharp),
              ('Canny edges', canny_edges), ('Canny enhanced', canny_sharp),
              ('Gaussian blurred 5x5 sigma=3', blur_5x5), ('Unsharp masking', unsharp)])
metrics['7'] = {'canny_edge_percent': round(float(100 * np.mean(canny_edges > 0)), 2),
                'unsharp_std': round(float(unsharp.std()), 2)}
print('Assignment 7:', metrics['7'])

Assignment 08 / Noise distributions

QUESTION 01 · PYTHON

Noise distributions

Generate uniform, Gaussian, Erlang, exponential and Rayleigh noise using distribution equations, compare with built-in noise generation and plot histograms.

The original question specifically requests MATLAB imnoise. This Python solution compares with NumPy distribution generators; it is not a literal imnoise implementation. MATLAB imnoise does not directly support all five distributions. Confirm Python is accepted.

View complete code · 84 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

n = gray.size
u = rng.random(n)
u2 = rng.random(n)
generated = {
    'Uniform': -1 + 2 * u,
    'Gaussian': np.sqrt(-2 * np.log(np.clip(u, 1e-12, 1))) * np.cos(2 * np.pi * u2),
    'Erlang k=3': -np.log(np.clip(rng.random((3, n)), 1e-12, 1)).sum(axis=0),
    'Exponential': -np.log1p(-u),
    'Rayleigh': np.sqrt(-2 * np.log1p(-u)),
}
reference_noise = {
    'Uniform': rng.uniform(-1, 1, n),
    'Gaussian': rng.normal(0, 1, n),
    'Erlang k=3': rng.gamma(3, 1, n),
    'Exponential': rng.exponential(1, n),
    'Rayleigh': rng.rayleigh(1, n),
}
fig, axes = plt.subplots(5, 2, figsize=(10, 15))
noise_stats = {}
for i, name in enumerate(generated):
    values, built_in = generated[name], reference_noise[name]
    upper = np.percentile(np.r_[values, built_in], 99.5)
    lower = min(0, float(np.percentile(values, 0.5)))
    axes[i, 0].hist(values, bins=70, range=(lower, upper), density=True, alpha=.55, label='Inverse-CDF / equation')
    axes[i, 0].hist(built_in, bins=70, range=(lower, upper), density=True, alpha=.45, label='NumPy built-in')
    axes[i, 0].set_title(f'{name} distribution')
    axes[i, 0].legend(fontsize=7)
    sample = values[:gray.size].reshape(gray.shape)
    sample = (sample - sample.mean()) / sample.std()
    noisy = np.clip(gray.astype(float) + 25 * sample, 0, 255).astype(np.uint8)
    axes[i, 1].imshow(noisy, cmap='gray', vmin=0, vmax=255)
    axes[i, 1].set_title(f'Image with {name} noise')
    axes[i, 1].axis('off')
    noise_stats[name] = {'generated_mean': round(float(values.mean()), 3),
                         'built_in_mean': round(float(built_in.mean()), 3)}
fig.tight_layout()
fig.savefig(OUT / 'assignment_8.png', dpi=150)
show_inline()
plt.close(fig)
metrics['8'] = noise_stats
print('Assignment 8:', metrics['8'])

Assignment 09 / Local binary pattern and denoising

QUESTION 01 · PYTHON

Local binary pattern

Implement local binary pattern (LBP) on a grayscale image.

Includes conventional LBP alongside the supplied uniform LBP variant.

View complete code · 46 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

lbp = local_binary_pattern(gray, P=8, R=1, method='default').astype(np.uint8)
uniform = local_binary_pattern(gray, P=8, R=1, method='uniform')
save_grid('9_lbp', [('Grayscale input', gray), ('Conventional LBP', lbp), ('Uniform LBP', uniform / max(1, uniform.max()) * 255)])
QUESTION 02 · PYTHON

Noise removal filters

Denoise images corrupted by Gaussian and speckle noise using Wiener, median, Gaussian and bilateral filters (3 × 3 or 5 × 5).

View complete code · 67 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

gray_unit = gray.astype(np.float64) / 255
noise_cases = {'Gaussian': np.clip(gray_unit + rng.normal(0, .08, gray.shape), 0, 1),
               'Speckle': np.clip(gray_unit * (1 + rng.normal(0, .20, gray.shape)), 0, 1)}
fig, axes = plt.subplots(2, 6, figsize=(18, 6))
scores = {}
for row, (name, noisy) in enumerate(noise_cases.items()):
    noisy_u8 = np.uint8(np.rint(noisy * 255))
    filtered = {'Wiener': np.clip(wiener(noisy_u8.astype(float), (5, 5)), 0, 255).astype(np.uint8),
                'Median': cv2.medianBlur(noisy_u8, 5),
                'Gaussian': cv2.GaussianBlur(noisy_u8, (5, 5), 1.0),
                'Bilateral': cv2.bilateralFilter(noisy_u8, 5, 50, 50)}
    panels = [('Noisy', noisy_u8), *filtered.items(), ('Original', gray)]
    for col, (title, image) in enumerate(panels):
        axes[row, col].imshow(image, cmap='gray', vmin=0, vmax=255)
        axes[row, col].set_title(f'{name}: {title}', fontsize=9)
        axes[row, col].axis('off')
    scores[name] = {'Noisy': round(psnr(gray, noisy_u8, data_range=255), 2),
                    **{k: round(psnr(gray, v, data_range=255), 2) for k, v in filtered.items()}}
fig.tight_layout()
fig.savefig(OUT / 'assignment_9_denoising.png', dpi=150)
show_inline()
plt.close(fig)
metrics['9'] = scores
print('Assignment 9:', metrics['9'])

Assignment 10 / Adaptive median and Otsu thresholding

QUESTION 01 · PYTHON

Adaptive median filtering

Denoise an image using an adaptive median filter. Obtain the initial window and Smax from the user and compare with fixed median filtering using PSNR.

View complete code · 78 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

initial_size = ask('Initial adaptive median window size (odd)', int, 3)
smax = ask('Maximum adaptive median window size (odd)', int, 7)
if initial_size < 3 or smax < initial_size or initial_size % 2 != 1 or smax % 2 != 1:
    raise ValueError('Window sizes must be odd, >=3, and Smax >= initial size')

def adaptive_median(image, initial, maximum):
    pad = maximum // 2
    padded = np.pad(image, pad, mode='edge')
    result = image.copy()
    for y in range(image.shape[0]):
        for x in range(image.shape[1]):
            zxy = int(image[y, x])
            value = zxy
            for size_now in range(initial, maximum + 1, 2):
                r = size_now // 2
                window = padded[y + pad - r:y + pad + r + 1,
                                x + pad - r:x + pad + r + 1]
                zmin, zmax, zmed = int(window.min()), int(window.max()), int(np.median(window))
                if zmin < zmed < zmax:           # Stage A: useful median found
                    value = zxy if zmin < zxy < zmax else zmed  # Stage B
                    break
                value = zmed                     # use largest-window median if needed
            result[y, x] = value
    return result

small = cv2.resize(gray, (256, 256), interpolation=cv2.INTER_AREA)
salt_pepper = small.copy()
mask = rng.random(small.shape)
salt_pepper[mask < .05] = 0
salt_pepper[mask > .95] = 255
median_restored = cv2.medianBlur(salt_pepper, initial_size)
adaptive_restored = adaptive_median(salt_pepper, initial_size, smax)
save_grid('10_adaptive', [('Original', small), ('Salt and pepper noise', salt_pepper), ('Fixed median filter', median_restored), ('Adaptive median filter', adaptive_restored)], cols=2)
for name, image in [('Noisy', salt_pepper), ('Fixed median', median_restored), ('Adaptive median', adaptive_restored)]:
    print(name, 'PSNR:', round(psnr(small, image, data_range=255), 2), 'dB')
QUESTION 02 · PYTHON

Otsu thresholding

Segment a grayscale image using Otsu’s global threshold.

View complete code · 46 lines
from pathlib import Path
import json
import numpy as np
import cv2
import matplotlib.pyplot as plt
from scipy.signal import wiener
from skimage import data, exposure
from skimage.feature import local_binary_pattern
from skimage.metrics import peak_signal_noise_ratio as psnr

OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
gray = data.camera()                 # 512 x 512 grayscale sample image
rgb = data.astronaut()               # 512 x 512 RGB sample image
reference = cv2.cvtColor(data.coffee(), cv2.COLOR_RGB2GRAY)
rng = np.random.default_rng(42)
metrics = {}

def show_inline():
    plt.show()

def ask(prompt, cast, default):
    try:
        raw = input(f'{prompt} [{default}]: ').strip()
    except EOFError:
        raw = ''
    return cast(raw) if raw else default

def save_grid(number, panels, cols=3, cmap='gray', figsize=None):
    rows = int(np.ceil(len(panels) / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize or (4 * cols, 3.5 * rows))
    axes = np.array(axes).reshape(-1)
    for ax, (title, image) in zip(axes, panels):
        ax.imshow(image, cmap=None if image.ndim == 3 else cmap, vmin=0 if image.ndim == 2 else None, vmax=255 if image.ndim == 2 else None)
        ax.set_title(title, fontsize=10)
        ax.axis('off')
    for ax in axes[len(panels):]:
        ax.axis('off')
    fig.tight_layout()
    fig.savefig(OUT / f'assignment_{number}.png', dpi=150, bbox_inches='tight')
    show_inline()
    plt.close(fig)

otsu_t, otsu_mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
save_grid('10_otsu', [('Original grayscale', gray), (f'Otsu threshold = {otsu_t:.0f}', otsu_mask)], cols=2)
print('Otsu threshold:', int(otsu_t))

Assignment 11 / CNN and transfer learning comparison

QUESTION 01 · PYTHON

CNN matrix operations

Notebook task 1: CNN operations on a 3 × 3 matrix.

Assignment 11 question sheet was not supplied. Task titles are from the notebook; training has not been verified.

View complete code · 52 lines
from pathlib import Path
import io
import json
import zipfile
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from torchvision.models import (vgg16, VGG16_Weights,
                                mobilenet_v2, MobileNet_V2_Weights,
                                resnet18, ResNet18_Weights)

SEED = 42
np.random.seed(SEED % (2**32))
torch.manual_seed(SEED)
torch.set_num_threads(min(6, torch.get_num_threads()))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
torch.hub.set_dir(str((OUT / 'torch_cache').resolve()))

def show_inline():
    plt.show()

matrix = torch.randint(0, 10, (1, 1, 3, 3)).float()
kernel = torch.tensor([[[[1., 0., -1.], [1., 0., -1.], [1., 0., -1.]]]])
convolution = nn.functional.conv2d(matrix, kernel, padding=1)  # CNN cross-correlation convention
relu = nn.ReLU()(convolution)
sigmoid = nn.Sigmoid()(convolution)
max_pool = nn.functional.max_pool2d(matrix, 2)
min_pool = -nn.functional.max_pool2d(-matrix, 2)
global_avg = nn.functional.adaptive_avg_pool2d(matrix, 1)
flat = nn.Flatten()(matrix)
dense = nn.Linear(9, 3)(flat)
batch_norm = nn.BatchNorm1d(3)(torch.cat([dense, dense + 1], dim=0))
dropout = nn.Dropout(p=.25)(dense)
for name, tensor in [('matrix', matrix), ('convolution with P=1', convolution),
                     ('ReLU', relu), ('sigmoid', sigmoid), ('max pool', max_pool),
                     ('min pool', min_pool), ('global average pool', global_avg),
                     ('flatten', flat), ('dense', dense), ('batch norm', batch_norm),
                     ('dropout', dropout)]:
    print(name, '=', tensor.detach().numpy().round(3).tolist())
fig, axes = plt.subplots(1, 4, figsize=(10, 3))
for ax, (title, tensor) in zip(axes, [('Input 3x3', matrix), ('Padded convolution', convolution),
                                      ('ReLU', relu), ('Sigmoid', sigmoid)]):
    ax.imshow(tensor[0, 0].detach().numpy(), cmap='viridis')
    ax.set_title(title)
    ax.set_xticks([]); ax.set_yticks([])
fig.tight_layout(); fig.savefig(OUT / 'assignment_11_matrix.png', dpi=150); show_inline(); plt.close(fig)
QUESTION 02 · PYTHON

Custom CNN

Notebook task 2: Custom CNN and overfitting analysis.

Requires Tiny ImageNet download and PyTorch; training not rerun.

View complete code · 134 lines
from pathlib import Path
import io
import json
import zipfile
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from torchvision.models import (vgg16, VGG16_Weights,
                                mobilenet_v2, MobileNet_V2_Weights,
                                resnet18, ResNet18_Weights)

SEED = 42
np.random.seed(SEED % (2**32))
torch.manual_seed(SEED)
torch.set_num_threads(min(6, torch.get_num_threads()))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
torch.hub.set_dir(str((OUT / 'torch_cache').resolve()))

def show_inline():
    plt.show()

ZIP = Path('work/tiny-imagenet-200.zip') if Path('work').exists() else Path('tiny-imagenet-200.zip')
if not ZIP.exists():
    from urllib.request import urlretrieve
    urlretrieve('http://cs231n.stanford.edu/tiny-imagenet-200.zip', ZIP)

with zipfile.ZipFile(ZIP) as z:
    wnids = z.read('tiny-imagenet-200/wnids.txt').decode().splitlines()
    selected = wnids[:3]  # fixed three classes, 200 images each
    words = dict(line.split('\t', 1) for line in z.read('tiny-imagenet-200/words.txt').decode().splitlines())
    labels = [words[w].split(',')[0] for w in selected]
    arrays, targets = [], []
    for class_index, wnid in enumerate(selected):
        paths = sorted(p for p in z.namelist() if p.startswith(f'tiny-imagenet-200/train/{wnid}/images/') and p.endswith('.JPEG'))[:200]
        if len(paths) != 200:
            raise ValueError(f'Expected 200 images for {wnid}, found {len(paths)}')
        for path in paths:
            with Image.open(io.BytesIO(z.read(path))) as image:
                arrays.append(np.asarray(image.convert('RGB').resize((64, 64)), dtype=np.uint8))
            targets.append(class_index)
images = np.stack(arrays)
targets = np.asarray(targets)
assert images.shape == (600, 64, 64, 3)

# 70/15/15 stratified split: 140/30/30 per class.
split_rng = np.random.default_rng(SEED)
train_ids, val_ids, test_ids = [], [], []
for cls in range(3):
    ids = split_rng.permutation(np.where(targets == cls)[0])
    train_ids.extend(ids[:140]); val_ids.extend(ids[140:170]); test_ids.extend(ids[170:200])
train_ids = np.array(train_ids); val_ids = np.array(val_ids); test_ids = np.array(test_ids)
pixels = torch.from_numpy(images.copy()).permute(0, 3, 1, 2).float() / 255
y = torch.from_numpy(targets).long()
mean = torch.tensor([0.485, 0.456, 0.406])[None, :, None, None]
std = torch.tensor([0.229, 0.224, 0.225])[None, :, None, None]
pixels_imagenet = (pixels - mean) / std
print('Selected classes:', list(zip(selected, labels)))
print('Dataset shape:', images.shape, 'Split:', len(train_ids), len(val_ids), len(test_ids))

def make_loader(x, ids, shuffle=False, batch_size=32):
    return DataLoader(TensorDataset(x[ids], y[ids]), batch_size=batch_size, shuffle=shuffle)

def train_model(model, train_loader, val_loader, epochs=12, patience=3, lr=1e-3):
    model.to(DEVICE)
    optimizer = torch.optim.Adam((p for p in model.parameters() if p.requires_grad), lr=lr)
    loss_fn = nn.CrossEntropyLoss()
    history = {'train_loss': [], 'val_loss': []}
    best_loss, stale, best_state = float('inf'), 0, None
    for epoch in range(epochs):
        model.train(); running = count = 0
        for xb, yb in train_loader:
            xb, yb = xb.to(DEVICE), yb.to(DEVICE)
            optimizer.zero_grad()
            loss = loss_fn(model(xb), yb)
            loss.backward(); optimizer.step()
            running += loss.item() * len(xb); count += len(xb)
        history['train_loss'].append(running / count)
        model.eval(); running = count = 0
        with torch.no_grad():
            for xb, yb in val_loader:
                xb, yb = xb.to(DEVICE), yb.to(DEVICE)
                running += loss_fn(model(xb), yb).item() * len(xb); count += len(xb)
        val_loss = running / count
        history['val_loss'].append(val_loss)
        print(f'Epoch {epoch+1}: train loss={history["train_loss"][-1]:.4f}, val loss={val_loss:.4f}', flush=True)
        if val_loss < best_loss - 1e-4:
            best_loss, stale = val_loss, 0
            best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
        else:
            stale += 1
            if stale >= patience:
                print('Early stopping')
                break
    model.load_state_dict(best_state)
    return model, history

def evaluate(model, loader):
    model.eval(); predicted = []; actual = []
    with torch.no_grad():
        for xb, yb in loader:
            predicted.extend(model(xb.to(DEVICE)).argmax(1).cpu().tolist())
            actual.extend(yb.tolist())
    p, r, f, _ = precision_recall_fscore_support(actual, predicted, average='macro', zero_division=0)
    return {'accuracy': round(accuracy_score(actual, predicted), 4),
            'precision': round(p, 4), 'recall': round(r, 4), 'f1': round(f, 4)}

class CustomCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 16, 3, padding=1), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(2),
            nn.Conv2d(16, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2),
            nn.AdaptiveAvgPool2d((1, 1)))
        self.classifier = nn.Sequential(nn.Flatten(), nn.Dropout(.3), nn.Linear(64, 3))
    def forward(self, x):
        return self.classifier(self.features(x))

custom, history = train_model(CustomCNN(), make_loader(pixels, train_ids, True),
                              make_loader(pixels, val_ids), epochs=12, patience=3)
results = {'Custom CNN': evaluate(custom, make_loader(pixels, test_ids))}
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(np.arange(1, len(history['train_loss']) + 1), history['train_loss'], marker='o', label='Training')
ax.plot(np.arange(1, len(history['val_loss']) + 1), history['val_loss'], marker='o', label='Validation')
ax.set(xlabel='Epoch', ylabel='Cross-entropy loss', title='Custom CNN learning curves')
ax.legend(); ax.grid(alpha=.25)
fig.tight_layout(); fig.savefig(OUT / 'assignment_11_loss_curves.png', dpi=150); show_inline(); plt.close(fig)
print('Custom CNN test metrics:', results['Custom CNN'])
QUESTION 03 · PYTHON

Transfer learning

Notebook task 3: Compare transfer learning models VGG16, MobileNetV2 and ResNet18 with a custom CNN.

Includes the custom CNN baseline; downloads pretrained weights and trains models. Training not rerun.

View complete code · 190 lines
from pathlib import Path
import io
import json
import zipfile
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from torchvision.models import (vgg16, VGG16_Weights,
                                mobilenet_v2, MobileNet_V2_Weights,
                                resnet18, ResNet18_Weights)

SEED = 42
np.random.seed(SEED % (2**32))
torch.manual_seed(SEED)
torch.set_num_threads(min(6, torch.get_num_threads()))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
torch.hub.set_dir(str((OUT / 'torch_cache').resolve()))

def show_inline():
    plt.show()

ZIP = Path('work/tiny-imagenet-200.zip') if Path('work').exists() else Path('tiny-imagenet-200.zip')
if not ZIP.exists():
    from urllib.request import urlretrieve
    urlretrieve('http://cs231n.stanford.edu/tiny-imagenet-200.zip', ZIP)

with zipfile.ZipFile(ZIP) as z:
    wnids = z.read('tiny-imagenet-200/wnids.txt').decode().splitlines()
    selected = wnids[:3]  # fixed three classes, 200 images each
    words = dict(line.split('\t', 1) for line in z.read('tiny-imagenet-200/words.txt').decode().splitlines())
    labels = [words[w].split(',')[0] for w in selected]
    arrays, targets = [], []
    for class_index, wnid in enumerate(selected):
        paths = sorted(p for p in z.namelist() if p.startswith(f'tiny-imagenet-200/train/{wnid}/images/') and p.endswith('.JPEG'))[:200]
        if len(paths) != 200:
            raise ValueError(f'Expected 200 images for {wnid}, found {len(paths)}')
        for path in paths:
            with Image.open(io.BytesIO(z.read(path))) as image:
                arrays.append(np.asarray(image.convert('RGB').resize((64, 64)), dtype=np.uint8))
            targets.append(class_index)
images = np.stack(arrays)
targets = np.asarray(targets)
assert images.shape == (600, 64, 64, 3)

# 70/15/15 stratified split: 140/30/30 per class.
split_rng = np.random.default_rng(SEED)
train_ids, val_ids, test_ids = [], [], []
for cls in range(3):
    ids = split_rng.permutation(np.where(targets == cls)[0])
    train_ids.extend(ids[:140]); val_ids.extend(ids[140:170]); test_ids.extend(ids[170:200])
train_ids = np.array(train_ids); val_ids = np.array(val_ids); test_ids = np.array(test_ids)
pixels = torch.from_numpy(images.copy()).permute(0, 3, 1, 2).float() / 255
y = torch.from_numpy(targets).long()
mean = torch.tensor([0.485, 0.456, 0.406])[None, :, None, None]
std = torch.tensor([0.229, 0.224, 0.225])[None, :, None, None]
pixels_imagenet = (pixels - mean) / std
print('Selected classes:', list(zip(selected, labels)))
print('Dataset shape:', images.shape, 'Split:', len(train_ids), len(val_ids), len(test_ids))

def make_loader(x, ids, shuffle=False, batch_size=32):
    return DataLoader(TensorDataset(x[ids], y[ids]), batch_size=batch_size, shuffle=shuffle)

def train_model(model, train_loader, val_loader, epochs=12, patience=3, lr=1e-3):
    model.to(DEVICE)
    optimizer = torch.optim.Adam((p for p in model.parameters() if p.requires_grad), lr=lr)
    loss_fn = nn.CrossEntropyLoss()
    history = {'train_loss': [], 'val_loss': []}
    best_loss, stale, best_state = float('inf'), 0, None
    for epoch in range(epochs):
        model.train(); running = count = 0
        for xb, yb in train_loader:
            xb, yb = xb.to(DEVICE), yb.to(DEVICE)
            optimizer.zero_grad()
            loss = loss_fn(model(xb), yb)
            loss.backward(); optimizer.step()
            running += loss.item() * len(xb); count += len(xb)
        history['train_loss'].append(running / count)
        model.eval(); running = count = 0
        with torch.no_grad():
            for xb, yb in val_loader:
                xb, yb = xb.to(DEVICE), yb.to(DEVICE)
                running += loss_fn(model(xb), yb).item() * len(xb); count += len(xb)
        val_loss = running / count
        history['val_loss'].append(val_loss)
        print(f'Epoch {epoch+1}: train loss={history["train_loss"][-1]:.4f}, val loss={val_loss:.4f}', flush=True)
        if val_loss < best_loss - 1e-4:
            best_loss, stale = val_loss, 0
            best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
        else:
            stale += 1
            if stale >= patience:
                print('Early stopping')
                break
    model.load_state_dict(best_state)
    return model, history

def evaluate(model, loader):
    model.eval(); predicted = []; actual = []
    with torch.no_grad():
        for xb, yb in loader:
            predicted.extend(model(xb.to(DEVICE)).argmax(1).cpu().tolist())
            actual.extend(yb.tolist())
    p, r, f, _ = precision_recall_fscore_support(actual, predicted, average='macro', zero_division=0)
    return {'accuracy': round(accuracy_score(actual, predicted), 4),
            'precision': round(p, 4), 'recall': round(r, 4), 'f1': round(f, 4)}

class CustomCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 16, 3, padding=1), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(2),
            nn.Conv2d(16, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2),
            nn.AdaptiveAvgPool2d((1, 1)))
        self.classifier = nn.Sequential(nn.Flatten(), nn.Dropout(.3), nn.Linear(64, 3))
    def forward(self, x):
        return self.classifier(self.features(x))

custom, history = train_model(CustomCNN(), make_loader(pixels, train_ids, True),
                              make_loader(pixels, val_ids), epochs=12, patience=3)
results = {'Custom CNN': evaluate(custom, make_loader(pixels, test_ids))}
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(np.arange(1, len(history['train_loss']) + 1), history['train_loss'], marker='o', label='Training')
ax.plot(np.arange(1, len(history['val_loss']) + 1), history['val_loss'], marker='o', label='Validation')
ax.set(xlabel='Epoch', ylabel='Cross-entropy loss', title='Custom CNN learning curves')
ax.legend(); ax.grid(alpha=.25)
fig.tight_layout(); fig.savefig(OUT / 'assignment_11_loss_curves.png', dpi=150); show_inline(); plt.close(fig)
print('Custom CNN test metrics:', results['Custom CNN'])

def transfer_backbone(name):
    if name == 'VGG16':
        model = vgg16(weights=VGG16_Weights.DEFAULT)
        model.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        dimension = 512
    elif name == 'MobileNetV2':
        model = mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT)
        dimension = 1280
    elif name == 'ResNet18':
        model = resnet18(weights=ResNet18_Weights.DEFAULT)
        dimension = 512
    return model.to(DEVICE).eval(), dimension

def frozen_features(model, name, x, batch_size=32):
    chunks = []
    resnet_body = nn.Sequential(*list(model.children())[:-1]) if name == 'ResNet18' else None
    with torch.no_grad():
        for batch in x.split(batch_size):
            batch = batch.to(DEVICE)
            if name == 'VGG16':
                feature = model.avgpool(model.features(batch)).flatten(1)
            elif name == 'MobileNetV2':
                feature = nn.functional.adaptive_avg_pool2d(model.features(batch), 1).flatten(1)
            else:
                feature = resnet_body(batch).flatten(1)
            chunks.append(feature.cpu())
    return torch.cat(chunks)

for name in ('VGG16', 'MobileNetV2', 'ResNet18'):
    print('Training', name, flush=True)
    backbone, dimension = transfer_backbone(name)
    features = frozen_features(backbone, name, pixels_imagenet)
    del backbone
    if torch.cuda.is_available():
        torch.cuda.empty_cache()
    head, model_history = train_model(nn.Linear(dimension, 3),
        make_loader(features, train_ids, True), make_loader(features, val_ids),
        epochs=30, patience=4, lr=1e-3)
    results[name] = evaluate(head, make_loader(features, test_ids))
    print(name, 'test metrics:', results[name], flush=True)
    del head, features

fig, ax = plt.subplots(figsize=(8, 4))
names = list(results)
for j, metric in enumerate(('accuracy', 'precision', 'recall', 'f1')):
    ax.bar(np.arange(len(names)) + (j - 1.5) * .18, [results[n][metric] for n in names],
           width=.18, label=metric.title())
ax.set_xticks(np.arange(len(names)), names)
ax.set(ylim=(0, 1), ylabel='Score', title='Test set comparison, 90 images')
ax.legend(ncol=4, loc='upper center', fontsize=8)
fig.tight_layout(); fig.savefig(OUT / 'assignment_11_comparison.png', dpi=150); show_inline(); plt.close(fig)
(OUT / 'metrics_11.json').write_text(json.dumps({'selected_wnids': selected, 'class_names': labels,
    'split': {'train': 420, 'validation': 90, 'test': 90},
    'custom_history': history, 'results': results}, indent=2))
print('Final comparison:', results)