Object Detection - Quick Start

Note: AutoGluon ObjectDetector will be deprecated in v0.7. Please try our AutoGluon MultiModalPredictor for more functionalities and better support for your object detection need.

Object detection is the process of identifying and localizing objects in an image and is an important task in computer vision. Follow this tutorial to learn how to use AutoGluon for object detection.

Tip: If you are new to AutoGluon, review Image Prediction - Quick Start first to learn the basics of the AutoGluon API.

Our goal is to detect motorbike in images by YOLOv3 model. A tiny dataset is collected from VOC dataset, which only contains the motorbike category. The model pretrained on the COCO dataset is used to fine-tune our small dataset. With the help of AutoGluon, we are able to try many models with different hyperparameters automatically, and return the best one as our final model.

To start, import ObjectDetector:

from autogluon.vision import ObjectDetector
/home/ci/opt/venv/lib/python3.8/site-packages/gluoncv/__init__.py:40: UserWarning: Both mxnet==1.9.1 and torch==1.12.1+cu102 are installed. You might encounter increased GPU memory footprint if both framework are used at the same time.
  warnings.warn(f'Both mxnet=={mx.__version__} and torch=={torch.__version__} are installed. '
INFO:matplotlib.font_manager:generated new fontManager
INFO:torch.distributed.nn.jit.instantiator:Created a temporary directory at /tmp/tmpsx3wq63k
INFO:torch.distributed.nn.jit.instantiator:Writing /tmp/tmpsx3wq63k/_remote_module_non_scriptable.py
INFO:root:Generating grammar tables from /usr/lib/python3.8/lib2to3/Grammar.txt
INFO:root:Generating grammar tables from /usr/lib/python3.8/lib2to3/PatternGrammar.txt

Tiny_motorbike Dataset

We collect a toy dataset for detecting motorbikes in images. From the VOC dataset, images are randomly selected for training, validation, and testing - 120 images for training, 50 images for validation, and 50 for testing. This tiny dataset follows the same format as VOC.

Using the commands below, we can download this dataset, which is only 23M. The name of unzipped folder is called tiny_motorbike. Anyway, the task dataset helper can perform the download and extraction automatically, and load the dataset according to the detection formats.

url = 'https://autogluon.s3.amazonaws.com/datasets/tiny_motorbike.zip'
dataset_train = ObjectDetector.Dataset.from_voc(url, splits='trainval')
Downloading /home/ci/.gluoncv/archive/tiny_motorbike.zip from https://autogluon.s3.amazonaws.com/datasets/tiny_motorbike.zip...
21273KB [00:01, 18385.57KB/s]
tiny_motorbike/
├── Annotations/
├── ImageSets/
└── JPEGImages/

Fit Models by AutoGluon

In this section, we demonstrate how to apply AutoGluon to fit our detection models. We use mobilenet as the backbone for the YOLOv3 model. Two different learning rates are used to fine-tune the network. The best model is the one that obtains the best performance on the validation dataset. You can also try using more networks and hyperparameters to create a larger searching space.

We fit a classifier using AutoGluon as follows. In each experiment (one trial in our searching space), we train the model for 5 epochs to avoid bursting our tutorial runtime.

time_limit = 60*30  # at most 0.5 hour
detector = ObjectDetector()
hyperparameters = {'epochs': 5, 'batch_size': 8}
hyperparameter_tune_kwargs={'num_trials': 2}
detector.fit(dataset_train, time_limit=time_limit, hyperparameters=hyperparameters, hyperparameter_tune_kwargs=hyperparameter_tune_kwargs)
=============================================================================
WARNING: ObjectDetector is deprecated as of v0.4.0 and may contain various bugs and issues!
In a future release ObjectDetector may be entirely reworked to use Torch as a backend.
This future change will likely be API breaking.Users should ensure they update their code that depends on ObjectDetector when upgrading to future AutoGluon releases.
For more information, refer to ObjectDetector refactor GitHub issue: https://github.com/autogluon/autogluon/issues/1559
=============================================================================

The number of requested GPUs is greater than the number of available GPUs.Reduce the number to 1
Randomly split train_data into train[156]/validation[14] splits.
Starting HPO experiments
  0%|          | 0/2 [00:00<?, ?it/s]
INFO:SSDEstimator:modified configs(<old> != <new>): {
INFO:SSDEstimator:root.gpus            (0, 1, 2, 3) != (0,)
INFO:SSDEstimator:root.valid.batch_size 16 != 8
INFO:SSDEstimator:root.dataset_root    ~/.mxnet/datasets/ != auto
INFO:SSDEstimator:root.train.early_stop_patience -1 != 10
INFO:SSDEstimator:root.train.batch_size 16 != 8
INFO:SSDEstimator:root.train.seed      233 != 326
INFO:SSDEstimator:root.train.early_stop_baseline 0.0 != -inf
INFO:SSDEstimator:root.train.early_stop_max_value 1.0 != inf
INFO:SSDEstimator:root.train.epochs    20 != 5
INFO:SSDEstimator:root.dataset         voc_tiny != auto
INFO:SSDEstimator:root.num_workers     4 != 8
INFO:SSDEstimator:root.ssd.data_shape  300 != 512
INFO:SSDEstimator:root.ssd.base_network vgg16_atrous != resnet50_v1
INFO:SSDEstimator:}
INFO:SSDEstimator:Saved config to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/79538aeb/.trial_0/config.yaml
INFO:SSDEstimator:Using transfer learning from ssd_512_resnet50_v1_coco, the other network parameters are ignored.
INFO:root:Model file not found. Downloading.
Downloading /home/ci/.mxnet/models/ssd_512_resnet50_v1_coco-c4835162.zip from https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/gluon/models/ssd_512_resnet50_v1_coco-c4835162.zip...
  0%|          | 0/181188 [00:00<?, ?KB/s]
  0%|          | 101/181188 [00:00<03:31, 856.17KB/s]
  0%|          | 504/181188 [00:00<01:16, 2357.13KB/s]
  1%|          | 2182/181188 [00:00<00:23, 7718.59KB/s]
  5%|▍         | 8331/181188 [00:00<00:06, 26769.18KB/s]
  8%|▊         | 14281/181188 [00:00<00:04, 37766.27KB/s]
 11%|█         | 20376/181188 [00:00<00:03, 45281.18KB/s]
 16%|█▌        | 28961/181188 [00:00<00:02, 54830.00KB/s]
 21%|██        | 37960/181188 [00:00<00:02, 61807.53KB/s]
 26%|██▌       | 47201/181188 [00:00<00:01, 70612.26KB/s]
 30%|██▉       | 54341/181188 [00:01<00:01, 70840.36KB/s]
 34%|███▍      | 61590/181188 [00:01<00:01, 71324.09KB/s]
 39%|███▉      | 70749/181188 [00:01<00:01, 77314.76KB/s]
 43%|████▎     | 78524/181188 [00:01<00:01, 76779.95KB/s]
 48%|████▊     | 86232/181188 [00:01<00:01, 76483.59KB/s]
 53%|█████▎    | 95614/181188 [00:01<00:01, 78439.93KB/s]
 58%|█████▊    | 104926/181188 [00:01<00:00, 82676.78KB/s]
 62%|██████▏   | 113212/181188 [00:01<00:00, 81734.13KB/s]
 67%|██████▋   | 121399/181188 [00:01<00:00, 81188.71KB/s]
 72%|███████▏  | 130812/181188 [00:02<00:00, 82989.14KB/s]
 77%|███████▋  | 139535/181188 [00:02<00:00, 84216.80KB/s]
 82%|████████▏ | 147962/181188 [00:02<00:00, 83161.80KB/s]
 86%|████████▋ | 156296/181188 [00:02<00:00, 82993.09KB/s]
 91%|█████████▏| 165453/181188 [00:02<00:00, 85512.47KB/s]
181189KB [00:02, 69220.50KB/s]
INFO:SSDEstimator:Start training from [Epoch 0]
INFO:SSDEstimator:[Epoch 0] Training cost: 11.207714, CrossEntropy=3.685083, SmoothL1=1.036739
INFO:SSDEstimator:[Epoch 0] Validation:
bus=nan
motorbike=0.4512357618740597
dog=nan
bicycle=0.0
cow=nan
chair=nan
pottedplant=nan
person=0.7547984556835007
car=0.5627705627705627
boat=nan
mAP=0.4422011950820308
INFO:SSDEstimator:[Epoch 0] Current best map: 0.442201 vs previous 0.000000, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/79538aeb/.trial_0/best_checkpoint.pkl
INFO:SSDEstimator:[Epoch 1] Training cost: 7.974542, CrossEntropy=2.881525, SmoothL1=1.347418
INFO:SSDEstimator:[Epoch 1] Validation:
bus=nan
motorbike=0.83452931744135
dog=nan
bicycle=0.0
cow=nan
chair=nan
pottedplant=nan
person=0.8976889833667329
car=0.6658376214979987
boat=nan
mAP=0.5995139805765204
INFO:SSDEstimator:[Epoch 1] Current best map: 0.599514 vs previous 0.442201, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/79538aeb/.trial_0/best_checkpoint.pkl
INFO:SSDEstimator:[Epoch 2] Training cost: 7.465841, CrossEntropy=2.408597, SmoothL1=1.045704
INFO:SSDEstimator:[Epoch 2] Validation:
bus=nan
motorbike=0.9325757575757578
dog=nan
bicycle=0.0
cow=nan
chair=nan
pottedplant=nan
person=0.9954545454545456
car=0.5790569997724396
boat=nan
mAP=0.6267718257006858
INFO:SSDEstimator:[Epoch 2] Current best map: 0.626772 vs previous 0.599514, saved to /home/ci/autogluon/docs/_build/eval/tutorials/object_detection/79538aeb/.trial_0/best_checkpoint.pkl
INFO:SSDEstimator:[Epoch 3] Training cost: 8.164927, CrossEntropy=2.475813, SmoothL1=1.169681
INFO:SSDEstimator:[Epoch 3] Validation:
bus=nan
motorbike=0.820791418919761
dog=nan
bicycle=0.0
cow=nan
chair=nan
pottedplant=nan
person=0.7739898989898989
car=0.6408402203856748
boat=nan
mAP=0.5589053845738337
INFO:SSDEstimator:[Epoch 4] Training cost: 7.503358, CrossEntropy=2.203998, SmoothL1=1.062197
INFO:SSDEstimator:[Epoch 4] Validation:
bus=nan
motorbike=0.8340909090909092
dog=nan
bicycle=0.0
cow=nan
chair=nan
pottedplant=nan
person=0.9619218500797448
car=0.5172909294411595
boat=nan
mAP=0.5783259221529534
INFO:SSDEstimator:Applying the state from the best checkpoint...
INFO:root:Model file not found. Downloading.
Downloading /home/ci/.mxnet/models/resnet50_v1-cc729d95.zip from https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/gluon/models/resnet50_v1-cc729d95.zip...
  0%|          | 0/57421 [00:00<?, ?KB/s]
  0%|          | 148/57421 [00:00<00:39, 1457.97KB/s]
  1%|          | 637/57421 [00:00<00:16, 3431.99KB/s]
  3%|▎         | 1584/57421 [00:00<00:09, 6149.26KB/s]
  5%|▌         | 3008/57421 [00:00<00:05, 9289.77KB/s]
  9%|▉         | 5152/57421 [00:00<00:03, 13612.77KB/s]
 15%|█▍        | 8336/57421 [00:00<00:02, 19772.95KB/s]
 23%|██▎       | 13136/57421 [00:00<00:01, 28934.91KB/s]
 36%|███▌      | 20481/57421 [00:00<00:00, 43057.79KB/s]
 53%|█████▎    | 30552/57421 [00:00<00:00, 61037.24KB/s]
 71%|███████▏  | 40977/57421 [00:01<00:00, 74353.19KB/s]
100%|██████████| 57421/57421 [00:01<00:00, 49356.13KB/s]
Finished, total runtime is 79.60 s
{ 'best_config': { 'dataset': 'auto',
                   'dataset_root': 'auto',
                   'estimator': <class 'gluoncv.auto.estimators.ssd.ssd.SSDEstimator'>,
                   'gpus': [0],
                   'horovod': False,
                   'num_workers': 8,
                   'resume': '',
                   'save_interval': 1,
                   'ssd': { 'amp': False,
                            'base_network': 'resnet50_v1',
                            'data_shape': 512,
                            'filters': None,
                            'nms_thresh': 0.45,
                            'nms_topk': 400,
                            'ratios': ( [1, 2, 0.5],
                                        [1, 2, 0.5, 3, 0.3333333333333333],
                                        [1, 2, 0.5, 3, 0.3333333333333333],
                                        [1, 2, 0.5, 3, 0.3333333333333333],
                                        [1, 2, 0.5],
                                        [1, 2, 0.5]),
                            'sizes': (30, 60, 111, 162, 213, 264, 315),
                            'steps': (8, 16, 32, 64, 100, 300),
                            'syncbn': False,
                            'transfer': 'ssd_512_resnet50_v1_coco'},
                   'train': { 'batch_size': 8,
                              'dali': False,
                              'early_stop_baseline': -inf,
                              'early_stop_max_value': inf,
                              'early_stop_min_delta': 0.001,
                              'early_stop_patience': 10,
                              'epochs': 5,
                              'log_interval': 100,
                              'lr': 0.001,
                              'lr_decay': 0.1,
                              'lr_decay_epoch': (160, 200),
                              'momentum': 0.9,
                              'seed': 326,
                              'start_epoch': 0,
                              'wd': 0.0005},
                   'valid': { 'batch_size': 8,
                              'iou_thresh': 0.5,
                              'metric': 'voc07',
                              'val_interval': 1}},
  'total_time': 79.60054230690002,
  'train_map': 0.7020848889531329,
  'valid_map': 0.6267718257006858}
<autogluon.vision.detector.detector.ObjectDetector at 0x7f60048c57c0>

Note that num_trials=2 above is only used to speed up the tutorial. In normal practice, it is common to only use time_limit and drop num_trials. Also note that hyperparameter tuning defaults to random search.

After fitting, AutoGluon automatically returns the best model among all models in the searching space. From the output, we know the best model is the one trained with the second learning rate. To see how well the returned model performed on test dataset, call detector.evaluate().

dataset_test = ObjectDetector.Dataset.from_voc(url, splits='test')

test_map = detector.evaluate(dataset_test)
print("mAP on test dataset: {}".format(test_map[1][-1]))
tiny_motorbike/
├── Annotations/
├── ImageSets/
└── JPEGImages/
mAP on test dataset: 0.09605784217775845

Below, we randomly select an image from test dataset and show the predicted class, box and probability over the origin image, stored in predict_class, predict_rois and predict_score columns, respectively. You can interpret predict_rois as a dict of (xmin, ymin, xmax, ymax) proportional to original image size.

image_path = dataset_test.iloc[0]['image']
result = detector.predict(image_path)
print(result)
   predict_class  predict_score  0      motorbike       0.993964
1         person       0.976356
2            car       0.274865
3            car       0.242428
4            car       0.214246
5            car       0.181645
6            car       0.153880
7            car       0.149213
8            car       0.128523
9      motorbike       0.115683
10           car       0.113089
11           car       0.110871
12           car       0.101940
13           car       0.092710
14           car       0.085229
15           car       0.081497
16           car       0.078498
17           car       0.076282
18           car       0.075468
19        person       0.070298
20        person       0.066968
21     motorbike       0.066634
22           car       0.065573
23           car       0.060747
24           car       0.059603
25        person       0.059487
26           car       0.059234
27   pottedplant       0.058574
28           car       0.058348
29           car       0.057876
30           car       0.055972
31     motorbike       0.051605
32           car       0.051307
33           car       0.050553
34           car       0.050526
35           car       0.049298
36           car       0.048161
37           car       0.046649
38           car       0.046189
39           car       0.044576
40           car       0.044476
41        person       0.044429
42           bus       0.042421

                                         predict_rois
0   {'xmin': 0.3225756585597992, 'ymin': 0.3951848...
1   {'xmin': 0.4014277756214142, 'ymin': 0.2678495...
2   {'xmin': 0.05417585000395775, 'ymin': 0.320879...
3   {'xmin': 0.30855533480644226, 'ymin': 0.580329...
4   {'xmin': 0.0008486835868097842, 'ymin': 0.6302...
5   {'xmin': 0.0, 'ymin': 0.5899590253829956, 'xma...
6   {'xmin': 0.6469194889068604, 'ymin': 0.6038273...
7   {'xmin': 0.40746650099754333, 'ymin': 0.849225...
8   {'xmin': 0.3437637686729431, 'ymin': 0.6622117...
9   {'xmin': 0.053961120545864105, 'ymin': 0.31272...
10  {'xmin': 0.008721726946532726, 'ymin': 0.59467...
11  {'xmin': 0.7214855551719666, 'ymin': 0.2121329...
12  {'xmin': 0.6892836093902588, 'ymin': 0.3145019...
13  {'xmin': 0.0, 'ymin': 0.5549805760383606, 'xma...
14  {'xmin': 0.8281876444816589, 'ymin': 0.1661576...
15  {'xmin': 0.7788901925086975, 'ymin': 0.0801258...
16  {'xmin': 0.03919331729412079, 'ymin': 0.624726...
17  {'xmin': 0.6802377700805664, 'ymin': 0.4172073...
18  {'xmin': 0.706669270992279, 'ymin': 0.47497802...
19  {'xmin': 0.7284289598464966, 'ymin': 0.3883834...
20  {'xmin': 0.0, 'ymin': 0.0, 'xmax': 0.068020388...
21  {'xmin': 0.0, 'ymin': 0.6153775453567505, 'xma...
22  {'xmin': 0.7426783442497253, 'ymin': 0.4338973...
23  {'xmin': 0.6857182383537292, 'ymin': 0.7100520...
24  {'xmin': 0.05235469341278076, 'ymin': 0.399417...
25  {'xmin': 0.03212909400463104, 'ymin': 0.0, 'xm...
26  {'xmin': 0.5653790235519409, 'ymin': 0.3523963...
27  {'xmin': 0.31041014194488525, 'ymin': 0.429569...
28  {'xmin': 0.0, 'ymin': 0.4475474953651428, 'xma...
29  {'xmin': 0.005950257647782564, 'ymin': 0.37983...
30  {'xmin': 0.5550954937934875, 'ymin': 0.6033522...
31  {'xmin': 0.3210487365722656, 'ymin': 0.4464541...
32  {'xmin': 0.0, 'ymin': 0.6594634652137756, 'xma...
33  {'xmin': 0.0, 'ymin': 0.5113850235939026, 'xma...
34  {'xmin': 0.5646947622299194, 'ymin': 0.7772882...
35  {'xmin': 0.8406778573989868, 'ymin': 0.5922008...
36  {'xmin': 0.7582877278327942, 'ymin': 0.6437577...
37  {'xmin': 0.6592857837677002, 'ymin': 0.4788408...
38  {'xmin': 0.0, 'ymin': 0.44803500175476074, 'xm...
39  {'xmin': 0.1129189282655716, 'ymin': 0.5010659...
40  {'xmin': 0.010334109887480736, 'ymin': 0.61061...
41  {'xmin': 0.7598918080329895, 'ymin': 0.4007599...
42  {'xmin': 0.31041014194488525, 'ymin': 0.429569...

Prediction with multiple images is permitted:

bulk_result = detector.predict(dataset_test)
print(bulk_result)
     predict_class  predict_score  0        motorbike       0.993964
1           person       0.976356
2              car       0.274865
3              car       0.242428
4              car       0.214246
...            ...            ...
3347           car       0.020583
3348        person       0.020540
3349         chair       0.020478
3350        person       0.020306
3351        person       0.020193

                                           predict_rois  0     {'xmin': 0.3225756585597992, 'ymin': 0.3951848...
1     {'xmin': 0.4014277756214142, 'ymin': 0.2678495...
2     {'xmin': 0.05417585000395775, 'ymin': 0.320879...
3     {'xmin': 0.30855533480644226, 'ymin': 0.580329...
4     {'xmin': 0.0008486835868097842, 'ymin': 0.6302...
...                                                 ...
3347  {'xmin': 0.17820002138614655, 'ymin': 0.459234...
3348  {'xmin': 0.10267238318920135, 'ymin': 0.447010...
3349  {'xmin': 0.863222599029541, 'ymin': 0.67616397...
3350  {'xmin': 0.4904642105102539, 'ymin': 0.1615851...
3351  {'xmin': 0.07392938435077667, 'ymin': 0.401680...

                                                  image
0     /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
1     /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
2     /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3     /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
4     /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
...                                                 ...
3347  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3348  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3349  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3350  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3351  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...

[3352 rows x 4 columns]

We can also save the trained model, and use it later.

Warning

ObjectDetector.load() used pickle module implicitly, which is known to be insecure. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling. Never load data that could have come from an untrusted source, or that could have been tampered with. Only load data you trust.

savefile = 'detector.ag'
detector.save(savefile)
new_detector = ObjectDetector.load(savefile)
/home/ci/opt/venv/lib/python3.8/site-packages/mxnet/gluon/block.py:1784: UserWarning: Cannot decide type for the following arguments. Consider providing them as input:
    data: None
  input_sym_arg_type = in_param.infer_type()[0]