You are on page 1of 33

MCT-453: Machine Vision

Getting to start with Images and videos in Matlab


REG NO: 2017-MC-293 NAME: Jalal Hussain
Lab Session 1:
Matlab toolboxes regarding Machine Vision:
Following toolboxes in Matlab can be helpful in machine vision applications.
For Matlab Command:
Computer Vision System Toolbox
Deep Learning Toolbox
Image Processing Toolbox
Statics and Machine Learning Toolbox
For Python Library:
OpenCV2
Skimage
Reading an Image from Matlab directory :
Matlab have a number of images in its installation folder and you can view these in the following folder
"C:\Program C:\Program Files\MATLAB\R2018a\toolbox\images\imdata"
I = imread('pout.tif');
To display the image, use imshow()
imshow(I);

Fig 1.1 'pout.tif'

The imread function returned the image data in the variable I, which is a 291-by-240 element
array of uint8
data. MATLAB can store images as
uint8, uint16, or double arrays.
Ahmed Qureshi 2017-MC-307

You can also get information about variables in the workspace by calling whos command.
whos I

Task 01:
Read any three images from matlab directory and dispay them in a subplot and show
appropriate
titles.
Matlab code:
%% Task 01 %%
I=imread('AT3_1m4_01.tif');
R=imread('baby.jpg');
L=imread('bag.png');
subplot(3,1,1),imshow(I)
title('pic_1')
subplot(3,1,2),imshow(R)
title('baby')
subplot(3,1,3),imshow(L)
title('bag')

Results:

Fig 1.2 images


Use of Image tool:
imtool opens the Image Viewer app in an empty state. Use the File menu options Open or
Import from
Workspace to choose an image for display.
imtool(I);

In Image Viewer app, hover your mouse over the image, you will see the pixel’s spatial location
(X,Y) and
intensity value (0-255).
Page | 1
Ahmed Qureshi 2017-MC-307

2
In Tools, go to image information, to see image dimensions, intensity range.
Task 02:
Open your image( eight.png ) in Matlab with imtool and find the intensity value of cions and
diameters of two different coins.
MATLAB code and results:
i=imread('baby.jpg');
imtool(i);

Fig 1.3
Task 03:
You are given a folder of hand written digits, write an algorithm to specify images folder using
cd,
and import all images and display them like a video.
MATLAB code:
d=12
iNum=10;
for n=0:iNum
cd(['C:\Program
Files\MATLAB\R2017a\toolbox\vision\visiondata\digits\handwritten\',num2str(n)
])
d=12;
for i=1:d
k=imread(['digit_',num2str(n),'_',num2str(i),'.png']);
imshow(k)

Lab Session# 02

Page | 2
Ahmed Qureshi 2017-MC-307

Geometric transformations (cropping, resizing, rotation, translation) in


MATLAB
Task#01:
Write a MATLAB program to read a grayscale image (‘cameraman.tif’). Resize given image to
following and place suitable titles
1) Half of its size
2) twice of its size
3) size (100x100)
4) size (100x250)
MATLAB Code:
A) K=imread('cameraman.tif');
L=imresize(K,0.5);
imshow(K)
figure(),imshow(L)
title('Half of its size')
B) M=imread('cameraman.tif');
N=imresize(M,2);
imshow(M)
figure(),imshow(N)
title('Twice of its size')
C) P=imread('cameraman.tif');
O=imresize(P,[100 100]);
imshow(P)
figure(),imshow(O)
title('size 100*100')
D) S=imread('cameraman.tif');
T=imresize(S,[100 250]);
imshow(S)
figure(),imshow(T)
title('size 100*250')

MATLAB Results:

Page | 3
Ahmed Qureshi 2017-MC-307

Page | 4
Ahmed Qureshi 2017-MC-307

Task#02:
Write a Matlab program to read a grayscale image (‘cameraman.tif’). Rotate given image to
angle and place suitable titles
1) Clockwise45
2) Anticlockwise90
3) Clockwise30 (output image dimension equal to input)
MATLAB Code:
A) Is= imread('cameraman.tif');
Js= imrotate(Is, -45);
imshow(Is)
figure(),imshow(Js)
title('clockwise45')
B) Ks= imread('cameraman.tif');
Ls= imrotate(Ks,90);
imshow(Ks)
figure(),imshow(Ls)
title('anticlockwise90')
C) Ms= imread('cameraman.tif');
Ns= imrotate(Ms,-30,'crop');
imshow(Ms)
figure(),imshow(Ns)
title('clockwise30 but same size as original')

MATLAB Results:

Page | 5
Ahmed Qureshi 2017-MC-307

Task#03:
Page | 6
Ahmed Qureshi 2017-MC-307

Write a Matlab program to read a grayscale image (‘pout.tif’). Translate given image to
following and and place suitable titles.
1) [-25,-25]
2) [30,50]
3) [-50,0] (white filled)

MATLAB Code:
A) Il = imread('pout.tif');
Jl= imtranslate(Il,[-25,-25]);
imshow(Il)
figure(),imshow(Jl)
set(gca,'Visible','on');
title('transated by [-25,-25]')
B) Kl = imread('pout.tif');
Jl= imtranslate(Kl,[30,50]);
imshow(Kl)
figure(),imshow(Jl)
set(gca,'Visible','on');
title('transated by [30,50]')
C) Kl = imread('pout.tif');
Jl= imtranslate(Kl,[-50,0],'FillValues',255);
imshow(Kl)
figure(),imshow(Jl)
set(gca,'Visible','on');
title('transated by [-50,0] with White filled')

MATLAB Results:

Page | 7
Ahmed Qureshi 2017-MC-307

Task#04:
Write a Matlab program to read a grayscale image (‘board.tif’). Rotate this image
by 90 anticlockwise and Create sub images of following components and place
suitable titles
1) U15
2) U21
3) C27
4) U20

MATLAB Code:
I=imread('board.tif');
J=imrotate(I,90);
K=imcrop(I,[82.5 97.5 57 45]);
imshow(J)
figure(),imshow(K)
title('U15')

Page | 8
Ahmed Qureshi 2017-MC-307

L=imcrop(I,[10.5 361.5 87 91]);


figure(),imshow(L)
title('U21')
M=imcrop(I,[87.5 499.5 16 32]);
figure(),imshow(M)
title('C27')
N=imcrop(I,[223.5 353.5 72 78]);
figure(),imshow(N)
title('U20')

MATLAB Result:

Page | 9
Ahmed Qureshi 2017-MC-307

Lab Session# 03 (Open Ended Lab)


Image acquisition using webcam and IP cameras in MATLAB
Reading your Webcam:
Your computer might be connected to more than one webcams, in order to list them,
we can the command>>webcamlist
>>
web
cam
list
ans
=

'Integrated Webcam'

My computer has only one webcam. To use this camera, we need to create an object of it.
% Create camera object and name it cam%
>> cam = webcam(1)
Note: Matlab may ask webcam support package installation, in that case click on the link in
command window and follow the steps. After installation, rerun above command.
Your webcam LED would be turn on but no video streaming would be seen on screen.

preview(camera object) would display images taken by webcam. So,

>> preview(cam)
Let’s take an image and store it in array img
>>img= snapshot(cam);
>>imshow(img)

Your Result:

To permanently store image on the computer, use imwrite(img, ‘name.format’) command


>>imwrite(img, 'yahoo.png');
After getting a number of images, close the preview and remove the cam object, so the
Page | 10
Ahmed Qureshi 2017-MC-307

webcam is turned off.


>>closePreview(cam)
>>clear cam

Use mobile camera in Matlab:


Are you interested in using your cell phone camera (a high resolution) in your engineering
project? If yes, you are at the right place! In this tutorial, we will configure mobile camera for
any robotic or vision project in Matlab

Configure your mobile:

Install IP Webcam app from Android app store.


After successful installation, open IP Webcam app and scroll down to the Start Server option
and begin server, a video streming will start and you will see a local host
address(http://192.168.8.100:8080) on the screen.
Open an internet browser and enter above local host address.
Click on Flash and you would be able to see your mobile camera streaming.

Right-click on screen and copy image address, you would be using this address in Matlab.

Page | 11
Ahmed Qureshi 2017-MC-307

Steps in Matlab:

% Create camera object and name it


mycam% cam =
ipcam('http://192.168.8.100:8080/vid
eo')
Note: Matlab may ask webcam support package installation, in that case click on the link in
command window and follow the steps. After installation, rerun above command.

>>preview(cam)
Let’s take an image and store it in array img
>>img= snapshot(cam);
>>imshow(img)
Your Result
To permanently store image on the computer, use imwrite(img, ‘name.format’) command
>>imwrite(img, 'yahoo.png');
After getting a number of images, close the preview and remove the cam object, so the
webcam is turned off.
>>closePreview(cam)
>>clear cam

To watch above demo,

https://www.youtube.com/channel/UCJA5xHsVppYct6zY

Page | 12
Ahmed Qureshi 2017-MC-307

SKePC9w

Task 01:
Write a MATLAB function to
 Acquire images from webcam at camera resolution (320x240) for 60 frames.
 Store them with naming 102MC01.jpg on local storage (102 is replaced with your
registration number and 01 is image number).
 Convert images frames into an avi video file with 20 fps to save on a local storage.

After successfully doing above steps, now make it a generic function as


MyImageCapture( camResolution, noFrames, videoName, storageLocation )
Upon execution,
MyImageCapture(‘320x240’, ‘60’,’machineVision’,’ D:\UET\MachineVision\’)
60 images and a video will be stored in given directory.

MATLAB Code:
function[] = MyImageCapture( camResolution, noFrames,
videoName); cd 'C:\Program Files\MATLAB\test';

cam = webcam(1);

cam.Resolution =
camResolution for idx =
1:noFrames

img = snapshot(cam);
filename = sprintf('148MC%02d.jpg', idx);
imwrite(img, filename);

end

video = VideoWriter(videoName); %create the video


object video.FrameRate =20;

open(video); %open the file for


writi for n = 1:noFrames

%K=
imread(['148MC',num2str(n),'.jpg']); K =
imread(sprintf('148MC%02d.jpg', n));
writeVideo(video,K)

end
close(video)

Page | 13
Ahmed Qureshi 2017-MC-307

implay(videoName);
end

MATLAB Snapshots:

Task 02:
MATLAB Code:
clear cam
function[] =
imagefun(cam.Resolution,
noFrames, videoName,
storageLocation);
storageLocation
cam=webcam;
for i=1:noFrames
A=snapshot(cam);
cam.Resolution=camresolution;
imwrite(A,
['133MC',num2str(i),'.jpg']);
end
v=VideoWriter(videoname);
v.FrameRate=20;
open(v)
for i=1:60

K=imread(['133MC',num2str(i),'.jpg']);
writeVideo(v,K)
end
close(v)
end

Page | 14
Ahmed Qureshi 2017-MC-307

Task 03:
MATLAB Code:
clear cam
function[] = imagefun(cam.Resolution, noFrames, videoName, storageLocation);
storageLocation
cam=webcam;
for i=1:noFrames
A=snapshot(cam);
cam.Resolution=camresolution;
imwrite(A,['133MC',num2str(i),'.jpg']);
video = VideoWriter(videoName); %create the video
object video.FrameRate =20;

open(video); %open the file for


writi for n = 1:noFrames

%K=
imread(['148MC',num2str(n),'.jpg']); K =
imread(sprintf('148MC%02d.jpg', n));
writeVideo(video,K)

end
close(video)

implay(videoName);
end

end
v=VideoWriter(videoname);
v.FrameRate=20;
open(v)
for i=1:60
K=imread(['133MC',num2str(i),'.jpg']);
writeVideo(v,K)
end
close(v)
end

Lab Session# 04
Implementation of point/pixel operations (image negative, scaling, power law
etc.) in MATLAB
Task#01:
1. From internet, search out two x-ray images and apply image negative for enhancements
purpose.
MATLAB Code:
A=imread('xray.jpg');% Place any image here
B=imcomplement(A);
imshowpair(A,B,'montage')

Page | 15
Ahmed Qureshi 2017-MC-307

A=imread('Knee_plain_X-ray.jpg');% Place any image here


B=imcomplement(A);
imshowpair(A,B,'montage')

MATLAB Results:

2. Search out a binary images from internet, and apply image negative

MATLAB Code:
A=imread('circles.png');% Place any image here
B=imcomplement(A);
imshowpair(A,B,'montage')

A=imread('logo.tif');
B=imcomplement(A);
imshowpair(A,B,'montage')

Page | 16
Ahmed Qureshi 2017-MC-307

MATLAB Results:

Task # 02:
Apply power law transformation to aerial satellite image (washed_out_aerial_image.tif) as
shown below, display all images in a subplot image with appropriate titles and gamma values
with shortest code.

MATLAB Code:
cd 'C:\Program Files\MATLAB\R2018a\toolbox\images\imdata\New Folder (3)'
I=imread('fractured spine.tif');
K=im2double(I);
Page | 17
Ahmed Qureshi 2017-MC-307

for i=0:0.2:0.6
J = imadjust(K, [0.2 0.3], [0.9 0.9], i);
figure;imshow(J);
end

MATLAB Results:

Lab Session# 05
Objective:
Firstly, Intensity level slicing would be implemented. Secondly, different noise addition to
images and smoothing filtering would be implemented.
Task # 01:
Write a m- file which takes a low contrast image as input and apply a intensity-level slicing
using transformation of Fig 3.11(a). Secondly, preserve the region of kidney and blood vessels
and dark out all other regions using transformation similar of Fig 3.11(b). Your function file
should display original image, resultant images in one figure as above.
MATLAB Code:
Page | 18
Ahmed Qureshi 2017-MC-307

I=imread('kidney.vessels.tif');
imshow(I)
for x=1:828;
for y=1:720;
if I(x,y)<=230&&I(x,y)>=150
p(x,y)=255;
else p(x,y)=0;
end
end
end
imshowpair(I,p,'montage')

MATLAB Results:

Task # 02: Implementing Averaging filter


Write an function to
1. Read a grayscale image (eight.tif).
2. Add three type of image noises with given values in Section imnoise to generate three noisy
images.
3. Apply averaging filters of sizes 5x5, 9x9, 15x15 with replicate padding on original image
and three noised images
4. Display original image, noisy images and their respective smoothed images with appropriate
titles in a subplot (4*4).

Page | 19
Ahmed Qureshi 2017-MC-307

MATLAB Code:

MATLAB Results:

Page | 20
Ahmed Qureshi 2017-MC-307

Task # 03: Advantage of median filter over averaging filter for noise removal
Write an m file to remove salt and pepper noise from image (circuit board). Apply averaging
filter and median filter
(medfilt2(img, [3, 3])) and display their results. (image in CH03 folder)

MATLAB Code:

MATLAB Results:

Page | 21
Ahmed Qureshi 2017-MC-307

Lab Session# 06
Objective:
MATLAB guide will be used to develop a graphical user interface (GUI) for vision processing
tasks such an image filtering, edge detection etc.
Task # 01: GUI Development for filters:
In this activity, an Image Filtering Application will be designed in MATLAB guide. The user
can browse images from any folder in the computer and can choose various filter types, border
padding options, filter sizes and the filtered image is displayed by pressing Apply button.
1. Open the Graphical user interface using Command Window

2. GUI Window

Page | 22
Ahmed Qureshi 2017-MC-307

3. Drag the widgets and use proper syntax for their tags.

4. Call back function for “browse push button”.

Page | 23
Ahmed Qureshi 2017-MC-307

5. Call back function for “choose filter” “push button”.

6. Call back function for “Effect” “slider”.

Page | 24
Ahmed Qureshi 2017-MC-307

7. Call back function for “Apply” “push button”.

Page | 25
Ahmed Qureshi 2017-MC-307

8. Final Output Window

Page | 26
Ahmed Qureshi 2017-MC-307

Lab Session# 07
Objective:
Simple object detection by implementing template matching technique using normalized cross
correlation on input image and given template.
Task # 01: Template Matching:
Write a function (circuit1, temp1) to
1. First read an input image (circuit1) and given template image (temp1).
2. Apply gray conversion on both images
3. Apply Normalized Cross Correlation (normxcorr2) between both images to detect all
instance of template image in input image
4. Visualize result of above step using 3D function surf (c)
5. Apply local maxima function and some thresholding value to detect only peaks where
correlation has maximum value
6. Draw input image along with bounding boxes of template size at each object location
7. Display the total number of template objects found on title of figure.
MATLAB Code:

Page | 27
Ahmed Qureshi 2017-MC-307

MATLAB Results:

Page | 28
Ahmed Qureshi 2017-MC-307

Lab Session# 08
Objective:

Page | 29
Ahmed Qureshi 2017-MC-307

Students will learn how to implement basic morphological operations such as image erosion,
dilation, image opening and closing.
Structuring Element:
se = strel( 'Type', Value);
se = strel( 'disk', 10);
Task # 01:
Image erosion:
Erosion is an operation that "shrinks" or "thin" objects in an image.
Img_erode = imerode(img, SE)
MATLAB Code:
I=imread('wirebond-mask.tif');
C=strel('disk',5);
D=strel('disk',10);
E=strel('disk',20);
subplot(2,2,1)
imshow(I)
subplot(2,2,2)
LE=imerode(I,C);
imshow(LE)
subplot(2,2,3)
ME=imerode(I,D);
imshow(ME)
subplot(2,2,4)
NE=imerode(I,E);
imshow(NE)

Result:

Task # 02:
Image Dilation:
Page | 30
Ahmed Qureshi 2017-MC-307

Dilation is an operation that "grows" or "thickens" objects in an image.


Img_dilate = imdilate(img, SE)
MATLAB Code:
I=imread('Broken_gaps.tif');
B=strel([0 1 0;1 1 1;0 1 0]);
C=strel('square',3);
Q=255-I;
subplot(1,3,1)
imshow(Q)
title('Original image')
subplot(1,3,2)
ME=imdilate(Q,B);
imshow(ME)
title('Cross St.element')
subplot(1,3,3)
NE=imdilate(Q,C);
imshow(NE)
title('Square st.element')

Results:

Task # 03: Application Example of morphological Operations:

Page | 31
Ahmed Qureshi 2017-MC-307

Import an image (testpat1.png) of a wheel and convert it to binary (if it is grayscale). Then,
using any morphological operation (erosion, dilation, opening, closing) and bwlabel() command,
you can count the number of spokes in the wheel. You can use similar techniques to count
objects in other intensity images.
MATAB Code:

Result:

Page | 32

You might also like