# 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.

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.

1. This comment has been removed by the author.

2. sir ,
switch 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

3. sir ,
switch 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

1. Could You Post Your Comment In English....So That Anyone Could Be Able To Understand The Problem Your Are Facing & Help Accordingly....

4. sir 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
[email protected]

1. Refer : http://www.divilabs.com/2013/11/motion-trackingdetection-in-matlab.html this link!

5. hi if want to save avi vedio in particular folder so how can i do it plz tell

1. In avi = avifile('timelapsevideo.avi','fps',framerate); instead of just timelapsevideo.avi provide the full folder path!

6. I want to detect weapon from a live video can any one help me plzz

1. I 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

7. Dear Sir,
How 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.

8. avi = avifile('timelapsevideo.avi','fps',framerate);
edit the frame rate variable to select 15fps recording

1. capturetime = 30;

edit this variable to set the capture,time in seconds.

2. 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.

3. Ok I will look into the matter & update you!

9. hi sir,
in 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]

1. Never done it. So can't say much. But have a search on matlabcentral, you will find some answers of it.

10. how to view live video sequence from webcam and extract those frames into a selected folder

1. Search over this website...I have uploaded them all. Just you need to search...!

11. error:
vid = videoinput('winvideo',1,'YUY2_640x480');

Actually in your system there might be some other video input adapter than 'winvideo' . So you need to check that.

12. sir I need matlab code plz will u provide it .. for dis Algor ithm 1 Entropy Based Things Merge
1: 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

1. 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.

13. Error in avifile (line 177)
aviobj.FileHandle = avi('open',filename);

Error in Untitled2 (line 41)
avi = avifile('timelapsevideo.avi','fps',framerate);

how to solve this?

1. 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.

14. Sir, i have used VideoWriter instead of avifile i.e. "writerObj=VideoWriter('timelapsevideo');"

still 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');

1. 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.

15. sir, video duration is just for 1 or 2 seconds. How can i increase recording length?

1. There is a capturetime variable, change it to a large value so to get enough recording time.

16. Thank you sir

17. Sir, this code is for webcam. If we use camera with USB, should we need to make any modifications or this is enough?

1. use the imaqhwinfo function to get the object constructor for your image acquisition device and substitute that syntax for the following code.

vid = videoinput('winvideo',1);

18. Sir, i am unable to get you

19. I understood sir, thank you

20. Sir, 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?

1. Hello,
Motion 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.

21. 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?

1. Explicitly helping in coding will not be possible for me. But yes I could help, if you got struck somewhere.

22. Sir i replaced the code line:avi = avifile('timelapsevideo.avi','fps',framerate);
with 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);

1. set "avi = close(avi);" as only "close(avi)". Since this command doesn't have any output argument.

23. Now i am getting new error
Unable to allocate memory for an incoming image frame. Use IMAQMEM to modify the frame
memory limit.

1. Your MATLAB is running out of memory. Use IMAQMEM to modify the frame memory limit.

24. HOW to do it?

on typing imaqmem shows:
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

1. Use it like this,
imaqmem(LIMIT)

say for example, imaqmem(2.0e+09)

25. Ok i incresed the limit.
but i want to know to deallocate the space which is already taken up and not required for processing in order to save memory.

26. Using flushdata?

how to use flushdata?

1. Yes, its flushdata.
You need to use it like, flushdata(object_created), it will flush the memory content of "object_created" object.

27. Thank you very much for your previous replies.
I 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?

28. 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 ?

1. You 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.
Of you have MATLAB IMAQ, it most probably have that feature.

29. Sir, I got stuck at trigger configuration . Can you help me?

1. Hi, Give me some more details, so that I can help.

30. Sir, I got stuck at trigger configuration . Can you help me?

1. Hi, Give me some more details, so that I can help.

31. Sir,I have got stuck in trigger configuration. Can you help me?

1. Hi, Give me some more details, so that I can help.

32. Sir, I want to do this code for real time video. Can you help??? Please

33. Hi sir!!!!
Can 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.

34. Hello, 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.

35. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. adult live webcams

36. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. iRec