Recording a Video From Webcam Using MATLAB Code
Recording a Video From Webcam Using MATLAB Code is a very simple task if, you know how to access your webcam or other imaging device using MATLAB & snapping from them.
Click Here to know more about accessing Webcam using MATLAB code.
Click Here to know more about snapping an image from Webcam using MATLAB code.
Code:
clear all;
close all;
clc;
% Constructing a video input interface
vid = videoinput('winvideo',1,'YUY2_640x480');
% setting the frame rate as 12 (it will depend on your webcam device also)
set(vid,'FramesPerTrigger',12);
set(vid,'FrameGrabInterval',10);
start(vid);
wait(vid,Inf);
% Retrieve the frames and timestamps for each frame.
[frames,time] = getdata(vid, get(vid,'FramesAvailable'));
% Calculate frame rate by averaging difference between each frame's timestamp
framerate = mean(1./diff(time));
capturetime = 30;
%The FrameGrabInterval property specifies how often frames are stored from
%the video stream. For instance, if we set it to 5, then only 1 in 5 frames
%is kept -- the other 4 frames will be discarded. Using the framerate,
%determine how often you want to get frames
interval = get(vid,'FrameGrabInterval');
%To determine how many frames to acquire in total, calculate the total
%number of frames that would be acquired at the device's frame rate,
%and then divide by the FrameGrabInterval.
numframes = floor(capturetime * framerate / interval);
%If a large number of frames will be acquired, it is more practical to log
%the images to disk rather than to memory.
%Using the Image Acquisition Toolbox, you can log images directly %
%to an AVI file. We configure this using the LoggingMode property.
set(vid,'LoggingMode','disk');
%Create an AVI file object to log to, using the avifile command.
%We must specify the filename to use, and the frame rate that
%the AVI file should be played back at. Then, set the DiskLogger property
%of the video input object to the AVI file.
avi = avifile('timelapsevideo.avi','fps',framerate);
set(vid,'DiskLogger',avi);
start(vid);
wait(vid,Inf); % Wait for the capture to complete before continuing.
%Once the capture is completed, retrieve the AVI file object, and use the
%close function to release the resources associated with it.
wait(vid,Inf); % Wait for the capture to complete before continuing.
avi = get(vid,'DiskLogger');
avi = close(avi);
%When you are done with the video input object, you should use
%the delete function to free the hardware resources associated with it,
%and remove it from the workspace using the clear function.
delete(vid);
clear vid;
NOTE:
# After the code execution you will see a .avi video file in your
current working Directory as
timelapsevideo.avi.
# If the video file is completely black, your camera is slow & thus need some
warm up time to start off. So give delay of 1-2 seconds during the camera capturing
step.
# The following error/warning can also arise, the 1st one is due to the fact that
"avifile" function is obsolete now & MATLAB has decided to remove in further
releases.
The 2nd one is due to the fact that the following codec the MATLAB is trying to
use is not installed in your system, so either install it or change it or MATLAB
will self use the 'none' attribute in place of the codec.
Warning: AVIFILE will be removed in a future release. Use VIDEOWRITER instead.
> In avifile.avifile at 81
In img at 33
Warning: Cannot locate Indeo5 compressor, using 'None' as the compression type.
See Mathworks Technical Solution 1-4G50RI for more information.
An active & prominent author at Digital iVision Labs! Specializing in MATLAB, C++, Arduino, OpenCV, NI Labview, Web Designing & other Electronics stuffs! Just started M.Tech. From IIIT Delhi, looking for excellent PhD Opportunities with prominent researchers. Drop a mail: vibhutesh[at]gmail.com or Follow him at....
This comment has been removed by the author.
ReplyDeletesir ,
ReplyDeleteswitch on chay gane automatic ga video recording aye laga matlab lo program kavali sir plzzzzz send me sirrrrrrr
my mail id is [email protected] sir plzzz send meeeeeeeeeee
sir ,
ReplyDeleteswitch on chay gane automatic ga secret camera video recording aye laga matlab lo program kavali sir plzzzzz send me sirrrrrrr
my mail id is [email protected] sir plzzz send meeeeeeeeeee
Could You Post Your Comment In English....So That Anyone Could Be Able To Understand The Problem Your Are Facing & Help Accordingly....
Deletesir i want code for motion detection in a sample video using matlab with help of gui we can chance to operate.my mail id is
ReplyDelete[email protected]
Refer : http://www.divilabs.com/2013/11/motion-trackingdetection-in-matlab.html this link!
Deletehi if want to save avi vedio in particular folder so how can i do it plz tell
ReplyDeleteIn avi = avifile('timelapsevideo.avi','fps',framerate); instead of just timelapsevideo.avi provide the full folder path!
DeleteI want to detect weapon from a live video can any one help me plzz
ReplyDeleteI will suggest using OpenCV for this. If you just want to detect a particular weapon with a distinct shape You just need to train the classifier with the shape samples & more the samples you will be providing more the probability you get it detect correctly. But if in the video something that moves is a weapon (assuming) then you perform a motion detection, refer: http://www.divilabs.com/2013/11/motion-trackingdetection-in-matlab.html
DeleteDear Sir,
ReplyDeleteHow to set recording time and frame rate in this program. I want to record a video for 1 minute duration with a frame rate of 15 frames per second.
avi = avifile('timelapsevideo.avi','fps',framerate);
ReplyDeleteedit the frame rate variable to select 15fps recording
capturetime = 30;
Deleteedit this variable to set the capture,time in seconds.
Sir I have edited the program as per your instructions with Framerate=15 and capturetime=60. The program is now recording a video at 15 fps but only for time duration of 1 sec. How to set the time duration to 1 minute.
DeleteOk I will look into the matter & update you!
Deletehi sir,
ReplyDeletein my project i am using video chat(sip protocol)from server to client.is it possible to video chat through lan using gui matlab , if possible plsplspls.............reply me sir
email id - [email protected]
Never done it. So can't say much. But have a search on matlabcentral, you will find some answers of it.
Deletehow to view live video sequence from webcam and extract those frames into a selected folder
ReplyDeleteSearch over this website...I have uploaded them all. Just you need to search...!
Deleteerror:
ReplyDeletevid = videoinput('winvideo',1,'YUY2_640x480');
I recommend to read this article before this: http://www.divilabs.com/2013/11/accessing-webcam-through-matlab-code.html
DeleteActually in your system there might be some other video input adapter than 'winvideo' . So you need to check that.
sir I need matlab code plz will u provide it .. for dis Algor ithm 1 Entropy Based Things Merge
ReplyDelete1: Input:P, i terM ax
2: H0 ← H 0
P , i ← 0
3: while i ≤ i terM ax do
4: i ← i + 1
5: A,B ← random clusters from P
6: x ← random thing from A, x ∈ A
7: B ← x,(move x to B)
8: if Hi > Hi − 1 then
9: A ← x, (move x back to A)
10: end if
11: Hi ← H P
i
12: end while
13: Output: PH , new groups with a reduced entropy
Sorry, due to some serious time constraints I won't be able to help. But may be other visitors who are here, may be able to help you regarding this algo's implementation.
DeleteError in avifile (line 177)
ReplyDeleteaviobj.FileHandle = avi('open',filename);
Error in Untitled2 (line 41)
avi = avifile('timelapsevideo.avi','fps',framerate);
how to solve this?
Have you given the correct name for your video, try giving a absolute path of the video if the folder in which it is, not a current working folder, or not added to the path of matlab directory.
DeleteSir, i have used VideoWriter instead of avifile i.e. "writerObj=VideoWriter('timelapsevideo');"
ReplyDeletestill showing error: Error using VideoWriter (line 234)
Cannot create file C:\WINDOWS\system32\timelapsevideo.avi. The reason given is:
Permission denied
Error in Untitled2 (line 41)
writerObj=VideoWriter('timelapsevideo');
C:\WINDOWS\system32 is system folder, your matlab software might not have a permission to create or modify any files in it. Try to change the output directory to a non-system one.
Deletesir, video duration is just for 1 or 2 seconds. How can i increase recording length?
ReplyDeleteThere is a capturetime variable, change it to a large value so to get enough recording time.
DeleteThank you sir
ReplyDeleteSir, this code is for webcam. If we use camera with USB, should we need to make any modifications or this is enough?
ReplyDeleteuse the imaqhwinfo function to get the object constructor for your image acquisition device and substitute that syntax for the following code.
Deletevid = videoinput('winvideo',1);
Sir, i am unable to get you
ReplyDeleteI understood sir, thank you
ReplyDeleteSir, I want a webcam or an external camera to work( start recording video or take photos) only when it detects motion of some object in its range.Can we control this ON and OFF of the camera using MATLAB and how?
ReplyDeleteHello,
DeleteMotion detection through a webcam is possible in matlab. But sincerely advising you against it, since it will be very slow to be considered as Real Time.
Controlling device is also possible thorough MATLAB, but I have till now only tried with mouse & keyboard.
Sir, we are working on a project in which a camera will be sent in a pipeline which will send video input to matlab and detection of cracks inside pipe will done by matlab. Can you help us out with the coding sir?
ReplyDeleteExplicitly helping in coding will not be possible for me. But yes I could help, if you got struck somewhere.
DeleteSir i replaced the code line:avi = avifile('timelapsevideo.avi','fps',framerate);
ReplyDeletewith this:avi = VideoWriter('C:\Users\HP\Desktop\PICS USED\timelapsevideo','Uncompressed AVI');
as i didn't have the required permission.
But now i am getting following error:
Error using VideoWriter/close
Too many output arguments.
Error in videocapture (line 54)
avi = close(avi);
set "avi = close(avi);" as only "close(avi)". Since this command doesn't have any output argument.
DeleteNow i am getting new error
ReplyDeleteUnable to allocate memory for an incoming image frame. Use IMAQMEM to modify the frame
memory limit.
Please help and thnx for quick reply to previous question.
Your MATLAB is running out of memory. Use IMAQMEM to modify the frame memory limit.
DeleteHOW to do it?
ReplyDeleteon typing imaqmem shows:
MemoryLoad: 76
TotalPhys: 4.2235e+09
AvailPhys: 981590016
TotalPageFile: 5.4609e+09
AvailPageFile: 846770176
TotalVirtual: 1.4074e+14
AvailVirtual: 1.4073e+14
FrameMemoryLimit: 1.0000e+09
FrameMemoryUsed: 999936000
Use it like this,
Deleteimaqmem(LIMIT)
say for example, imaqmem(2.0e+09)
Ok i incresed the limit.
ReplyDeletebut i want to know to deallocate the space which is already taken up and not required for processing in order to save memory.
Using flushdata?
ReplyDeletehow to use flushdata?
Yes, its flushdata.
DeleteYou need to use it like, flushdata(object_created), it will flush the memory content of "object_created" object.
Thank you very much for your previous replies.
ReplyDeleteI have one new problem now, you told that to increase the length of recorded video just change(increase) the value of capturetime variable but it seems to have to have no effect.
Any solution?
Sir I want a code that records a video form external webcam for GUI. Also start and stop of video should be manual. Can u please suggest the code for the same ?
ReplyDeleteYou need to search file-exchange at matlabcentral, if something like that exist. Other wise you need to build the same. I guess playing and pausing MATlAB GUI you could be able to find.
DeleteOf you have MATLAB IMAQ, it most probably have that feature.
Sir, I got stuck at trigger configuration . Can you help me?
ReplyDeleteHi, Give me some more details, so that I can help.
DeleteSir, I got stuck at trigger configuration . Can you help me?
ReplyDeleteHi, Give me some more details, so that I can help.
DeleteSir,I have got stuck in trigger configuration. Can you help me?
ReplyDeleteHi, Give me some more details, so that I can help.
DeleteSir, I want to do this code for real time video. Can you help??? Please
ReplyDeleteHi sir!!!!
ReplyDeleteCan u plz send me a code for real time capturing? I need it for real time object detection.I'm using Matlab R2015a.The code should capture the video,convert it to frames and detect the object.
ReplyDeleteHello, Sir
I am working on CMOS camera as a receiver. i need OOK Matlab coding for modulating and demodulate data. I am very thankful for you if you help me in this part.