practice problems

Dec 3, 2026
β€’
12 min read
β€’
2419 words

Core Algorithmic Implementations Across Experiments

Course: Image and Video Processing Lab (EC39028)
Author: Utsab Karan (23EC39028)


Experiment 1: Custom Interpolation, Scaling & Rotation

1. Scaling (Nearest Neighbor & Bilinear)

Always use inverse mapping: iterate over the target image grid and look up corresponding continuous coordinates in the source image $(x_{\text{src}} = x_{\text{target}} / f_x, \; y_{\text{src}} = y_{\text{target}} / f_y)$.

# Nearest Neighbor Scaling
def scaling_nn(image, fx, fy):
  H, W = image.shape[:2]
  new_H, new_W = int(H * fy), int(W * fx)
  scaled = np.zeros((new_H, new_W), dtype=image.dtype)

  for y in range(new_H):
    src_y = min(int(round(y / fy)), H - 1)
    for x in range(new_W):
      src_x = min(int(round(x / fx)), W - 1)
      scaled[y, x] = image[src_y, src_x]
  return scaled


# Bilinear Interpolation Scaling
def scaling_bilinear(image, fx, fy):
  H, W = image.shape[:2]
  new_H, new_W = int(H * fy), int(W * fx)
  scaled = np.zeros((new_H, new_W), dtype=np.float64)

  for y in range(new_H):
    src_y = y / fy
    y1 = int(np.floor(src_y))
    y2 = min(y1 + 1, H - 1)
    dy = src_y - y1

    for x in range(new_W):
      src_x = x / fx
      x1 = int(np.floor(src_x))
      x2 = min(x1 + 1, W - 1)
      dx = src_x - x1

      # 4 neighbor pixel values
      f11 = image[y1, x1]
      f12 = image[y1, x2]
      f21 = image[y2, x1]
      f22 = image[y2, x2]

      # Bilinear blend formula
      scaled[y, x] = (
          (1 - dx) * (1 - dy) * f11
          + dx * (1 - dy) * f12
          + (1 - dx) * dy * f21
          + dx * dy * f22
      )

  return np.clip(scaled, 0, 255).astype(np.uint8)

2. Arbitrary Center-based Rotation (Inverse Transformation)

To rotate by $+\theta$ clockwise without holes, project destination pixel $(x_{\text{dst}}, y_{\text{dst}})$ back into source coordinates using rotation by $-\theta$:

$$\begin{bmatrix} x_{\text{src}} - c_x \\ y_{\text{src}} - c_y \end{bmatrix} = \begin{bmatrix} \cos\theta & \sin\theta \\ -\sin\theta & \cos\theta \end{bmatrix} \begin{bmatrix} x_{\text{dst}} - c_x \\ y_{\text{dst}} - c_y \end{bmatrix}$$
def rotate_image_nn(image, angle_deg):
  H, W = image.shape[:2]
  cx, cy = W / 2.0, H / 2.0
  rad = np.radians(angle_deg)
  cos_a, sin_a = np.cos(rad), np.sin(rad)

  rotated = np.zeros_like(image)

  for y in range(H):
    for x in range(W):
      # Shift to origin, rotate backward, shift back
      xt = x - cx
      yt = y - cy
      src_x = int(round(cos_a * xt + sin_a * yt + cx))
      src_y = int(round(-sin_a * xt + cos_a * yt + cy))

      # Bounds check
      if 0 <= src_x < W and 0 <= src_y < H:
        rotated[y, x] = image[src_y, src_x]

  return rotated

Experiment 2: Reading & Writing BMP Files from Scratch

Key BMP Rules

  1. File Header (14 bytes): Magic b'BM', total file size, data offset.
  2. DIB Header (40 bytes): Width, height (positive = bottom-up row ordering!), bit count (8 or 24).
  3. 4-Byte Row Alignment: Every row in a BMP must be padded to a multiple of 4 bytes: $$\text{row\_size} = \left\lfloor \frac{\text{bpp} \cdot \text{width} + 31}{32} \right\rfloor \times 4, \quad \text{padding} = \text{row\_size} - \left(\text{width} \times \frac{\text{bpp}}{8}\right)$$
def read_bmp(filename):
  with open(filename, 'rb') as f:
    # 1. 14-byte File Header
    magic = f.read(2)
    assert magic == b'BM', 'Not a valid BMP'
    file_size = int.from_bytes(f.read(4), 'little')
    f.seek(10)
    data_offset = int.from_bytes(f.read(4), 'little')

    # 2. 40-byte DIB Header
    header_size = int.from_bytes(f.read(4), 'little')
    width = int.from_bytes(f.read(4), 'little', signed=True)
    height = int.from_bytes(f.read(4), 'little', signed=True)
    f.read(2)  # color planes
    bit_count = int.from_bytes(f.read(2), 'little')  # 8 or 24

    # 3. Read Palette if 8-bit
    palette = None
    if bit_count == 8:
      f.seek(14 + header_size)
      palette_bytes = f.read(data_offset - (14 + header_size))
      # Palette entries are 4 bytes: [B, G, R, reserved]
      palette = np.frombuffer(palette_bytes, dtype=np.uint8).reshape(-1, 4)

    # 4. Read Pixel Data (Bottom-Up)
    f.seek(data_offset)
    bytes_per_pixel = bit_count // 8
    row_size = ((bit_count * width + 31) // 32) * 4
    pad = row_size - (width * bytes_per_pixel)

    rows = []
    for _ in range(abs(height)):
      row_data = f.read(width * bytes_per_pixel)
      f.read(pad)  # skip padding bytes
      if bit_count == 24:
        rows.append(np.frombuffer(row_data, dtype=np.uint8).reshape(width, 3))
      else:
        rows.append(np.frombuffer(row_data, dtype=np.uint8))

    img = np.array(rows)
    # If height > 0, rows are stored bottom-to-top, so invert rows:
    if height > 0:
      img = img[::-1, :]

    header = {
        'width': width,
        'height': height,
        'bit_count': bit_count,
        'palette': palette,
    }
    return header, img

Experiment 4: Histogram Equalization & Matching

1. Histogram Equalization from Scratch

Transforms the cumulative probability of gray levels into a uniform distribution:

$$s_k = T(r_k) = \text{round}\left( (L - 1) \sum_{j=0}^k p_r(r_j) \right)$$
def histogram_equalize(image):
  H, W = image.shape[:2]
  total_pixels = H * W

  # 1. Compute Histogram (counts)
  hist = np.zeros(256, dtype=np.int64)
  for val in image.ravel():
    hist[val] += 1

  # 2. Probability Mass Function (PMF) & CDF
  pmf = hist / total_pixels
  cdf = np.cumsum(pmf)

  # 3. Create Mapping Lookup Table (LUT)
  lut = np.clip(np.round(cdf * 255), 0, 255).astype(np.uint8)

  # 4. Map Image via LUT
  equalized = lut[image]
  return equalized, hist, lut

2. Histogram Matching (Specification)

Matches source image histogram to a target/reference image histogram:

  1. Compute $s = T(r) = \text{round}(255 \times \text{CDF}_{\text{source}})$
  2. Compute $v = G(z) = \text{round}(255 \times \text{CDF}_{\text{target}})$
  3. For each gray level $s_k$, find $z_q$ minimizing $|s_k - G(z_q)|$: $$M(r) = \arg\min_{z} |T(r) - G(z)|$$
def histogram_matching(source, target):
  # Compute CDFs
  _, _, lut_source = histogram_equalize(source)
  _, _, lut_target = histogram_equalize(target)

  # Build inverse mapping: map source gray level r -> target gray level z
  mapping = np.zeros(256, dtype=np.uint8)
  for r in range(256):
    s_val = lut_source[r]
    # Find z that makes G(z) closest to s_val
    best_z = np.argmin(np.abs(lut_target.astype(int) - int(s_val)))
    mapping[r] = best_z

  matched_image = mapping[source]
  return matched_image

Experiment 5: 1D & 2D Fast Fourier Transform (FFT) from Scratch

Cooley-Tukey Radix-2 Recursive Formulation:

$$X[k] = X_{\text{even}}[k] + W_N^k X_{\text{odd}}[k], \quad X[k + N/2] = X_{\text{even}}[k] - W_N^k X_{\text{odd}}[k]$$
def next_power_of_2(n):
  return 1 if n <= 1 else 1 << (n - 1).bit_length()


def fft_1d(x):
  x = np.asarray(x, dtype=complex)
  N = x.shape[0]

  # Pad to power of 2 if necessary
  if N > 0 and (N & (N - 1)) != 0:
    target_N = next_power_of_2(N)
    x = np.pad(x, (0, target_N - N), mode='constant')
    N = target_N

  if N <= 1:
    return x

  even = fft_1d(x[0::2])
  odd = fft_1d(x[1::2])

  # Twiddle factor: e^(-2j * pi * k / N)
  twiddle = np.exp(-2j * np.pi * np.arange(N // 2) / N)
  return np.concatenate([even + twiddle * odd, even - twiddle * odd])


# 2D FFT: Row transform followed by Column transform
def fft_2d(image):
  H, W = image.shape
  H_p = next_power_of_2(H)
  W_p = next_power_of_2(W)
  padded = np.pad(
      image.astype(complex), ((0, H_p - H), (0, W_p - W)), mode='constant'
  )

  # Row-wise FFT
  row_fft = np.zeros((H_p, W_p), dtype=complex)
  for r in range(H_p):
    row_fft[r, :] = fft_1d(padded[r, :])

  # Column-wise FFT
  col_fft = np.zeros((H_p, W_p), dtype=complex)
  for c in range(W_p):
    col_fft[:, c] = fft_1d(row_fft[:, c])

  return col_fft


# Inverse FFT using conjugation property: IFFT(X) = (1/N) * conj(FFT(conj(X)))
def ifft_2d(freq_img, original_shape=None):
  H_p, W_p = freq_img.shape
  conj_fft = fft_2d(np.conjugate(freq_img))
  rec = np.conjugate(conj_fft) / (H_p * W_p)
  if original_shape is not None:
    rec = rec[: original_shape[0], : original_shape[1]]
  return rec

Experiment 6: Frequency Domain Filters & Notch Filtering

1. LPF and HPF Transfer Functions

Let $D(u, v) = \sqrt{(u - M/2)^2 + (v - N/2)^2}$ be the Euclidean distance from center:

grid_y, grid_x = np.indices((M, N))
D = np.sqrt((grid_y - M // 2) ** 2 + (grid_x - N // 2) ** 2)

# Ideal LPF / HPF
H_ideal_lpf = (D <= D0).astype(float)
H_ideal_hpf = 1.0 - H_ideal_lpf

# Gaussian LPF / HPF
H_gauss_lpf = np.exp(-(D**2) / (2 * (D0**2)))
H_gauss_hpf = 1.0 - H_gauss_lpf

# Butterworth LPF / HPF (order n)
H_butter_lpf = 1.0 / (1.0 + (D / (D0 + 1e-8)) ** (2 * n))
H_butter_hpf = 1.0 / (1.0 + (D0 / (D + 1e-8)) ** (2 * n))

# Filtering step:
# G(u, v) = F(u, v) * H(u, v)
# g(x, y) = real(ifft2(ifftshift(G)))

2. Butterworth Notch Reject Filter (Sinusoidal Noise Removal)

Given detected noise spike locations $(u_k, v_k)$:

$$H_{\text{notch}}(u, v) = \frac{1}{1 + \left[ \frac{D_0}{D_k(u, v)} \right]^{2n}} \cdot \frac{1}{1 + \left[ \frac{D_0}{D_{-k}(u, v)} \right]^{2n}}$$
def notch_reject_filter(shape, peaks, D0=4.0, n=2):
  M, N = shape
  grid_y, grid_x = np.indices((M, N))
  H_total = np.ones((M, N), dtype=float)

  for py, px in peaks:
    Dk = np.sqrt((grid_y - py) ** 2 + (grid_x - px) ** 2)
    # Symmetrical conjugate peak
    sym_y, sym_x = M - py, N - px
    D_sym = np.sqrt((grid_y - sym_y) ** 2 + (grid_x - sym_x) ** 2)

    H_k = 1.0 / (1.0 + (D0 / (Dk + 1e-8)) ** (2 * n))
    H_sym = 1.0 / (1.0 + (D0 / (D_sym + 1e-8)) ** (2 * n))

    H_total *= H_k * H_sym

  return H_total

Experiment 7: Lucas–Kanade Optical Flow Estimation

Overdetermined System:

$$A \begin{bmatrix} u \\ v \end{bmatrix} = -b \implies (A^T A) \mathbf{v} = -A^T b$$
# Gradients
Ix = cv2.Sobel(I_curr, cv2.CV_64F, 1, 0, ksize=3)
Iy = cv2.Sobel(I_curr, cv2.CV_64F, 0, 1, ksize=3)
It = I_curr - I_prev  # Temporal difference

n = 12  # Window size
half = n // 2
H, W = I_curr.shape

for y in range(half, H - half, n):
  for x in range(half, W - half, n):
    # Extract window neighborhood
    w_Ix = Ix[y - half : y + half, x - half : x + half].flatten()
    w_Iy = Iy[y - half : y + half, x - half : x + half].flatten()
    w_It = It[y - half : y + half, x - half : x + half].flatten()

    A = np.column_stack((w_Ix, w_Iy))  # (n^2, 2)
    b = w_It[:, None]  # (n^2, 1)

    ATA = A.T @ A
    eigenvalues = np.linalg.eigvals(ATA)

    # Threshold on minimum eigenvalue to avoid Aperture problem / singular matrices
    if np.min(eigenvalues) > 0.02:
      # Solve for [u, v]
      v_vec = np.linalg.solve(ATA, -A.T @ b)
      u, v = v_vec[0, 0], v_vec[1, 0]

      # Draw arrow if velocity is reasonable
      speed = np.hypot(u, v)
      if 0.2 < speed < 15.0:
        pt1 = (int(x), int(y))
        pt2 = (int(x + scale * u), int(y + scale * v))
        cv2.arrowedLine(canvas, pt1, pt2, (0, 255, 0), 1, tipLength=0.3)

Experiment 8: 2D Haar Wavelet Transform & Image Compression

1D Pair Operations:

$$\ell = \frac{a + b}{2}, \quad d = \frac{a - b}{2} \iff a = \ell + d, \quad b = \ell - d$$
def haar_1d(arr):
  a = arr[0::2]
  b = arr[1::2]
  return np.concatenate([(a + b) / 2.0, (a - b) / 2.0])


def inv_haar_1d(arr):
  half = len(arr) // 2
  L = arr[:half]
  H = arr[half:]
  out = np.zeros_like(arr, dtype=float)
  out[0::2] = L + H
  out[1::2] = L - H
  return out


def haar_2d_step(mat):
  H, W = mat.shape
  row_tf = np.zeros_like(mat, dtype=float)
  for r in range(H):
    row_tf[r, :] = haar_1d(mat[r, :])
  col_tf = np.zeros_like(row_tf, dtype=float)
  for c in range(W):
    col_tf[:, c] = haar_1d(row_tf[:, c])
  return col_tf


def inv_haar_2d_step(mat):
  H, W = mat.shape
  col_inv = np.zeros_like(mat, dtype=float)
  for c in range(W):
    col_inv[:, c] = inv_haar_1d(mat[:, c])
  row_inv = np.zeros_like(col_inv, dtype=float)
  for r in range(H):
    row_inv[r, :] = inv_haar_1d(col_inv[r, :])
  return row_inv


# Multilevel: apply recursively ONLY on top-left LL quadrant
def haar_transform(img, L):
  coeff = img.copy().astype(float)
  H, W = coeff.shape
  ll_list = []
  for lvl in range(1, L + 1):
    cur_H = H // (2 ** (lvl - 1))
    cur_W = W // (2 ** (lvl - 1))
    coeff[:cur_H, :cur_W] = haar_2d_step(coeff[:cur_H, :cur_W])
    ll_list.append(coeff[: cur_H // 2, : cur_W // 2].copy())
  return coeff, ll_list

Experiment 9: Morphological Operations from Scratch

Method 1: Exam-Friendly Sliding Window via np.pad & Masking (Most Intuitive!)

Pad the image according to the kernel origin and slide the window over each pixel:

  • Dilation (“Hit”): Check if the structuring element touches any foreground pixel. Since $window \in \{0, 255\}$ and $SE \in \{0, 1\}$, window * SE_reflected is $255$ on any hit $\implies$ output[r, c] = np.max(window * SE_reflected).
  • Erosion (“Fit”): Check if the structuring element fits completely within foreground $\implies$ np.sum(window * SE) == 255 * np.sum(SE).
def DilateBinary(image, SE, origin=None):
    kernel = np.array(SE['B'] if isinstance(SE, dict) else SE, dtype=np.uint8)
    kh, kw = kernel.shape
    r0, c0 = SE.get('center', (kh // 2, kw // 2)) if isinstance(SE, dict) else (origin or (kh // 2, kw // 2))
    H, W = image.shape
    
    # Dilation uses reflected kernel about its origin
    SE_ref = np.flip(kernel)
    r0_ref, c0_ref = kh - 1 - r0, kw - 1 - c0
    
    # Pad so kernel origin aligns with each pixel
    pad = ((r0_ref, kh - 1 - r0_ref), (c0_ref, kw - 1 - c0_ref))
    padded = np.pad(image, pad, mode='constant', constant_values=0)
    
    output = np.zeros_like(image)
    for r in range(H):
        for c in range(W):
            window = padded[r : r + kh, c : c + kw]
            # Max is 255 if any SE pixel touches foreground, else 0
            output[r, c] = np.max(window * SE_ref)
    return output

def ErodeBinary(image, SE, origin=None):
    kernel = np.array(SE['B'] if isinstance(SE, dict) else SE, dtype=np.uint8)
    kh, kw = kernel.shape
    r0, c0 = SE.get('center', (kh // 2, kw // 2)) if isinstance(SE, dict) else (origin or (kh // 2, kw // 2))
    H, W = image.shape
    
    pad = ((r0, kh - 1 - r0), (c0, kw - 1 - c0))
    padded = np.pad(image, pad, mode='constant', constant_values=0)
    
    target_sum = 255 * np.sum(kernel)
    output = np.zeros_like(image)
    for r in range(H):
        for c in range(W):
            window = padded[r : r + kh, c : c + kw]
            # Complete fit: every active SE pixel must hit 255
            if np.sum(window * kernel) == target_sum:
                output[r, c] = 255
    return output

def OpenBinary(image, SE, origin=None):
    return DilateBinary(ErodeBinary(image, SE, origin), SE, origin)

def CloseBinary(image, SE, origin=None):
    return ErodeBinary(DilateBinary(image, SE, origin), SE, origin)

Method 2: Fast Vectorized np.pad + Kernel Loop (Lab 8 convolve_2d Style)

When execution speed is needed (instant runtime vs ~1s per image), pad once and loop only over the kernel ($kh \times kw$ iterations instead of $H \times W$ iterations):

def DilateBinaryFast(image, SE, origin=None):
    kernel = np.array(SE['B'] if isinstance(SE, dict) else SE, dtype=np.uint8)
    kh, kw = kernel.shape
    r0, c0 = SE.get('center', (kh // 2, kw // 2)) if isinstance(SE, dict) else (origin or (kh // 2, kw // 2))
    H, W = image.shape
    
    pad_top, pad_bottom = kh - 1 - r0, r0
    pad_left, pad_right = kw - 1 - c0, c0
    padded = np.pad(image, ((pad_top, pad_bottom), (pad_left, pad_right)), mode='constant', constant_values=0)
    
    dilated = np.zeros_like(image)
    for i in range(kh):
        for j in range(kw):
            if kernel[i, j]:
                dilated |= padded[kh - 1 - i : kh - 1 - i + H, kw - 1 - j : kw - 1 - j + W]
    return dilated

Structuring Elements Definitions

SE_list = [
    {'name': '1x2_Horizontal', 'B': np.array([[1, 1]], dtype=np.uint8), 'center': (0, 0)},
    {'name': '3x3_Square',     'B': np.ones((3, 3), dtype=np.uint8),     'center': (1, 1)},
    {'name': '3x3_Cross',      'B': np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=np.uint8), 'center': (1, 1)},
    {'name': '9x9_Square',     'B': np.ones((9, 9), dtype=np.uint8),     'center': (4, 4)},
    {'name': '15x15_Square',   'B': np.ones((15, 15), dtype=np.uint8),   'center': (7, 7)}
]