Academic Block

Logo of Academicblock.net

Image Processing using MATLAB

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 way you can upload the images in Matlab using “imread” function:

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


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 in Matlab using uigetfile function

% 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 in Matlab using imwrite function

% Read and display images with uigetfile, works similar to Windows UI
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, in Matlab

% Convert an RGB image to grayscale
img = imread('peppers.png');
gray_img = rgb2gray(img);
subplot(1, 2, 1); % Create a 1x2 grid, select the first section
imshow(img);
title('Color Image');

subplot(1, 2, 2); % Select the second section
imshow(gray_img);
title('Grayscale Image');

Example 5: Resizing Images in Matlab

% 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 in Matlab

Matlab offers many functions for applying filters, and to enhance image features or suppress noise:

Example 6: Applying a Gaussian Filter on a image in Matlab

% 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 in Matlab

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

Example 8: Image Geometric Transformations in Matlab

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) Image Processing using Matlab

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) Image using Matlab

User can use computer mouse to click and select specific areas ROI of an image:

% 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
% Get a point from the user
[xi, yi, button] = ginput(1);

% Break if the user presses Enter (button = empty)
if isempty(button)
break;
end

% Store the point
x = [x; xi];
y = [y; yi];

% Plot the '+' sign at the selected point
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 of the same size as the original image
white_image = 255 * ones(size(original_img), 'like', original_img);

% Overlay the ROI onto the white image
output_image = bsxfun(@times, white_image, ~cast(roi_mask, 'like', original_img)) + roi;

% Save the result
imwrite(output_image, 'C:/Users/JohnDoe/Pictures/roi_output.jpg');

% Display the final ROI
figure;
imshow(output_image);
title('Extracted Region of Interest on White Background');

Example 11: Image Histogram Equalization in Matlab

Enhance contrast in images using histogram equalization:

% Equalize the histogram of a grayscale image

% Read the original 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 in Matlab

Use selects multiple images, and then creates videos out of the selected images:

% 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'); % Output video file
outputVideo.FrameRate = 2; % Set frame rate (e.g., 2 frames per second)
open(outputVideo);

% Read each image and add it as a frame to the video
for i = 1:length(fileNames)
% Read the image
img = imread(fullfile(pathName, fileNames{i}));

% Convert the image to match video format if necessary
if size(img, 3) ~= 3
img = repmat(img, [1, 1, 3]); % Convert grayscale to RGB
end

% Write the image to the video
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 in Matlab

Use can extract image frames from the selected video using the following Matlab codes:

% 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)
% Read the next frame
frame = readFrame(videoObj);

% Increment frame counter
frameCount = frameCount + 1;

% Create a filename for the frame
frameFileName = fullfile(outputFolder, sprintf('frame_%04d.jpg', frameCount));

% Save the frame as an image
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 specified methods like ‘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.