Academic Block

Image Processing using MATLAB Get Certified

Image processing is a crucial application of MATLAB, providing tools for manipulating, analyzing, and visualizing images. MATLAB’s Image Processing Toolbox offers a wide range of functions to work with images effectively. This section introduces key concepts, examples, and problems in image processing.

Reading, Writing and Displaying Images

You can read, display and write images using MATLAB commands like imread, imshow and imwrite.

There are three ways you can upload images in MATLAB using the imread function:

  1. img = imread('myImage.png'); — when the image is located in the current working directory.
  2. img = imread('C:/path_to_image/myImage.jpg'); — when the image is located in a different directory.
  3. [filename, pathname] = uigetfile({'*.jpg;*.png;*.bmp', 'Image Files'}); — select any location interactively.

Example 1: Reading and Displaying Images in Matlab

% Read and display images from predefined paths
img1 = imread('peppers.png');
img2 = imread('C:/Users/JohnWick/Pictures/myImage.jpg');

subplot(1, 2, 1); % Create a 1x2 grid, select the first section
imshow(img1);
title('Image 1');

subplot(1, 2, 2); % Select the second section
imshow(img2);
title('Image 2');
Output: Both images will be displayed side by side in the figure window.

Example 2: Reading and Displaying Images using uigetfile

% Read and display images with uigetfile, works similar to Windows UI
[filename, pathname] = uigetfile({'*.jpg;*.png;*.bmp', 'Image Files'});
if isequal(filename, 0)
    disp('No file selected');
else
    img = imread(fullfile(pathname, filename));
    imshow(img);
end

Example 3: Reading, Writing and Displaying Images with imwrite

% Read an image and save it in a different format
img = imread('C:/Users/JohnWick/Pictures/continental_01.jpg'); % Read an image
imwrite(img, 'C:/Users/JohnWick/Pictures/continental_01.png'); % Save the image in PNG format
imshow(img);
Output: continental_01.jpg will be saved as continental_01.png

Example 4: Converting Image to Grayscale

% Convert an RGB image to grayscale
img = imread('peppers.png');
gray_img = rgb2gray(img);
subplot(1, 2, 1);
imshow(img);
title('Color Image');

subplot(1, 2, 2);
imshow(gray_img);
title('Grayscale Image');

Example 5: Resizing Images

% Resize an image
img = imread('car.png');
resized_img = imresize(img, 0.5); % Resized to 50%
imshow(resized_img);
imwrite(img, 'C:/Users/JohnWick/Pictures/car_01.png');

Image Filtering and Enhancement

MATLAB offers many functions for applying filters and for enhancing image features or suppressing noise.

Example 6: Applying a Gaussian Filter

% Apply Gaussian filter
img1 = imread('puppy.png');
gray_img = rgb2gray(img1);
smoothed_img = imgaussfilt(gray_img, 2); % Standard deviation = 2
imshow(smoothed_img);

Example 7: Edge Detection

% Detect edges using Canny method
edges = edge(gray_img, 'Canny');
imshow(edges);

Example 8: Image Geometric Transformations

Perform transformations like rotation, translation, and scaling:

% Read the original image
original_img = imread('C:/Users/JohnDoe/Pictures/sample_image.jpg');

% Perform transformations
rotated_img = imrotate(original_img, 45); % Rotate by 45 degrees
translated_img = imtranslate(original_img, [50, 30]); % Translate by [50 pixels right, 30 pixels down]
scaled_img = imresize(original_img, 0.5); % Scale down by 50%

% Display images in a 2x2 grid
figure;
subplot(2, 2, 1);
imshow(original_img);
title('Original Image');

subplot(2, 2, 2);
imshow(rotated_img);
title('Rotated Image');

subplot(2, 2, 3);
imshow(translated_img);
title('Translated Image');

subplot(2, 2, 4);
imshow(scaled_img);
title('Scaled Image');

Example 9: Simple Region of Interest (ROI)

Focus on specific areas of an image:

my_img = imread('C:/Users/JohnDoe/Pictures/sample_image.jpg');
% Extract a region of interest
roi = my_img(50:200, 50:200, :); % Selects a 150 by 150px square sub-image
imshow(roi);

Example 10: User-Selected Region of Interest (ROI)

The user can click on the image to select a polygonal ROI:

% Read the original image
original_img = imread('C:/Users/JohnWick/Pictures/my_car_01.jpg');

% Display the image
figure;
imshow(original_img);
title('Click to select points for ROI. Press Enter when done.');

% Initialize variables for storing points
x = [];
y = [];

% Loop to capture clicks and display '+' after each click
hold on;
while true
    [xi, yi, button] = ginput(1);
    if isempty(button)
        break;
    end
    x = [x; xi];
    y = [y; yi];
    plot(xi, yi, 'r+', 'MarkerSize', 10, 'LineWidth', 2);
end
hold off;

% Create a binary mask for the selected ROI
roi_mask = poly2mask(x, y, size(original_img, 1), size(original_img, 2));

% Extract the ROI
roi = bsxfun(@times, original_img, cast(roi_mask, 'like', original_img));

% Create an all-white image and overlay the ROI
white_image = 255 * ones(size(original_img), 'like', original_img);
output_image = bsxfun(@times, white_image, ~cast(roi_mask, 'like', original_img)) + roi;

% Save and display the result
imwrite(output_image, 'C:/Users/JohnDoe/Pictures/roi_output.jpg');
figure;
imshow(output_image);
title('Extracted Region of Interest on White Background');

Example 11: Image Histogram Equalization

Enhance contrast in images using histogram equalization:

% Equalize the histogram of a grayscale image
original_img = imread('C:/Users/JohnWick/Pictures/Helen_Wick_01.jpg');
eq_img = histeq(original_img);
imshow(eq_img);

Example 12: Making Videos from Images

The user selects multiple images and creates a video from them:

% Prompt the user to select multiple image files
[fileNames, pathName] = uigetfile({'*.jpg;*.png;*.bmp', 'Image Files (*.jpg, *.png, *.bmp)'}, ...
                                  'Select Images', 'MultiSelect', 'on');

% Check if the user selected files
if isequal(fileNames, 0)
    disp('No files selected.');
    return;
end

% If only one file is selected, make it a cell array for consistency
if ischar(fileNames)
    fileNames = {fileNames};
end

% Create a VideoWriter object for the output video
outputVideo = VideoWriter('output_video.avi');
outputVideo.FrameRate = 2; % 2 frames per second
open(outputVideo);

% Read each image and add it as a frame to the video
for i = 1:length(fileNames)
    img = imread(fullfile(pathName, fileNames{i}));
    if size(img, 3) ~= 3
        img = repmat(img, [1, 1, 3]); % Convert grayscale to RGB
    end
    writeVideo(outputVideo, img);
end

% Close the VideoWriter object
close(outputVideo);
disp('Video created successfully as output_video.avi');

Example 13: Extracting Image Frames from Videos

Extract individual frames from a video file:

% Specify the video file
videoFile = 'C:/Users/JohnWick/Videos/John_Helen.mp4';

% Create a VideoReader object
videoObj = VideoReader(videoFile);

% Create a folder to save the extracted frames
outputFolder = 'C:/Users/JohnDoe/Videos/ExtractedFrames';
if ~exist(outputFolder, 'dir')
    mkdir(outputFolder);
end

% Initialize frame counter
frameCount = 0;

% Loop through each frame in the video
while hasFrame(videoObj)
    frame = readFrame(videoObj);
    frameCount = frameCount + 1;
    frameFileName = fullfile(outputFolder, sprintf('frame_%04d.jpg', frameCount));
    imwrite(frame, frameFileName);
end

disp(['Frames extracted and saved to: ', outputFolder]);

Useful MATLAB Functions for Image Processing

Function
Explanation
imread
Reads an image from a file.
imshow
Displays an image in a figure window.
imwrite
Writes an image to a file.
rgb2gray
Converts an RGB image to grayscale.
imresize
Resizes an image to a specified size or scale.
imgaussfilt
Applies a Gaussian filter to an image.
edge
Detects edges in an image using methods such as Canny or Sobel.
imrotate
Rotates an image by a specified angle.
histeq
Enhances the contrast of a grayscale image.

Practice Questions

Test Yourself

1. Load an image, convert it to grayscale, and perform edge detection.

2. Rotate an image by 30 degrees and crop the rotated image.

3. Resize an image to half its original size and enhance its contrast.

4. Apply a Gaussian filter to an image and compare it with the original.