Main Content


Detect objects using R-CNN deep learning detector


bboxes = detect(detector,I) detects objects within image I using an R-CNN (regions with convolutional neural networks) object detector. The locations of objects detected are returned as a set of bounding boxes.

When using this function, use of a CUDA® enabled NVIDIA® GPU is highly recommended. The GPU reduces computation time significantly. Usage of the GPU requires Parallel Computing Toolbox™. For information about the supported compute capabilities, see GPU Computing Requirements (Parallel Computing Toolbox).

[bboxes,scores] = detect(detector,I) also returns the detection scores for each bounding box.


[___,labels] = detect(detector,I) also returns a categorical array of labels assigned to the bounding boxes, using either of the preceding syntaxes. The labels used for object classes are defined during training using the trainRCNNObjectDetector function.

[___] = detect(___,roi) detects objects within the rectangular search region specified by roi.

[___] = detect(___,Name=Value) specifies options using one or more name-value arguments in addition to any combination of arguments from previous syntaxes.


collapse all

Load training data and network layers.

load('rcnnStopSigns.mat', 'stopSigns', 'layers')

Add the image directory to the MATLAB path.

imDir = fullfile(matlabroot, 'toolbox', 'vision', 'visiondata',...

Set network training options to use mini-batch size of 32 to reduce GPU memory usage. Lower the InitialLearnRate to reduce the rate at which network parameters are changed. This is beneficial when fine-tuning a pre-trained network and prevents the network from changing too rapidly.

options = trainingOptions('sgdm', ...
  'MiniBatchSize', 32, ...
  'InitialLearnRate', 1e-6, ...
  'MaxEpochs', 10);

Train the R-CNN detector. Training can take a few minutes to complete.

rcnn = trainRCNNObjectDetector(stopSigns, layers, options, 'NegativeOverlapRange', [0 0.3]);
Training an R-CNN Object Detector for the following object classes:

* stopSign

--> Extracting region proposals from 27 training images...done.

--> Training a neural network to classify objects in training data...

Training on single CPU.
Initializing input data normalization.
|  Epoch  |  Iteration  |  Time Elapsed  |  Mini-batch  |  Mini-batch  |  Base Learning  |
|         |             |   (hh:mm:ss)   |   Accuracy   |     Loss     |      Rate       |
|       1 |           1 |       00:00:01 |       96.88% |       0.1651 |      1.0000e-06 |
|       2 |          50 |       00:00:15 |       96.88% |       0.0807 |      1.0000e-06 |
|       3 |         100 |       00:00:27 |       96.88% |       0.1340 |      1.0000e-06 |
|       5 |         150 |       00:00:38 |       96.88% |       0.0225 |      1.0000e-06 |
|       6 |         200 |       00:00:49 |       93.75% |       0.6584 |      1.0000e-06 |
|       8 |         250 |       00:01:00 |       93.75% |       0.5233 |      1.0000e-06 |
|       9 |         300 |       00:01:11 |      100.00% |   2.9456e-05 |      1.0000e-06 |
|      10 |         350 |       00:01:23 |      100.00% |       0.0009 |      1.0000e-06 |
Training finished: Max epochs completed.

Network training complete.

--> Training bounding box regression models for each object class...100.00%...done.

Detector training complete.

Test the R-CNN detector on a test image.

img = imread('stopSignTest.jpg');

[bbox, score, label] = detect(rcnn, img, MiniBatchSize=32);

Display strongest detection result.

[score, idx] = max(score);

bbox = bbox(idx, :);
annotation = sprintf('%s: (Confidence = %f)', label(idx), score);

detectedImg = insertObjectAnnotation(img, 'rectangle', bbox, annotation);


Remove the image directory from the path.


Input Arguments

collapse all

R-CNN object detector, specified as an rcnnObjectDetector object. To create this object, call the trainRCNNObjectDetector function with training data as input.

Input image, specified as an H-by-W-by-C numeric array of images. Images must be real, nonsparse, grayscale or RGB image.

  • H: Height

  • W: Width

  • C: The channel size in each image must be equal to the network's input channel size. For example, for grayscale images, C must be equal to 1. For RGB color images, it must be equal to 3.

The detector is sensitive to the range of the input image. Therefore, ensure that the input image range is similar to the range of the images used to train the detector. For example, if the detector was trained on uint8 images, rescale this input image to the range [0, 255] by using the im2uint8 or rescale function. The size of this input image should be comparable to the sizes of the images used in training. If these sizes are very different, the detector has difficulty detecting objects because the scale of the objects in the input image differs from the scale of the objects the detector was trained to identify. Consider whether you used the SmallestImageDimension property during training to modify the size of training images.

Data Types: uint8 | uint16 | int16 | double | single | logical

Search region of interest, specified as an [x y width height] vector. The vector specifies the upper left corner and size of a region in pixels.

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: detect(detector,I,NumStrongestRegions=1000) limits the number of strongest region proposals to 1000.

Maximum number of strongest region proposals, specified as an integer. Reduce this value to speed up processing time at the cost of detection accuracy. To use all region proposals, specify this value as Inf.

Select strongest bounding box for each detected object, specified as a logical true or false, where:

  • true — Return the strongest bounding box per object. To select these boxes, detect calls the selectStrongestBboxMulticlass function, which uses nonmaximal suppression to eliminate overlapping bounding boxes based on their scores.

    For example:

     selectStrongestBboxMulticlass(bbox,scores, ...
                'RatioType','Min', ...

  • false — Return all detected bounding boxes. You can then use a custom operation to eliminate overlapping bounding boxes.

Size of smaller batches for R-CNN data processing, specified as an integer. Larger batch sizes lead to faster processing but take up more memory.

Hardware resource on which to run the detector, specified as "auto", "gpu", or "cpu". The table shows the valid hardware resource values.

Resource Action
"auto"Use a GPU if it is available. Otherwise, use the CPU.
"gpu"Use the GPU. To use a GPU, you must have Parallel Computing Toolbox and a CUDA enabled NVIDIA GPU. If a suitable GPU is not available, the function returns an error. For information about the supported compute capabilities, see GPU Computing Requirements (Parallel Computing Toolbox).
"cpu"Use the CPU.

Output Arguments

collapse all

Location of objects detected within the image, returned as an M-by-4 matrix defining M bounding boxes. Each row of bboxes contains a four-element vector of the form [x y width height]. This vector specifies the upper left corner and size of a bounding box in pixels.

Detection scores, returned as an M-by-1 vector. A higher score indicates higher confidence in the detection.

Labels for bounding boxes, returned as an M-by-1 categorical array of M labels. You define the class names used to label the objects when you train the input detector.

Version History

Introduced in R2016b