{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "x7seefPduh36" }, "source": [ "
\n", " \n", "
 
\n", "
\n", " OpenMMLab website\n", " \n", " \n", " HOT\n", " \n", " \n", "     \n", " OpenMMLab platform\n", " \n", " \n", " TRY IT OUT\n", " \n", " \n", "
\n", "
 
\n", "\n", "\"Open\n", "\n", "[![PyPI](https://img.shields.io/pypi/v/mmyolo)](https://pypi.org/project/mmyolo)\n", "[![docs](https://img.shields.io/badge/docs-latest-blue)](https://mmyolo.readthedocs.io/en/latest/)\n", "[![deploy](https://github.com/open-mmlab/mmyolo/workflows/deploy/badge.svg)](https://github.com/open-mmlab/mmyolo/actions)\n", "[![codecov](https://codecov.io/gh/open-mmlab/mmyolo/branch/main/graph/badge.svg)](https://codecov.io/gh/open-mmlab/mmyolo)\n", "[![license](https://img.shields.io/github/license/open-mmlab/mmyolo.svg)](https://github.com/open-mmlab/mmyolo/blob/main/LICENSE)\n", "[![open issues](https://isitmaintained.com/badge/open/open-mmlab/mmyolo.svg)](https://github.com/open-mmlab/mmyolo/issues)\n", "[![issue resolution](https://isitmaintained.com/badge/resolution/open-mmlab/mmyolo.svg)](https://github.com/open-mmlab/mmyolo/issues)\n", "\n", "[📘Documentation](https://mmyolo.readthedocs.io/en/latest/) |\n", "[🛠️Installation](https://mmyolo.readthedocs.io/en/latest/get_started/installation.html) |\n", "[👀Model Zoo](https://mmyolo.readthedocs.io/en/latest/model_zoo.html) |\n", "[🆕Update News](https://mmyolo.readthedocs.io/en/latest/notes/changelog.html) |\n", "[🤔Reporting Issues](https://github.com/open-mmlab/mmyolo/issues/new/choose)\n", "\n", "
\n", "\n", "
\n", " \n", " \"\"\n", " \"\"\n", " \n", " \"\"\n", " \"\"\n", " \n", " \"\"\n", " \"\"\n", " \n", " \"\"\n", " \"\"\n", " \n", " \"\"\n", " \"\"\n", " \n", " \"\"\n", "
" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "V6W8P5XEJGoc" }, "source": [ "# 15 minutes to get started with MMYOLO instance segmentation\n", "\n", "Instance segmentation is a task in computer vision that aims to segment each object in an image and assign each object a unique identifier.\n", "\n", "Unlike semantic segmentation, instance segmentation not only segments out different categories in an image, but also separates different instances of the same category.\n", "\n", "
\n", "\"Instance\n", "
\n", "\n", "Taking the downloadable balloon dataset as an example, I will guide you through a 15-minute easy introduction to MMYOLO instance segmentation. The entire process includes the following steps:\n", "\n", "- [Installation](#installation)\n", "- [Dataset](#dataset)\n", "- [Config](#config)\n", "- [Training](#training)\n", "- [Testing](#testing)\n", "- [EasyDeploy](#easydeploy-deployment)\n", "\n", "In this tutorial, we will use YOLOv5-s as an example. For the demo configuration of the balloon dataset with other YOLO series algorithms, please refer to the corresponding algorithm configuration folder." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "Ae5SqsA7wYGQ" }, "source": [ "## Installation\n", "\n", "Assuming you've already installed Conda in advance, then install PyTorch using the following commands." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "colab": { "base_uri": "https://localhost:8080/" }, "id": "XVLRaEIzwW-6", "outputId": "901b5db6-b1d7-4830-e746-485ee76d6648" }, "outputs": [], "source": [ "# -----------------------------------------------------------------------------------------\n", "# If you are using colab, you can skip this cell for PyTorch is pre-installed on the colab.\n", "# -----------------------------------------------------------------------------------------\n", "!python -V\n", "# Check nvcc version\n", "!nvcc -V\n", "# Check GCC version\n", "!gcc --version\n", "# Create a new Conda environment\n", "%conda create -n mmyolo python=3.8 -y\n", "%conda activate mmyolo\n", "# If you have GPU\n", "%conda install pytorch torchvision -c pytorch\n", "# If you only have CPU\n", "# %conda install pytorch torchvision cpuonly -c pytorch" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check PyTorch version\n", "import torch\n", "print(torch.__version__)\n", "print(torch.cuda.is_available())" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Install MMYOLO and dependency libraries using the following commands.\n", "For details about how to configure the environment, see [Installation and verification](https://mmyolo.readthedocs.io/en/latest/get_started/installation.html).\n", "```{note}\n", "Note: Since this repo uses OpenMMLab 2.0, it is better to create a new conda virtual environment to prevent conflicts with the repo installed in OpenMMLab 1.0.\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "-qATUuntwmfD", "outputId": "24be577b-efce-46f2-8b2f-a65d02824467" }, "outputs": [], "source": [ "!git clone https://github.com/open-mmlab/mmyolo.git\n", "%cd mmyolo\n", "%pip install -U openmim\n", "!mim install -r requirements/mminstall.txt\n", "# Install albumentations\n", "!mim install -r requirements/albu.txt\n", "# Install MMYOLO\n", "!mim install -v -e .\n", "# \"-v\" means verbose, or more output\n", "# \"-e\" means installing a project in editable mode,\n", "# thus any local modifications made to the code will take effect without reinstallation." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Dataset\n", "\n", "The Balloon dataset is a single-class dataset that consists of 74 images and includes annotated information required for training. Here is an example image from the dataset:\n", "\n", "
\n", "\"balloon\n", "
\n", "\n", "You can download and use it directly by the following command:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "colab": { "base_uri": "https://localhost:8080/" }, "id": "gMQXwWuIw3ef", "outputId": "c8efeac7-5b0c-4342-b5af-d3e790e358c3" }, "outputs": [], "source": [ "!python tools/misc/download_dataset.py --dataset-name balloon --save-dir ./data/balloon --unzip --delete\n", "!python ./tools/dataset_converters/balloon2coco.py" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "covQskXXw2ul" }, "source": [ "The data for the MMYOLO project is located in the MMYOLO project directory. The `train.json` and `val.json` files store the annotations in COCO format, while the `data/balloon/train` and `data/balloon/val` directories contain all the images for the dataset.\n", "\n", "## Config\n", "\n", "Taking YOLOv5 algorithm as an example, considering the limited GPU memory of users, we need to modify some default training parameters to make them run smoothly. The key parameters to be modified are as follows:\n", "\n", "- YOLOv5 is an Anchor-Based algorithm, and different datasets need to calculate suitable anchors adaptively.\n", "- The default config uses 8 GPUs with a batch size of 16 per GPU. Now change it to a single GPU with a batch size of 12.\n", "- In principle, the learning rate should be linearly scaled accordingly when the batch size is changed, but actual measurements have found that this is not necessary.\n", "\n", "To perform the specific operation, create a new configuration file named `yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py` in the `configs/yolov5/ins_seg` folder. For convenience, we have already provided this configuration file. Copy the following contents into the configuration file.\n", "\n", "```python\n", "_base_ = './yolov5_ins_s-v61_syncbn_fast_8xb16-300e_coco_instance.py' # noqa\n", "\n", "data_root = 'data/balloon/' # dataset root\n", "# Training set annotation file of json path\n", "train_ann_file = 'train.json'\n", "train_data_prefix = 'train/' # Dataset prefix\n", "# Validation set annotation file of json path\n", "val_ann_file = 'val.json'\n", "val_data_prefix = 'val/'\n", "metainfo = {\n", " 'classes': ('balloon', ), # dataset category name\n", " 'palette': [\n", " (220, 20, 60),\n", " ]\n", "}\n", "num_classes = 1\n", "# Set batch size to 4\n", "train_batch_size_per_gpu = 4\n", "# dataloader num workers\n", "train_num_workers = 2\n", "log_interval = 1\n", "#####################\n", "train_dataloader = dict(\n", " batch_size=train_batch_size_per_gpu,\n", " num_workers=train_num_workers,\n", " dataset=dict(\n", " data_root=data_root,\n", " metainfo=metainfo,\n", " data_prefix=dict(img=train_data_prefix),\n", " ann_file=train_ann_file))\n", "val_dataloader = dict(\n", " dataset=dict(\n", " data_root=data_root,\n", " metainfo=metainfo,\n", " data_prefix=dict(img=val_data_prefix),\n", " ann_file=val_ann_file))\n", "test_dataloader = val_dataloader\n", "val_evaluator = dict(ann_file=data_root + val_ann_file)\n", "test_evaluator = val_evaluator\n", "default_hooks = dict(logger=dict(interval=log_interval))\n", "#####################\n", "\n", "model = dict(bbox_head=dict(head_module=dict(num_classes=num_classes)))\n", "```\n", "\n", "The above configuration inherits from `yolov5_ins_s-v61_syncbn_fast_8xb16-300e_coco_instance.py` and updates configurations such as `data_root`, `metainfo`, `train_dataloader`, `val_dataloader`, `num_classes`, etc., based on the characteristics of the balloon dataset.\n", "\n", "## Training" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python tools/train.py configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "TQ0h6sv_rJxq" }, "source": [ "After running the training command mentioned above, the folder `work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance` will be automatically generated. The weight files and the training configuration file for this session will be saved in this folder. On a lower-end GPU like the GTX 1660, the entire training process will take approximately 30 minutes.\n", "\n", "
\n", "\"image\"/\n", "
\n", "\n", "The performance on `val.json` is as follows:\n", "\n", "```text\n", " Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.330\n", " Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.509\n", " Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.317\n", " Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000\n", " Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.103\n", " Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.417\n", " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.150\n", " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.396\n", " Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.454\n", " Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000\n", " Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.317\n", " Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.525\n", "```\n", "\n", "The above performance is obtained by printing using the COCO API, where -1 indicates the absence of objects of that scale.\n", "\n", "### Some Notes\n", "\n", "Two key warnings are printed during training:\n", "\n", "- You are using `YOLOv5Head` with num_classes == 1. The loss_cls will be 0. This is a normal phenomenon.\n", "\n", "The warning is because the `num_classes` currently trained is 1, the loss of the classification branch is always 0 according to the community of the YOLOv5 algorithm, which is a normal phenomenon.\n", "\n", "### Training is resumed after the interruption\n", "\n", "If you stop training, you can add `--resume` to the end of the training command and the program will automatically resume training with the latest weights file from `work_dirs`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python tools/train.py configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py --resume" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "3sJxvQoUrMhX" }, "source": [ "### Save GPU memory strategy\n", "\n", "The above config requires about 3G RAM, so if you don't have enough, consider turning on mixed-precision training" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python tools/train.py configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py --amp" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "jVJdyHTxrQ9a" }, "source": [ "### Training visualization\n", "\n", "MMYOLO currently supports local, TensorBoard, WandB and other back-end visualization. The default is to use local visualization, and you can switch to WandB and other real-time visualization of various indicators in the training process.\n", "\n", "#### 1 WandB\n", "\n", "WandB visualization need registered in website, and in the https://wandb.ai/settings for wandb API Keys.\n", "\n", "
\n", "\"image\"/\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install wandb\n", "# After running wandb login, enter the API Keys obtained above, and the login is successful.\n", "!wandb login" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "Yu0_4YYRrbyY" }, "source": [ "Add the wandb config at the end of config file we just created: `configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py`.\n", "\n", "```python\n", "visualizer = dict(vis_backends = [dict(type='LocalVisBackend'), dict(type='WandbVisBackend')])\n", "```\n", "\n", "Running the training command and you will see the loss, learning rate, and coco/bbox_mAP visualizations in the link." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python tools/train.py configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "f_DyzfDIzwMa" }, "source": [ "
\n", "\"image\"/\n", "
\n", "
\n", "\"image\"/\n", "
\n", "\n", "#### 2 Tensorboard\n", "\n", "Install Tensorboard using the following command." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "gHkGlii3n29Q" }, "outputs": [], "source": [ "%pip install tensorboard" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "bE-nx9TY1P-M" }, "source": [ "Add the `tensorboard` config at the end of config file we just created: `configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py`.\n", "\n", "```python\n", "visualizer = dict(vis_backends=[dict(type='LocalVisBackend'),dict(type='TensorboardVisBackend')])\n", "```\n", "\n", "After re-running the training command, Tensorboard file will be generated in the visualization folder `work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance/{timestamp}/vis_data`.\n", "We can use Tensorboard to view the loss, learning rate, and coco/bbox_mAP visualizations from a web link by running the following command:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "cellView": "form", "id": "g8fZgokho5CE" }, "outputs": [], "source": [ "!tensorboard --logdir=work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "GUZ7MPoaro-o" }, "source": [ "## Testing" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "VYmxtE0GunTB", "outputId": "f440807c-1931-4810-b76d-617f73fde227" }, "outputs": [], "source": [ "!python tools/test.py configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance best_coco_bbox_mAP_epoch_300.pth --show-dir show_results" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "_cFocUqN0BCb" }, "source": [ "Run the above test command, you can not only get the AP performance printed in the **Training** section, You can also automatically save the result images to the `work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance/{timestamp}/show_results` folder. Below is one of the result images, the left image is the actual annotation, and the right image is the inference result of the model.\n", "\n", "
\n", "\"result_img\"/\n", "
\n", "\n", "You can also visualize model inference results in a browser window if you use `WandbVisBackend` or `TensorboardVisBackend`.\n", "\n", "## Feature map visualization\n", "\n", "MMYOLO provides visualization scripts for feature map to analyze the current model training. Please refer to [Feature Map Visualization](../recommended_topics/visualization.md)\n", "\n", "Due to the bias of direct visualization of `test_pipeline`, we need to modify the `test_pipeline` of `configs/yolov5/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py`\n", "\n", "```python\n", "test_pipeline = [\n", " dict(\n", " type='LoadImageFromFile',\n", " file_client_args=_base_.file_client_args),\n", " dict(type='YOLOv5KeepRatioResize', scale=img_scale),\n", " dict(\n", " type='LetterResize',\n", " scale=img_scale,\n", " allow_scale_up=False,\n", " pad_val=dict(img=114)),\n", " dict(type='LoadAnnotations', with_bbox=True, _scope_='mmdet'),\n", " dict(\n", " type='mmdet.PackDetInputs',\n", " meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n", " 'scale_factor', 'pad_param'))\n", "]\n", "```\n", "\n", "to the following config:\n", "\n", "```python\n", "test_pipeline = [\n", " dict(\n", " type='LoadImageFromFile',\n", " file_client_args=_base_.file_client_args),\n", " dict(type='mmdet.Resize', scale=img_scale, keep_ratio=False), # modify the LetterResize to mmdet.Resize\n", " dict(type='LoadAnnotations', with_bbox=True, _scope_='mmdet'),\n", " dict(\n", " type='mmdet.PackDetInputs',\n", " meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n", " 'scale_factor'))\n", "]\n", "```\n", "\n", "Let's choose the `data/balloon/train/3927754171_9011487133_b.jpg` image as an example to visualize the output feature maps of YOLOv5 backbone and neck layers.\n", "\n", "**1. Visualize the three channels of YOLOv5 backbone**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python demo/featmap_vis_demo.py data/balloon/train/3927754171_9011487133_b.jpg onfigs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance/best_coco_bbox_mAP_epoch_300.pth --target-layers backbone --channel-reduction squeeze_mean" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\"image\"/\n", "
\n", "\n", "The result will be saved to the output folder in current path. Three output feature maps plotted in the above figure correspond to small, medium and large output feature maps.\n", "\n", "**2. Visualize the three channels of YOLOv5 neck**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python demo/featmap_vis_demo.py data/balloon/train/3927754171_9011487133_b.jpg \\\n", " configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py \\\n", " work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance/best_coco_bbox_mAP_epoch_300.pth \\\n", " --target-layers neck \\\n", " --channel-reduction squeeze_mean" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\"image\"/\n", "
\n", "\n", "**3. Grad-Based CAM visualization**\n", "TODO" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## EasyDeploy deployment\n", "TODO\n", "\n", "This completes the transformation deployment of the trained model and checks the inference results. This is the end of the tutorial.\n", "\n", "If you encounter problems during training or testing, please check the [common troubleshooting steps](https://mmyolo.readthedocs.io/en/dev/recommended_topics/troubleshooting_steps.html) first and feel free to open an [issue](https://github.com/open-mmlab/mmyolo/issues/new/choose) if you still can't solve it." ] } ], "metadata": { "accelerator": "GPU", "colab": { "provenance": [], "toc_visible": true }, "gpuClass": "standard", "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0 }