Main Content

Acquire Webcam Images in a Loop

The snapshot function acquires a single image from a webcam. If you want to acquire images in a loop, you can do that with some extra programming.

This example uses MATLAB® and Image Processing Toolbox™ to find circles in a video stream from a webcam.

  1. Create a webcam object called cam, using a Logitech® webcam.

    cam = webcam('Logitech')
    
    cam =
     
      webcam with properties:
     
                         Name: 'Logitech Webcam C925e'
                   Resolution: '640x480'
         AvailableResolutions: {'2304x1536'  '2304x1296'  '1920x1080'  '1600x896'  '1280x720'  '960x720'  '1024x576'  '800x600'  '864x480'  '800x448'  '640x480'  '640x360'  '432x240'  '352x288'  '320x240'  '320x180'  '176x144'  '160x120'  '160x90'}
        BacklightCompensation: 0
                   Brightness: 128
                     Contrast: 128
                     Exposure: -5
                 ExposureMode: 'auto'
                        Focus: 0
                    FocusMode: 'auto'
                         Gain: 0
                          Pan: 0
                   Saturation: 128
                    Sharpness: 128
                         Tilt: 0
                 WhiteBalance: 4000
             WhiteBalanceMode: 'auto'
                         Zoom: 100

    Note

    The only properties available in MATLAB Online™ are Name, AvailableResolutions, and Resolution. The default resolution of the webcam is the only resolution supported in MATLAB Online for the R2018a release.

  2. Preview the image.

    preview(cam)
    
  3. Set any properties that you need to change. For example, you might want to change the brightness, if the camera supports that device-specific property.

    cam.Brightness = 128;
    

    For more information on what properties you can set for webcams and how to set the properties, see Set Properties for Webcam Acquisition.

  4. Create the loop and perform processing.

    for idx = 1:100
       % Acquire a single image.
       rgbImage = snapshot(cam);
    
       % Convert RGB to grayscale.
       grayImage = rgb2gray(rgbImage);
    
       % Find circles.
       [centers, radii] = imfindcircles(grayImage, [60 80]);
    
       % Display the image.
       imshow(rgbImage);
       hold on;
       viscircles(centers, radii);
       drawnow
    end
  5. Clean up by clearing the object.

    clear('cam');

For more information on creating a webcam object and acquiring single snapshots, see Acquire Images from Webcams. For a list of the functions you can use with the webcam support, see Supported Functions for Webcam.

See Also

| |

Related Topics