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+cu113 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/tmp0osfunrh
INFO:torch.distributed.nn.jit.instantiator:Writing /tmp/tmp0osfunrh/_remote_module_non_scriptable.py

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, 19191.99KB/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[159]/validation[11] splits.
Starting HPO experiments
  0%|          | 0/2 [00:00<?, ?it/s]
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%|          | 104/181188 [00:00<03:31, 857.09KB/s]
  0%|          | 517/181188 [00:00<01:17, 2326.99KB/s]
  1%|          | 2177/181188 [00:00<00:24, 7418.96KB/s]
  4%|▍         | 8019/181188 [00:00<00:06, 25083.38KB/s]
  8%|▊         | 14053/181188 [00:00<00:04, 36753.17KB/s]
 13%|█▎        | 22689/181188 [00:00<00:03, 50630.48KB/s]
 17%|█▋        | 31485/181188 [00:00<00:02, 62050.57KB/s]
 22%|██▏       | 39069/181188 [00:00<00:02, 66242.46KB/s]
 26%|██▋       | 47745/181188 [00:00<00:01, 70653.15KB/s]
 31%|███       | 56334/181188 [00:01<00:01, 75172.55KB/s]
 35%|███▌      | 63983/181188 [00:01<00:01, 75563.16KB/s]
 40%|████      | 72609/181188 [00:01<00:01, 76324.68KB/s]
 45%|████▍     | 81217/181188 [00:01<00:01, 79174.98KB/s]
 49%|████▉     | 89169/181188 [00:01<00:01, 78228.14KB/s]
 54%|█████▍    | 97745/181188 [00:01<00:01, 79093.84KB/s]
 59%|█████▊    | 106210/181188 [00:01<00:00, 80713.35KB/s]
 63%|██████▎   | 114298/181188 [00:01<00:00, 78968.95KB/s]
 68%|██████▊   | 122814/181188 [00:01<00:00, 80771.07KB/s]
 72%|███████▏  | 130909/181188 [00:02<00:00, 79497.44KB/s]
 77%|███████▋  | 138873/181188 [00:02<00:00, 79191.40KB/s]
 81%|████████  | 147013/181188 [00:02<00:00, 79838.61KB/s]
 86%|████████▌ | 155005/181188 [00:02<00:00, 79055.09KB/s]
 90%|█████████ | 163358/181188 [00:02<00:00, 80372.76KB/s]
 95%|█████████▍| 171403/181188 [00:02<00:00, 79920.55KB/s]
181189KB [00:02, 68291.84KB/s]
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%|          | 101/57421 [00:00<01:08, 833.05KB/s]
  1%|          | 515/57421 [00:00<00:24, 2335.56KB/s]
  4%|▍         | 2180/57421 [00:00<00:07, 7462.41KB/s]
 14%|█▍        | 7974/57421 [00:00<00:01, 24988.01KB/s]
 26%|██▌       | 14647/57421 [00:00<00:01, 38824.55KB/s]
 39%|███▉      | 22663/57421 [00:00<00:00, 50640.31KB/s]
 55%|█████▍    | 31461/57421 [00:00<00:00, 62159.53KB/s]
 68%|██████▊   | 39087/57421 [00:00<00:00, 66470.81KB/s]
 83%|████████▎ | 47753/57421 [00:00<00:00, 70814.42KB/s]
100%|██████████| 57421/57421 [00:01<00:00, 52355.07KB/s]
Finished, total runtime is 75.31 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': 421,
                              'start_epoch': 0,
                              'wd': 0.0005},
                   'valid': { 'batch_size': 8,
                              'iou_thresh': 0.5,
                              'metric': 'voc07',
                              'val_interval': 1}},
  'total_time': 75.30475449562073,
  'train_map': 0.7204280566885625,
  'valid_map': 0.9341521150509916}
<autogluon.vision.detector.detector.ObjectDetector at 0x7f8f689c16a0>

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.39227659045813806

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.944437
1         person       0.829662
2      motorbike       0.319636
3      motorbike       0.233822
4      motorbike       0.227945
5            car       0.169213
6      motorbike       0.136762
7      motorbike       0.105894
8    pottedplant       0.104180
9      motorbike       0.072894
10        person       0.068709
11        person       0.067453
12        person       0.067396
13        person       0.061977
14        person       0.061744
15     motorbike       0.052180
16       bicycle       0.050272
17        person       0.049930
18     motorbike       0.048863
19     motorbike       0.047319
20           car       0.043177
21        person       0.041619
22        person       0.041228
23        person       0.037719
24           car       0.036797
25        person       0.036548
26        person       0.036156
27        person       0.035666
28           car       0.035511
29        person       0.034619
30           dog       0.034503
31        person       0.034149
32     motorbike       0.032053
33        person       0.032023
34         chair       0.031928
35        person       0.031283
36        person       0.031249
37     motorbike       0.030009
38        person       0.029745
39        person       0.029688
40        person       0.029669
41        person       0.029532
42           car       0.029507
43        person       0.029293
44     motorbike       0.029144
45     motorbike       0.028926
46     motorbike       0.028599
47        person       0.028130
48        person       0.027599
49       bicycle       0.027499
50        person       0.027135
51        person       0.027024
52     motorbike       0.026887
53     motorbike       0.026885
54        person       0.026587
55           car       0.026375

                                         predict_rois
0   {'xmin': 0.3198387324810028, 'ymin': 0.4405676...
1   {'xmin': 0.3818334937095642, 'ymin': 0.2969620...
2   {'xmin': 0.7121447324752808, 'ymin': 0.1802718...
3   {'xmin': 0.0005333706503733993, 'ymin': 0.6465...
4   {'xmin': 0.3765932023525238, 'ymin': 0.3170163...
5   {'xmin': 0.0005333706503733993, 'ymin': 0.6465...
6   {'xmin': 0.7058811187744141, 'ymin': 0.3079434...
7   {'xmin': 0.6361035108566284, 'ymin': 0.0681726...
8   {'xmin': 0.3053668439388275, 'ymin': 0.4499387...
9   {'xmin': 0.7123414874076843, 'ymin': 0.3897169...
10  {'xmin': 0.3962763249874115, 'ymin': 0.2919827...
11  {'xmin': 0.33416154980659485, 'ymin': 0.345117...
12  {'xmin': 0.3133251667022705, 'ymin': 0.2210566...
13  {'xmin': 0.9876390695571899, 'ymin': 0.5288349...
14  {'xmin': 0.9027056097984314, 'ymin': 0.2078328...
15  {'xmin': 0.3133251667022705, 'ymin': 0.2210566...
16  {'xmin': 0.30911460518836975, 'ymin': 0.450034...
17  {'xmin': 0.37443625926971436, 'ymin': 0.306855...
18  {'xmin': 0.39615774154663086, 'ymin': 0.067459...
19  {'xmin': 0.755367636680603, 'ymin': 0.08559870...
20  {'xmin': 0.666469931602478, 'ymin': 0.05101162...
21  {'xmin': 0.30857816338539124, 'ymin': 0.365583...
22  {'xmin': 0.9970389604568481, 'ymin': 0.4524995...
23  {'xmin': 0.4953533709049225, 'ymin': 0.3068005...
24  {'xmin': 0.6799491047859192, 'ymin': 0.1457533...
25  {'xmin': 0.4737255573272705, 'ymin': 0.3021801...
26  {'xmin': 0.9882245063781738, 'ymin': 0.2375874...
27  {'xmin': 0.0, 'ymin': 0.3394560217857361, 'xma...
28  {'xmin': 0.6506831645965576, 'ymin': 0.1000173...
29  {'xmin': 0.44540950655937195, 'ymin': 0.287244...
30  {'xmin': 0.30911460518836975, 'ymin': 0.450034...
31  {'xmin': 0.7109805941581726, 'ymin': 0.3976593...
32  {'xmin': 0.3169269561767578, 'ymin': 0.5118487...
33  {'xmin': 0.9669552445411682, 'ymin': 0.5048523...
34  {'xmin': 0.3019549548625946, 'ymin': 0.0020512...
35  {'xmin': 0.43810808658599854, 'ymin': 0.086986...
36  {'xmin': 0.4799288213253021, 'ymin': 0.3076659...
37  {'xmin': 0.8052250146865845, 'ymin': 0.1642719...
38  {'xmin': 0.9810229539871216, 'ymin': 0.0498418...
39  {'xmin': 0.996984601020813, 'ymin': 0.53755748...
40  {'xmin': 0.9962202906608582, 'ymin': 0.3898071...
41  {'xmin': 0.5076624751091003, 'ymin': 0.3166834...
42  {'xmin': 0.30911460518836975, 'ymin': 0.450034...
43  {'xmin': 0.3156031370162964, 'ymin': 0.2795293...
44  {'xmin': 0.19459757208824158, 'ymin': 0.344114...
45  {'xmin': 0.37192651629447937, 'ymin': 0.109095...
46  {'xmin': 0.6792832016944885, 'ymin': 0.4234628...
47  {'xmin': 0.9949443340301514, 'ymin': 0.5022779...
48  {'xmin': 0.4073106646537781, 'ymin': 0.2365254...
49  {'xmin': 0.7109805941581726, 'ymin': 0.3976593...
50  {'xmin': 0.46960002183914185, 'ymin': 0.290261...
51  {'xmin': 0.922869861125946, 'ymin': 0.59202671...
52  {'xmin': 0.6162905693054199, 'ymin': 0.1245651...
53  {'xmin': 0.7131490707397461, 'ymin': 0.2423614...
54  {'xmin': 0.30911460518836975, 'ymin': 0.450034...
55  {'xmin': 0.7139614820480347, 'ymin': 0.0222105...

Prediction with multiple images is permitted:

bulk_result = detector.predict(dataset_test)
print(bulk_result)
     predict_class  predict_score  0        motorbike       0.944437
1           person       0.829662
2        motorbike       0.319636
3        motorbike       0.233822
4        motorbike       0.227945
...            ...            ...
3857        person       0.036159
3858        person       0.035951
3859     motorbike       0.035950
3860        person       0.035922
3861           car       0.035859

                                           predict_rois  0     {'xmin': 0.3198387324810028, 'ymin': 0.4405676...
1     {'xmin': 0.3818334937095642, 'ymin': 0.2969620...
2     {'xmin': 0.7121447324752808, 'ymin': 0.1802718...
3     {'xmin': 0.0005333706503733993, 'ymin': 0.6465...
4     {'xmin': 0.3765932023525238, 'ymin': 0.3170163...
...                                                 ...
3857  {'xmin': 0.34639793634414673, 'ymin': 0.984214...
3858  {'xmin': 0.17816868424415588, 'ymin': 0.661037...
3859  {'xmin': 0.09734556078910828, 'ymin': 0.565375...
3860  {'xmin': 0.42627769708633423, 'ymin': 0.227234...
3861  {'xmin': 0.7766627073287964, 'ymin': 0.4587219...

                                                  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...
...                                                 ...
3857  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3858  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3859  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3860  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...
3861  /home/ci/.gluoncv/datasets/tiny_motorbike/tiny...

[3862 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]