.. _sec_object_detection_quick: 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 :ref:`sec_imgquick` 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: .. code:: python from autogluon.vision import ObjectDetector .. parsed-literal:: :class: output /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/tmpj29zasy7 INFO:torch.distributed.nn.jit.instantiator:Writing /tmp/tmpj29zasy7/_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. .. code:: python url = 'https://autogluon.s3.amazonaws.com/datasets/tiny_motorbike.zip' dataset_train = ObjectDetector.Dataset.from_voc(url, splits='trainval') .. parsed-literal:: :class: output Downloading /home/ci/.gluoncv/archive/tiny_motorbike.zip from https://autogluon.s3.amazonaws.com/datasets/tiny_motorbike.zip... .. parsed-literal:: :class: output 21273KB [00:01, 17758.92KB/s] .. parsed-literal:: :class: output 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. .. code:: python 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) .. parsed-literal:: :class: output ============================================================================= 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[153]/validation[17] splits. Starting HPO experiments .. parsed-literal:: :class: output 0%| | 0/2 [00:00, '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': 465, 'start_epoch': 0, 'wd': 0.0005}, 'valid': { 'batch_size': 8, 'iou_thresh': 0.5, 'metric': 'voc07', 'val_interval': 1}}, 'total_time': 72.85688781738281, 'train_map': 0.6030938671397602, 'valid_map': 0.8605054240179776} .. parsed-literal:: :class: output 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(). .. code:: python 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])) .. parsed-literal:: :class: output tiny_motorbike/ ├── Annotations/ ├── ImageSets/ └── JPEGImages/ mAP on test dataset: 0.1651368087106408 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. .. code:: python image_path = dataset_test.iloc[0]['image'] result = detector.predict(image_path) print(result) .. parsed-literal:: :class: output predict_class predict_score \ 0 person 0.986930 1 motorbike 0.957386 2 car 0.748174 3 motorbike 0.277935 4 motorbike 0.190122 .. ... ... 60 pottedplant 0.029843 61 person 0.029740 62 person 0.029169 63 person 0.028643 64 person 0.028192 predict_rois 0 {'xmin': 0.39921894669532776, 'ymin': 0.277194... 1 {'xmin': 0.32189151644706726, 'ymin': 0.442039... 2 {'xmin': 0.0, 'ymin': 0.6730638742446899, 'xma... 3 {'xmin': 0.709790825843811, 'ymin': 0.38805425... 4 {'xmin': 0.00020241353195160627, 'ymin': 0.653... .. ... 60 {'xmin': 0.31941738724708557, 'ymin': 0.452766... 61 {'xmin': 0.3926831781864166, 'ymin': 0.3282300... 62 {'xmin': 0.19570107758045197, 'ymin': 0.752834... 63 {'xmin': 0.0, 'ymin': 0.5318694114685059, 'xma... 64 {'xmin': 0.859866738319397, 'ymin': 0.39932516... [65 rows x 3 columns] Prediction with multiple images is permitted: .. code:: python bulk_result = detector.predict(dataset_test) print(bulk_result) .. parsed-literal:: :class: output predict_class predict_score \ 0 person 0.986930 1 motorbike 0.957386 2 car 0.748174 3 motorbike 0.277935 4 motorbike 0.190122 ... ... ... 3971 motorbike 0.029450 3972 person 0.029406 3973 person 0.029364 3974 person 0.029318 3975 person 0.028826 predict_rois \ 0 {'xmin': 0.39921894669532776, 'ymin': 0.277194... 1 {'xmin': 0.32189151644706726, 'ymin': 0.442039... 2 {'xmin': 0.0, 'ymin': 0.6730638742446899, 'xma... 3 {'xmin': 0.709790825843811, 'ymin': 0.38805425... 4 {'xmin': 0.00020241353195160627, 'ymin': 0.653... ... ... 3971 {'xmin': 0.6376281380653381, 'ymin': 0.4148297... 3972 {'xmin': 0.0, 'ymin': 0.4482800364494324, 'xma... 3973 {'xmin': 0.3135392963886261, 'ymin': 0.4288076... 3974 {'xmin': 0.25278082489967346, 'ymin': 0.472066... 3975 {'xmin': 0.2228342443704605, 'ymin': 0.3917526... 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... ... ... 3971 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3972 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3973 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3974 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... 3975 /home/ci/.gluoncv/datasets/tiny_motorbike/tiny... [3976 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.** .. code:: python savefile = 'detector.ag' detector.save(savefile) new_detector = ObjectDetector.load(savefile) .. parsed-literal:: :class: output /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]