Main Content

Try Deep Learning in 10 Lines of MATLAB Code

This example shows how to use deep learning to identify objects on a live webcam using only 10 lines of MATLAB® code. Try the example to see how simple it is to get started with deep learning in MATLAB.

  1. Run these commands to get the downloads if needed, connect to the webcam, and get a pretrained neural network.

    camera = webcam;  % Connect to the camera
    net = squeezenet; % Load the neural network

    If you need to install the webcam add-on, a message from the function appears with a link to help you download the free add-on using Add-On Explorer. Alternatively, see MATLAB Support Package for USB Webcams.

    SqueezeNet is a pretrained convolutional neural network (CNN) that has been trained on more than a million images and can classify images into 1000 object categories (for example, keyboard, mouse, coffee mug, pencil, and many animals).

  2. Run the following code to show and classify live images. Point the webcam at an object and the neural network reports what class of object it thinks the webcam is showing. It will keep classifying images until you press Ctrl+C. The code resizes the image for the network using imresize.

    while true
        im = snapshot(camera);       % Take a picture
        image(im);                   % Show the picture
        im = imresize(im,[227 227]); % Resize the picture for squeezenet
        label = classify(net,im);    % Classify the picture
        title(char(label));          % Show the class label
        drawnow
    end

    In this example, the network correctly classifies a coffee mug. Experiment with objects in your surroundings to see how accurate the network is.

    Webcam image of a mug with the title displaying the predicted class ("coffee mug")

    To watch a video of this example, see Deep Learning in 11 Lines of MATLAB Code.

    To learn how to extend this example and show the probability scores of classes, see Classify Webcam Images Using Deep Learning.

    For next steps in deep learning, you can use the pretrained network for other tasks. Solve new classification problems on your image data with transfer learning or feature extraction. For examples, see Start Deep Learning Faster Using Transfer Learning and Train Classifiers Using Features Extracted from Pretrained Networks. To try other pretrained networks, see Pretrained Deep Neural Networks.

See Also

| | |

Related Topics