.. _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/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. .. 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, 18385.57KB/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[156]/validation[14] splits. Starting HPO experiments .. parsed-literal:: :class: output 0%| | 0/2 [00:00 != ): { 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. .. parsed-literal:: :class: output 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... .. parsed-literal:: :class: output 0%| | 0/181188 [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': 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} .. 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.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. .. 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 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: .. code:: python bulk_result = detector.predict(dataset_test) print(bulk_result) .. parsed-literal:: :class: output 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.** .. 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]