Main Content

Acquiring a Single Image in a Loop

This example shows how to use the snapshot function to acquire live images from USB webcams.

MATLAB® Support Package for USB Webcams provides the ability to bring live images from any USB video class (UVC) compliant webcam into MATLAB.

Identifying Available Webcams

The webcamlist function provides a cell array of webcams on the current system that MATLAB can access.

camList = webcamlist
camList = 1×1 cell array
    {'Logitech Webcam 250'}

Set up Connection to Webcam

A webcam object represents the connection between MATLAB® and the USB webcam. To create a connection to the webcam, use the webcam function and indicate what camera to connect to. You can specify the camera either by name or index as returned by webcamlist. This example uses the "Logitech Webcam 250" camera. Once the connection is established, you can access specific property values by using the dot(.) notation.

% Connect to the webcam.
cam = webcam(1)
cam = 
  webcam with properties:

                     Name: 'Logitech Webcam 250'
     AvailableResolutions: {'640x480'  '160x90'  '160x100'  '160x120'  '176x144'  '320x180'  '320x200'  '320x240'  '352x288'  '640x360'  '640x400'}
               Resolution: '640x480'
                Sharpness: 48
                 Contrast: 32
                     Gain: 63
             WhiteBalance: 0
             ExposureMode: 'auto'
                 Exposure: -6
               Brightness: 128
    BacklightCompensation: 1
               Saturation: 32

Preview Video Stream

To open a video preview window, use the preview function. The video preview window displays the live video stream from the device.

preview(cam);

Acquire a Frame

To acquire a single frame, use the snapshot function.

img = snapshot(cam);

% Display the frame in a figure window.
image(img);

Acquiring Multiple Frames

A common task is to repeatedly acquire a single image, process it, and then store the result. To do this, snapshot should be called in a loop.

for idx = 1:5
    img = snapshot(cam);
    image(img);
end

Clean Up

Once the connection is no longer needed, clear the associated variable.

clear cam