CS180 — Project 2: Fun with Filters and Frequencies

This project explores the fundamentals of image processing through filtering and frequency domain manipulation. We apply the techniques we develop on a series of fun images to create cool visual effects.


Part 1: Fun with Filters

In this part, we will build intuitions about 2D convolutions and filtering, beginning with finite difference operators as our filters in the x and y directions.

Part 1.1: Convolutions from Scratch!

First, let's implement convolution from scratch using numpy only. I'll compare my implementation with scipy's built-in function and analyze the differences in runtime and boundary handling.

What is Convolution?

Intuitive Understanding: Convolution is like sliding a small window (called a kernel or filter) across an image and computing a weighted sum at each position.

For example:

The mathematical operation involves flipping the kernel and then sliding it across the image, multiplying corresponding pixel values and summing the results. This creates a new "filtered" version of the image that emphasizes certain features based on the kernel used.

What Does a Box Filter Do?

A box filter is one of the simplest blur filters - it's a square matrix filled with equal values (typically 1's that are then normalized). When convolved with an image, it replaces each pixel with the average of its neighbors within the box. This has a smoothing effect because sharp changes in intensity get averaged out with surrounding pixels. A 9x9 box filter takes the average of 81 neighboring pixels, creating a more pronounced blur than smaller kernels.

My Convolution Implementation

# Four-loop implementation
def convolve_4loops(image, kernel, padding = True):
    #flip kernel to make operation commutative
    kernel = np.flip(kernel)

    img_height, img_width = image.shape
    kernel_height, kernel_width = kernel.shape

    if padding:
        pad_h = kernel_height // 2
        pad_w = kernel_width // 2

        padded_image = np.zeros((img_height + 2*pad_h, img_width + 2*pad_w))
        padded_image[pad_h:pad_h+img_height, pad_w:pad_w+img_width] = image

        result = np.zeros((img_height, img_width))
    else:
        padded_image = image
        result_height = img_height - kernel_height + 1
        result_width = img_width - kernel_width + 1
        result = np.zeros((result_height, result_width))
        pad_h, pad_w = 0, 0

    for i in range(result.shape[0]):
        for j in range(result.shape[1]):
            conv_sum = 0
            for ki in range(kernel_height):
                for kj in range(kernel_width):
                    #convolve by manually sliding the kernel over the image
                    img_i = i + ki
                    img_j = j + kj
                    conv_sum += padded_image[img_i, img_j] * kernel[ki, kj]

            result[i, j] = conv_sum

    return result

# Two-loop implementation
def convolve_2loops(image, kernel, padding = True):
    #flip kernel
    kernel = np.flip(kernel)

    img_height, img_width = image.shape
    kernel_height, kernel_width = kernel.shape

    if padding:
        pad_h = kernel_height // 2
        pad_w = kernel_width // 2

        padded_image = np.zeros((img_height + 2*pad_h, img_width + 2*pad_w))
        padded_image[pad_h:pad_h+img_height, pad_w:pad_w+img_width] = image

        result = np.zeros((img_height, img_width))
    else:
        padded_image = image
        result_height = img_height - kernel_height + 1
        result_width = img_width - kernel_width + 1
        result = np.zeros((result_height, result_width))
        pad_h, pad_w = 0, 0

    for i in range(result.shape[0]):
        for j in range(result.shape[1]):
            #convolve by getting the image matrix and multiplying element-wise by using built in numpy operations
            patch = padded_image[i:i+kernel_height, j:j+kernel_width]
            result[i, j] = np.sum(patch * kernel)

    return result

Comparison with scipy.signal.convolve2d

Original Image Box Filter Result
Left: Original headshot image. Right: Result after applying 9x9 box filter to grayscale version of headshot.
Timing Comparison
Runtime comparison between my convolution implementations and scipy's built-in function.

Finite Difference Results

Dx Filter Dy Filter Gradient Magnitude
Left: Result of Dx finite difference operator. Middle: Result of Dy finite difference operator. Right: Gradient magnitude image.

Padding and Boundary Handling: My convolution implementation handles boundaries through zero-padding when the padding=True parameter is set. The algorithm calculates padding dimensions as pad_h = kernel_height // 2 and pad_w = kernel_width // 2, then creates a larger array filled with zeros and places the original image in the center. This approach ensures that:

  1. Output size preservation: With padding, the output image maintains the same dimensions as the input image
  2. Edge handling: Pixels near image boundaries are convolved with zero-valued pixels, which can create darker edges compared to other padding strategies
  3. Valid convolution: When padding=False, only valid convolutions are computed, resulting in a smaller output image with dimensions (input_height - kernel_height + 1, input_width - kernel_width + 1)

The zero-padding strategy is simple but can introduce boundary artifacts.

Runtime Comparison: As you can see in the runtime comparison, my two loop implementation of the convolution is an order of magnitude faster than the four loop convolution implementation. The scipy implementation of the operation is roughly 30x faster than the two loop implementation, so we use that from here on out.


Part 1.2: Finite Difference Operator

Here I compute the partial derivatives of the cameraman image and create edge detection results. The intuitive approach used here is provided in the previous section.

Original Cameraman Image Partial Derivative X Partial Derivative Y
Left: Original cameraman image. Middle: Partial derivative in x-direction. Right: Partial derivative in y-direction.
Gradient Magnitude Binarized Edge Image
Left: Gradient magnitude image, computed by taking the norm of D_x and D_y. Right: Binarized edge image.

Threshold Selection: To get the threshold for the binarized edge image, we play around with different threshold values until the edges come out very thin and fine, but still provide detail throughout the image. With too low of a threshold, we pick up noise in the image, and our edges become very large, and by picking too high of a threshold, we lose details from the image. We will see in the next part how to more effectively detect the edges. The threshold we use here is 35 (pixel values from [0, 255]).


Part 1.3: Derivative of Gaussian (DoG) Filter

To reduce noise in edge detection, I first blur the image with a Gaussian filter before applying the finite difference operators.

Gaussian Smoothing First

Original Cameraman Gaussian Blurred
Left: Original cameraman image. Right: Gaussian blurred cameraman.
Blurred then Dx Blurred then Dy
Left: Dx after blurring. Right: Dy after blurring.

Derivative of Gaussian Filters

DoG X Filter DoG Y Filter
Left: Derivative of Gaussian filter in x-direction. Right: Derivative of Gaussian filter in y-direction.

Single Convolution Results

DoG Gradient Magnitude Smooth Gradient Magnitude
Left: Gradient magnitude using DoG filters (single convolution). Right: Gradient magnitude from smooth then differentiate approach.
Binary Edge Image
Final binary edge image using DoG filters.

Thoughts: In the first approach, we begin by blurring the image and then use the finite difference operators from above. The second approach, the Derivative of Gaussian (DoG) filter approach, we convolve the 2d Gaussian kernel with the D_x/D_y kernels before convolving with the image. Because convolution is a commutative operation, we get the same results from both of these approaches, which can be seen in the smooth gradient magnitude image vs. the DoG gradient magnitude image. Finally, we provide the binary_edges image computed from our gradient magnitude image with an intensity threshold of 35.

We see that by blurring first, we pick up much less noise throughout the image (no grass, etc).


Part 2: Fun with Frequencies!

Part 2.1: Image "Sharpening"

Using the unsharp masking technique to enhance image sharpness by emphasizing high-frequency components.

Theory and Implementation

The unsharp mask filter works by:

  1. Creating a low-pass filtered (blurred) version of the image
  2. Subtracting this from the original to get high frequencies
  3. Adding scaled high frequencies back to the original image

Formula: sharpened = original + α × (original - blurred)

Results on Taj Mahal

We see the step by step approach to sharpening the details on the Taj Mahal. We start with a blurry original image, and create a low-pass-filter version that is even more blurry. Then we get the high-frequency image by subtracting the low-pass-filtered version from the original. Finally, we add some amount of the high_frequency image back to the original to get a sharpened version (alpha = 1.5 in this case).

Original Taj Blurred Taj High Frequencies
Left: Original Taj Mahal. Middle: Blurred version. Right: High frequency components.
Sharpened Taj
Sharpened Taj Mahal using unsharp masking.

Additional Example

This image was taken on a hike through Peñalara, a mountain in Spain. We see how the small details in the rocks and bushes are emphasized using this technique.

Original Penalara High Frequencies Penalara Sharpened Penalara
Left: Original image. Middle: High frequency components. Right: Sharpened result.

Evaluation: Blur then Sharpen

Sharp Original Artificially Blurred Re-sharpened
Left: Original sharp image. Middle: Artificially blurred. Right: Attempt to re-sharpen.

Observations: Here I try a quick experiment, in which I start with a good quality original image. I then blur it, and try recreate the "sharp" version through the process noted above. We see that the resharpened version differs from the original, because some information was lost when we apply the blur. However, in the resharpened version, you can see details on the roof of the house, as well as some added contrast in my glasses. This picture was taken in the Lofoten Islands in the North of Norway.


Part 2.2: Hybrid Images

Creating hybrid images that change interpretation based on viewing distance, following the approach by Oliva, Torralba, and Schyns (SIGGRAPH 2006). Here we take a low-pass-filtered image, and then a high-pass-filtered image (taken by subtracting the low-pass image from the original) and overlay them. After overlaying them, we can see the high-pass image from up close and then the low-pass image from a distance.

Process Demonstration

First, I'll demonstrate how the process works on two images of my cousins, who are twins.

Varun Original Vipin Original
Left: Varun (cousin 1). Right: Vipin (cousin 2).
Varun Aligned Vipin Aligned
Left: Varun aligned for processing. Right: Vipin aligned for processing.

Frequency Analysis

Varun FFT Vipin FFT
Left: Fourier transform of Varun's aligned image. Right: Fourier transform of Vipin's aligned image.

Filtered Images and Their Frequency Content

Varun Low-pass Vipin High-pass
Left: Varun low-pass filtered (cutoff frequency = 2.0). Right: Vipin high-pass filtered (cutoff frequency = 6.0).
Low-pass FFT High-pass FFT
Left: FFT of low-pass filtered Varun. Right: FFT of high-pass filtered Vipin.

Final Hybrid Result

Hybrid Result Hybrid FFT
Left: Final hybrid image of Vipin and Varun. Right: FFT of the hybrid result.

Understanding the Process

How Hybrid Images Work: The magic of hybrid images lies in how our visual system processes different spatial frequencies. When viewing an image up close, we can resolve fine details (high frequencies), but from a distance, only the coarse structure (low frequencies) is visible.

Frequency Domain Analysis: The FFT plots show the frequency content of our images in the frequency domain. The bright center represents low frequencies (smooth variations), while the outer regions represent high frequencies (sharp edges and fine details).

Cutoff Frequency Selection:

The difference in cutoff frequencies (2.0 vs 6.0) creates a frequency gap that prevents interference between the two images. When combined, viewers see Vipin's detailed features up close but Varun's overall face structure from a distance, creating the hybrid effect.

FFT Analysis:

Additional Hybrid Images

Example 1: Derek + Nutmeg

Derek Original Nutmeg Original Derek + Nutmeg Hybrid
Left: Derek original. Middle: Nutmeg original. Right: Derek + Nutmeg hybrid image.

Example 2: Custom Hybrid

Dad Dad's Coworker Dad + Coworker Hybrid
Left: My dad. Middle: My dad's coworker. Right: The hybrid result.

Part 2.3 & 2.4: Multi-resolution Blending

Implementing the multi-resolution blending technique from Burt and Adelson (1983) to create seamless image composites.

Understanding Gaussian and Laplacian Pyramids

Gaussian Pyramid: A Gaussian pyramid is created by repeatedly applying a Gaussian filter and downsampling (though we maintain the same image size for visualization). Each level represents the image at progressively lower resolution, containing mainly the coarse, low-frequency information.

Laplacian Pyramid: The Laplacian pyramid captures the high-frequency details at each scale. Each level is computed by subtracting the next Gaussian level from the current one: Laplacian[i] = Gaussian[i] - Gaussian[i+1]. This gives us the band-pass filtered information at each scale.

Multi-resolution Blending: The key insight is that we can blend images at different frequency bands using different masks. High-frequency details need sharp transitions in the mask, while low-frequency components can use smooth mask transitions. This prevents artifacts that would occur with simple alpha blending.

Apple and Orange Blending Demonstration

Apple Original Orange Original
Left: Original apple image. Right: Original orange image.
Complete Pyramid Visualization
Complete visualization showing Gaussian and Laplacian pyramids for both apple and orange images, demonstrating the multi-resolution decomposition process.
Blending Process Visualization
Detailed visualization of the improved blending process for part 2.4 showing how each pyramid level is combined using the multi-resolution mask.
Final Oraple Result
The final "oraple" result - seamlessly blended apple and orange using multi-resolution techniques.

Additional Blending Examples

Cup of Coffee
Mars
Cup of Mars
Guinness
Nighttime Street
Guinness Street
Additional examples of multi-resolution blending showing input images and their seamlessly blended results.

What I Learned

In this project, I learned several techniques that can be used to sharpen and blend images in different ways. Through these blending/sharpening techniques, I developed a more intuitive understanding of frequency space and how it is useful in image processing. I also had the opportunity to make some fun pictures!