Assignment Chef icon Assignment Chef
All English tutorials

Programming lesson

Mastering MATLAB Image Processing: A Tutorial for CPS843/CP8307 Assignments

Learn key MATLAB image processing techniques for CPS843/CP8307 assignments: loading images, color plane manipulation, pixel replacement, arithmetic operations, convolution, and Canny edge detection. Avoid loops, use vectorization.

MATLAB image processing CPS843 assignment CP8307 assignment vectorized MATLAB color plane manipulation image convolution Canny edge detection MATLAB Gaussian noise MATLAB imread imshow image gradient computation separable convolution MATLAB loops avoid image processing tutorial 2026 computer vision assignment help CPS843 solution CP8307 solution

Introduction: Why MATLAB Image Processing Matters in 2026

Image processing is everywhere in 2026—from AI-powered photo editors on your phone to autonomous vehicles navigating city streets. In CPS843/CP8307, you'll build foundational skills that power these technologies. This tutorial covers essential techniques for assignments 0-4, focusing on efficient MATLAB coding without loops. We'll use real-world examples, like how your favorite social media app swaps color channels for vintage filters, to make concepts stick.

Loading and Displaying Images

Start by finding two interesting color images (max 512x512). Use imread() to load them and imshow() to display. Always set the display range to the image's min and max for proper contrast:

img1 = imread('image1.jpg');
img2 = imread('image2.jpg');
imshow(img1, [min(img1(:)) max(img1(:))]);

This ensures your output looks correct—crucial when debugging later steps.

Manipulating Color Planes

Color images are 3D arrays (height x width x 3). Swapping red and blue channels is a single line:

img_swapped = img1(:,:,[3,2,1]);

To extract monochrome images from the green and red channels:

img_g = img1(:,:,2); % green channel
img_r = img1(:,:,1); % red channel

Convert to grayscale with rgb2gray(). This mimics how many AI models preprocess images before analysis.

Replacing Pixels: The Center Square

Take a 100x100 block from the center of grayscale image 1 and paste it into grayscale image 2. Use vectorized indexing—no loops:

[h, w] = size(gray1);
center = gray1(h/2-49:h/2+50, w/2-49:w/2+50);
gray2(h/2-49:h/2+50, w/2-49:w/2+50) = center;

This technique is used in augmented reality apps to overlay logos or filters.

Arithmetic and Geometric Operations

Compute statistics of img_g:

min_val = min(img_g(:));
max_val = max(img_g(:));
mean_val = mean(img_g(:));
std_val = std(double(img_g(:)));

Normalize by subtracting mean, dividing by std, multiplying by 10 (if 0-255 range), then adding mean back:

img_double = double(img_g);
normalized = (img_double - mean_val) / std_val * 10 + mean_val;

Shift image left by 2 pixels using indexing:

shifted = zeros(size(img_g));
shifted(:, 1:end-2) = img_g(:, 3:end);

Subtract shifted from original to highlight edges—a basic form of edge detection. Flip horizontally: flipped = fliplr(img_g);. Invert intensities: inverted = 255 - img_g; (or 1 - img_g for double).

Adding Gaussian Noise

Simulate sensor noise by adding Gaussian noise to each color channel. Increase variance until visible:

sigma = 30; % adjust to taste
noise = sigma * randn(size(img1));
noisy_img = uint8(double(img1) + noise);

This mimics low-light photography conditions—see how your phone's night mode tries to remove this.

Convolution: Understanding the Math

Convolution is the heart of image filtering. For the derivative filter [1,0,-1] horizontally, you compute the output by sliding the kernel across the image. Here's a manual example for a small 7x7 image (zero padded). The output at each pixel is the sum of element-wise products. For instance, at position (2,3) with the given image, the horizontal gradient is computed by hand. Use fprintf() to display results.

Gradient magnitude at a pixel combines horizontal and vertical gradients: G = sqrt(Gx^2 + Gy^2). Compute at specified pixels using the same derivative filter for vertical direction (transposed).

Writing Your Own Convolution Function

Implement MyConv using loops (allowed here) but pad the image with zeros first. Flip the kernel both horizontally and vertically (180° rotation). Compare with imfilter using a 13x13 Gaussian kernel (sigma=2). The difference should be near zero if implemented correctly.

function output = MyConv(image, kernel)
    [h, w] = size(image);
    [kh, kw] = size(kernel);
    padded = padarray(image, [floor(kh/2), floor(kw/2)], 0);
    output = zeros(h, w);
    kernel_flipped = rot90(kernel, 2);
    for i = 1:h
        for j = 1:w
            region = padded(i:i+kh-1, j:j+kw-1);
            output(i,j) = sum(sum(region .* kernel_flipped));
        end
    end
end

Separable Convolution for Speed

Convolving with a 2D Gaussian of sigma=8 on a 640x480 image takes time. But Gaussian kernels are separable: convolve with a 1D horizontal kernel, then a 1D vertical kernel. Use tic and toc to measure. You'll see significant speedup—essential for real-time video processing in apps like Instagram filters.

Canny Edge Detection (Partial Implementation)

Implement MyCanny up to hysteresis. Steps: (1) Smooth with Gaussian (sigma parameter), (2) Compute gradients using Sobel or derivative filters, (3) Non-maximum suppression, (4) Double thresholding. Return binary edge map. This algorithm is used in self-driving cars to detect lane markings.

For the full assignment, follow the handout. Remember to avoid loops where possible—use vectorized operations like imgradient or custom vectorized gradient computation.

Final Tips for Assignment Success

  • Always cast to double before arithmetic to avoid uint8 overflow.
  • Use imshow() with appropriate scaling for display.
  • Submit a zip with images and scripts; ensure a0 script.m runs without errors.
  • Search the web for MATLAB vectorization tricks—they're your best friend.

By mastering these techniques, you're not just completing an assignment—you're building skills used in cutting-edge AI and computer vision applications. Good luck!