How do I record video from a webcam in MATLAB?

matlab, video, video-recording, webcam

Solution

NOTE: This is now updated for use with newer versions of MATLAB, since some of the older functionality has been superseded and removed.

If you already know how to capture a single image from a webcam, then it should just be a matter of stitching the images together into a movie. You can use a `VideoWriter` object to open a movie file and then add sequential images using the `writeVideo` method. For example:

aviObject = VideoWriter('myVideo.avi');  % Create a new AVI file
for iImage = 1:100                       % Capture 100 frames
  % ...
  % You would capture a single image I from your webcam here
  % ...
  writeVideo(aviObject, I);  % Add the image to the AVI file
end
close(aviObject);  % Close the AVI file

I just used a for loop as a simple example, but you may want to use a `timer` if you instead want to capture images and add them to the AVI file at regular time intervals.

Problem

I would like to know how I can record a video in MATLAB with my webcam.

Original source