Hello friends, hope you all are fine and having fun with your lives. Today, I am going to share a new project which is Motion Detection in MATLAB. In this project, I am gonna detect the motion in MATLAB. This project was designed for security purposes and the condition was to use MATLAB instead of PIR Sensor. We all know that PIR sensor is used for motion detection but for that we have to design a hardware but using this software we can easily detect any motion using MATLAB.
In this project, I have used the webcam and then applied a simple image processing algorithm, designed in MATLAB. Using this algorithm I have detected the motion in the environment. That's a quite simple project and you are gonna like this one. The code and complete simulation is given below for download. So, let's get started with Motion Detection in MATLAB:
You may also like:
In the above code, first of all, I created an object of the webcam and then took a screenshot from that webcam.
After that I saved that image in the project directory and named it as A.jpg.
If you check your project directory then you will find this image.
Now let's have a look at the code behind Start Comparison Button:
go = true;
obj.ReturnedColorspace = 'rgb';
I1 = imread('A.jpg');
I2 = imread('B.jpg');
% convert images to type double (range from from 0 to 1 instead of from 0 to 255)
Imaged1 = im2double(I1);
Imaged2 = im2double(I2);
% reduce three channel [ RGB ] to one channel [ grayscale ]
Imageg1 = rgb2gray(Imaged1);
Imageg2 = rgb2gray(Imaged2);
% Calculate the Normalized Histogram of Image 1 and Image 2
hn1 = imhist(Imageg1)./numel(Imageg1);
hn2 = imhist(Imageg2)./numel(Imageg2);
% Calculate the histogram error/ Difference
f1 = sum((hn1 - hn2).^2);
serialOne=serial('COM1', 'BaudRate', 9600);
if f1 > 0.009
go = false;
if f1 < 0.009
This is the main code of this Motion detection in MATLAB project.
Here, again I am creating an object of the webcam and taking a screenshot.
After that I am saving this screenshot in the project's directory and I have renamed it as B.jpg.
So, now I have two images A and B.
After that I have converted both of these images to grey scale and calculated their histogram error and on the basis of this error I have detected the motion.
Finally I have created a Serial Port object, if you don't wanna use serial port then simply remove this code.
So, that's all for today, I hope you have enjoyed the motion detection in MATLAB. If you have any questions, then ask in comments and I will resolve them.
I am Syed Zain Nasir, the founder of The Engineering Projects (TEP). I am a
programmer since 2009 before that I just search things, make small projects and now I am sharing my
knowledge through this platform. I also work as a freelancer and did many projects related to
programming and electrical circuitry. My Google Profile+Follow