Homework 02: Filtering

Implement correlation, convolution, common linear filters, and a median filter from scratch.

Total: 5 points
Submission: Gradescope Programming Assignment
Work: Individual

Objective

The objective of this homework is to implement the core image filtering operation yourself, and use it to explore several topics such as correlatio, convolution, and nonlinear filters.

Use the course cv Conda environment, and OpenCV (cv2). The filtering computations required below must be implemented by you rather than delegated to a library filtering function.

Do not use generative AI to solve this homework. The purpose of this assignment is to make sure you can translate the filtering equations from lecture into working code.

Starter file

Complete the provided hw02.py file. Do not rename the required functions, change their arguments, or modify the three provided kernels because the Gradescope autograder calls/checks them directly.

Download hw02.py

The required functions are:

correlate2d(image, kernel)
convolve2d(image, kernel)
median_filter3x3(image)

Part 1 — Implement 2-D correlation

Complete:

def correlate2d(image, kernel):
    ...

Requirements:

  • image is a 2-D grayscale array.
  • kernel is a 2-D kernel with odd height and width.
  • Use zero padding outside the image boundary.
  • Return an output with the same height and width as the input image.
  • Return numpy.float32 output.
  • Implement the kernel sweep yourself, e.g., using nested for loops.

Your implementation should work for different odd kernel sizes, not only 3x3 kernels.

Part 2 — Implement 2-D convolution

Complete:

def convolve2d(image, kernel):
    ...

For convolution, rotate the kernel by 180 degrees and then reuse your correlate2d() implementation.

You may use np.flip() or cv2.flip() to rotate the kernel. Do not reimplement the filtering operation with a library function.

The output must use the same zero-padding and same-size convention as correlate2d().

Part 3 — Use the provided linear-filter kernels

The starter file provides these kernels:

BOX_3X3
SOBEL_X
SHARPEN_3X3

Do not modify them.

When you run the script, your correlation/convolution implementation will be used to produce:

  • box-filter smoothing;
  • a horizontal derivative response using Sobel X; and
  • a sharpened image.

The script also compares correlation and convolution for the symmetric box kernel and the asymmetric Sobel X kernel.

Part 4 — Implement a 3x3 median filter

Complete:

def median_filter3x3(image):
    ...

Requirements:

  • Use a 3x3 neighborhood.
  • Use zero padding outside the image boundary.
  • Return an output with the same shape as the input image.
  • Return numpy.float32 output.
  • Sweep the kernel yourself, e.g., using nested for loops.
  • You may use np.median() to compute the median of one local 3x3 neighborhood.

The provided script adds deterministic salt-and-pepper noise and uses your median filter so you can compare the noisy and filtered images.

Important: filtering functions you may not use

The filtering operation itself must be your implementation. We check your code for prohibited shortcuts. Using a prohibited library filtering implementation causes the homework to receive no credit.

Examples of functions you should not use to implement the required filters include:

cv2.filter2D
cv2.blur
cv2.boxFilter
cv2.GaussianBlur
cv2.Sobel
cv2.Scharr
cv2.sepFilter2D
cv2.medianBlur
cv2.Laplacian

scipy.signal.correlate / correlate2d
scipy.signal.convolve / convolve2d
scipy.signal.fftconvolve
scipy.ndimage.correlate / convolve
scipy.ndimage.uniform_filter
scipy.ndimage.gaussian_filter
scipy.ndimage.median_filter
scipy.ndimage.sobel

np.convolve
np.correlate
np.lib.stride_tricks.sliding_window_view

Do not use skimage, PIL/Pillow, or another image-processing package as a replacement.

You may use OpenCV for ordinary image I/O and visualization operations such as cv2.imread, cv2.cvtColor, cv2.resize, and cv2.imwrite. You may also use basic NumPy operations such as np.pad, slicing, np.sum, np.median, and np.flip.

Run your program

Activate the course environment and run the script with a JPG/JPEG or PNG image. You may reuse your HW01 headshot.

conda activate cv
python hw02.py my_image.png

For speed, the provided script downsizes large images before running your manual filters.

A successful run must:

  • execute without an error;
  • print the maximum correlation/convolution difference for the box kernel;
  • print the maximum correlation/convolution difference for the Sobel X kernel; and
  • save hw02_output.png containing a montage of the filtering results.

Inspect the output and notice that:

  • correlation and convolution agree for the symmetric box kernel;
  • correlation and convolution differ for the asymmetric Sobel X kernel; and
  • the median filter suppresses isolated salt-and-pepper outliers better than ordinary averaging.

What to submit

Submit exactly one file to Gradescope:

hw02.py

Do not submit your input image, hw02_output.png, screenshots, or a PDF report. The autograder runs your script with instructor-provided images and arrays.

Submission limit — important

You may make at most 3 Gradescope submissions for this homework. Test and debug thoroughly in your local cv environment before submitting.

  • Submissions 1–3 are graded normally.
  • Submission 4 and every later submission receive a score of 0 for the homework.
  • A Gradescope infrastructure failure marked as an autograder error does not count against the three-submission limit.

Grading

HW02 is worth 5 points and is autograded.

The autograder checks:

  • whether the required functions are present;
  • whether prohibited filtering routines are used;
  • correlation correctness, including boundary handling and different kernel shapes;
  • convolution correctness;
  • the provided box, Sobel X, and sharpening kernels;
  • the 3x3 median filter; and
  • whether python hw02.py IMAGE runs successfully in the cv environment and saves the expected output file.

Some basic tests are public and provide feedback when you submit. More substantive numerical correctness tests are private. Passing all public tests does not guarantee full credit.

Notes

  • Use the course cv Conda environment, and the openCV (cv2) library.
  • Do not use OpenCV to replace the filtering algorithms you are required to implement.
  • Do not change the required function names or arguments.
  • Do not modify BOX_3X3, SOBEL_X, or SHARPEN_3X3.
  • Do not hard-code outputs for a particular image or kernel.
  • Test locally before using one of your Gradescope submissions.