├── .gitignore
├── Arial.ttf
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── README.md
├── assets
├── data.png
├── data2.png
├── helmet.gif
└── train.png
├── data
├── Argoverse.yaml
├── GlobalWheat2020.yaml
├── Objects365.yaml
├── SKU-110K.yaml
├── VOC.yaml
├── VisDrone.yaml
├── clda.yaml
├── coco.yaml
├── coco128.yaml
├── fire.yaml
├── helmet.yaml
├── hyps
│ ├── hyp.finetune.yaml
│ ├── hyp.finetune_objects365.yaml
│ ├── hyp.scratch-p6.yaml
│ └── hyp.scratch.yaml
├── images
│ ├── bus.jpg
│ └── zidane.jpg
├── scripts
│ ├── download_weights.sh
│ ├── get_coco.sh
│ └── get_coco128.sh
└── xView.yaml
├── detect.py
├── export.py
├── hubconf.py
├── models
├── __init__.py
├── common.py
├── experimental.py
├── hub
│ ├── anchors.yaml
│ ├── yolov3-spp.yaml
│ ├── yolov3-tiny.yaml
│ ├── yolov3.yaml
│ ├── yolov5-bifpn.yaml
│ ├── yolov5-fpn.yaml
│ ├── yolov5-p2.yaml
│ ├── yolov5-p6.yaml
│ ├── yolov5-p7.yaml
│ ├── yolov5-panet.yaml
│ ├── yolov5l6.yaml
│ ├── yolov5m6.yaml
│ ├── yolov5s-ghost.yaml
│ ├── yolov5s-transformer.yaml
│ ├── yolov5s6.yaml
│ └── yolov5x6.yaml
├── tf.py
├── yolo.py
├── yolov5l.yaml
├── yolov5m.yaml
├── yolov5s.yaml
└── yolov5x.yaml
├── requirements.txt
├── train.py
├── tutorial.ipynb
├── utils
├── __init__.py
├── activations.py
├── augmentations.py
├── autoanchor.py
├── aws
│ ├── __init__.py
│ ├── mime.sh
│ ├── resume.py
│ └── userdata.sh
├── callbacks.py
├── datasets.py
├── downloads.py
├── flask_rest_api
│ ├── README.md
│ ├── example_request.py
│ └── restapi.py
├── general.py
├── google_app_engine
│ ├── Dockerfile
│ ├── additional_requirements.txt
│ └── app.yaml
├── loggers
│ ├── __init__.py
│ └── wandb
│ │ ├── README.md
│ │ ├── __init__.py
│ │ ├── log_dataset.py
│ │ ├── sweep.py
│ │ ├── sweep.yaml
│ │ └── wandb_utils.py
├── loss.py
├── metrics.py
├── plots.py
└── torch_utils.py
└── val.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/Arial.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/Arial.ttf
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Contributing to YOLOv5 🚀
2 |
3 | We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible, whether it's:
4 |
5 | - Reporting a bug
6 | - Discussing the current state of the code
7 | - Submitting a fix
8 | - Proposing a new feature
9 | - Becoming a maintainer
10 |
11 | YOLOv5 works so well due to our combined community effort, and for every small improvement you contribute you will be
12 | helping push the frontiers of what's possible in AI 😃!
13 |
14 | ## Submitting a Pull Request (PR) 🛠️
15 |
16 | Submitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps:
17 |
18 | ### 1. Select File to Update
19 |
20 | Select `requirements.txt` to update by clicking on it in GitHub.
21 |

22 |
23 | ### 2. Click 'Edit this file'
24 |
25 | Button is in top-right corner.
26 | 
27 |
28 | ### 3. Make Changes
29 |
30 | Change `matplotlib` version from `3.2.2` to `3.3`.
31 | 
32 |
33 | ### 4. Preview Changes and Submit PR
34 |
35 | Click on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch**
36 | for this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose
37 | changes** button. All done, your PR is now submitted to YOLOv5 for review and approval 😃!
38 | 
39 |
40 | ### PR recommendations
41 |
42 | To allow your work to be integrated as seamlessly as possible, we advise you to:
43 |
44 | - ✅ Verify your PR is **up-to-date with origin/master.** If your PR is behind origin/master an
45 | automatic [GitHub actions](https://github.com/ultralytics/yolov5/blob/master/.github/workflows/rebase.yml) rebase may
46 | be attempted by including the /rebase command in a comment body, or by running the following code, replacing 'feature'
47 | with the name of your local branch:
48 |
49 | ```bash
50 | git remote add upstream https://github.com/ultralytics/yolov5.git
51 | git fetch upstream
52 | git checkout feature # <----- replace 'feature' with local branch name
53 | git merge upstream/master
54 | git push -u origin -f
55 | ```
56 |
57 | - ✅ Verify all Continuous Integration (CI) **checks are passing**.
58 | - ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase
59 | but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ -Bruce Lee
60 |
61 | ## Submitting a Bug Report 🐛
62 |
63 | If you spot a problem with YOLOv5 please submit a Bug Report!
64 |
65 | For us to start investigating a possibel problem we need to be able to reproduce it ourselves first. We've created a few
66 | short guidelines below to help users provide what we need in order to get started.
67 |
68 | When asking a question, people will be better able to provide help if you provide **code** that they can easily
69 | understand and use to **reproduce** the problem. This is referred to by community members as creating
70 | a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your code that reproduces
71 | the problem should be:
72 |
73 | * ✅ **Minimal** – Use as little code as possible that still produces the same problem
74 | * ✅ **Complete** – Provide **all** parts someone else needs to reproduce your problem in the question itself
75 | * ✅ **Reproducible** – Test the code you're about to provide to make sure it reproduces the problem
76 |
77 | In addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code
78 | should be:
79 |
80 | * ✅ **Current** – Verify that your code is up-to-date with current
81 | GitHub [master](https://github.com/ultralytics/yolov5/tree/master), and if necessary `git pull` or `git clone` a new
82 | copy to ensure your problem has not already been resolved by previous commits.
83 | * ✅ **Unmodified** – Your problem must be reproducible without any modifications to the codebase in this
84 | repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code ⚠️.
85 |
86 | If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the 🐛 **
87 | Bug Report** [template](https://github.com/ultralytics/yolov5/issues/new/choose) and providing
88 | a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to help us better
89 | understand and diagnose your problem.
90 |
91 | ## License
92 |
93 | By contributing, you agree that your contributions will be licensed under
94 | the [GPL-3.0 license](https://choosealicense.com/licenses/gpl-3.0/)
95 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch
4 | FROM nvcr.io/nvidia/pytorch:21.05-py3
5 |
6 | # Install linux packages
7 | RUN apt update && apt install -y zip htop screen libgl1-mesa-glx
8 |
9 | # Install python dependencies
10 | COPY requirements.txt .
11 | RUN python -m pip install --upgrade pip
12 | RUN pip uninstall -y nvidia-tensorboard nvidia-tensorboard-plugin-dlprof
13 | RUN pip install --no-cache -r requirements.txt coremltools onnx gsutil notebook
14 | RUN pip install --no-cache -U torch torchvision numpy
15 | # RUN pip install --no-cache torch==1.9.0+cu111 torchvision==0.10.0+cu111 -f https://download.pytorch.org/whl/torch_stable.html
16 |
17 | # Create working directory
18 | RUN mkdir -p /usr/src/app
19 | WORKDIR /usr/src/app
20 |
21 | # Copy contents
22 | COPY . /usr/src/app
23 |
24 | # Set environment variables
25 | ENV HOME=/usr/src/app
26 |
27 |
28 | # Usage Examples -------------------------------------------------------------------------------------------------------
29 |
30 | # Build and Push
31 | # t=ultralytics/yolov5:latest && sudo docker build -t $t . && sudo docker push $t
32 |
33 | # Pull and Run
34 | # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t
35 |
36 | # Pull and Run with local directory access
37 | # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/datasets:/usr/src/datasets $t
38 |
39 | # Kill all
40 | # sudo docker kill $(sudo docker ps -q)
41 |
42 | # Kill all image-based
43 | # sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest)
44 |
45 | # Bash into running container
46 | # sudo docker exec -it 5a9b5863d93d bash
47 |
48 | # Bash into stopped container
49 | # id=$(sudo docker ps -qa) && sudo docker start $id && sudo docker exec -it $id bash
50 |
51 | # Clean up
52 | # docker system prune -a --volumes
53 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # yolov5-helmet-detection-python
2 | A Python implementation of Yolov5 to detect head or helmet in the wild in Jetson Xavier nx and Jetson nano. In Jetson Xavier Nx, it can achieve 33 FPS.
3 |
4 | You can see video play in [BILIBILI](https://www.bilibili.com/video/BV1Kv411M7u2/), or [YOUTUBE](https://www.youtube.com/watch?v=ZFCIcMngP08).
5 |
6 | if you have problem in this project, you can see this [artical](https://blog.csdn.net/weixin_42264234/article/details/121241573).
7 |
8 | If you want to try to train your own model, you can see [yolov5-helmet-detection-python](https://github.com/RichardoMrMu/yolov5-helmet-detection-python). Follow the readme to get your own model.
9 |
10 |
11 |
12 | # Dataset
13 | You can get the dataset from this [aistudio url](https://aistudio.baidu.com/aistudio/datasetdetail/50329). And the head & helmet detect project pdpd version can be found in this [url](https://github.com/PaddlePaddle/awesome-DeepLearning/tree/master/Paddle_Enterprise_CaseBook/Hemtle%20Detection). It is an amazing project.
14 |
15 | ## Data
16 | This pro needs dataset like
17 | ```
18 | ../datasets/coco128/images/im0.jpg #image
19 | ../datasets/coco128/labels/im0.txt #label
20 | ```
21 |
22 |
23 |
24 | Download the dataset and unzip it.
25 |
26 |
27 |
28 | ```shell
29 | unzip annnotations.zip
30 | unzip images.zip
31 | ```
32 | You can get this.
33 | ```
34 | ├── dataset
35 | ├── annotations
36 | │ ├── fire_000001.xml
37 | │ ├── fire_000002.xml
38 | │ ├── fire_000003.xml
39 | │ | ...
40 | ├── images
41 | │ ├── fire_000001.jpg
42 | │ ├── fire_000003.jpg
43 | │ ├── fire_000003.jpg
44 | │ | ...
45 | ├── label_list.txt
46 | ├── train.txt
47 | └── valid.txt
48 | ```
49 | You should turn xml files to txt files. You also can see [this](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data
50 | ).
51 | Open `script/sw2yolo.py`, Change `save_path` to your own save path,`root` as your data path, and `list_file` as `val_list.txt` and `train_list.txt` path.
52 |
53 | ```Python
54 | list_file = "./val_list.txt"
55 | xmls_path,imgs_path = get_file_path(list_file)
56 |
57 | # 将train_list中的xml 转成 txt, img放到img中
58 | save_path = './data/yolodata/fire/cocolike/val/'
59 | root = "./data/yolodata/fire/"
60 | train_img_root = root
61 | ```
62 |
63 | Then you need `script/yolov5-split-label-img.py` to split img and txt file.
64 |
65 |
66 | ```shell
67 | mkdir images
68 | mkdir lables
69 | mv ./train/images/* ./images/train
70 | mv ./train/labels/* ./labels/train
71 | mv ./val/iamges/* ./images/val
72 | mv ./val/lables/* ./lables/val
73 | ```
74 |
75 | Finally You can get this.
76 | ```
77 | ├── cocolike
78 | ├── lables
79 | │ ├── val
80 | │ ├── fire_000001.xml
81 | | ├── ...
82 | │ ├── train
83 | │ ├── fire_000002.xml
84 | | ├── ...
85 | │
86 | ├── images
87 | │ ├── val
88 | │ ├── fire_000001.jpg
89 | | ├── ...
90 | │ ├── train
91 | │ ├── fire_000003.jpg
92 | | ├── ...
93 | ├── label_list.txt
94 | ├── train.txt
95 | └── valid.txt
96 | ```
97 | ## Datafile
98 | `{porject}/yolov5/data/` add your own yaml files like `helmet.yaml`.
99 | ```yaml
100 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
101 | # COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017)
102 | # Example usage: python train.py --data coco128.yaml
103 | # parent
104 | # ├── yolov5
105 | # └── datasets
106 | # └── coco128 downloads here
107 |
108 |
109 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
110 | path: /home/data/tbw_data/face-dataset/yolodata/helmet/cocolike/ # dataset root dir
111 | train: images/train # train images (relative to 'path') 128 images
112 | val: images/val # val images (relative to 'path') 128 images
113 | test: # test images (optional)
114 |
115 | # Classes
116 | nc: 2 # number of classes
117 | names: ['head','helmet'] # class names
118 | ```
119 |
120 | # Train
121 | Change `{project}/train.py`'s data path as your own data yaml path.
122 |
123 | Change `batch-size ` as a suitable num. Change device if you have 2 or more gpu devices.
124 | Then
125 |
126 | ```shell
127 | python train.py
128 | ```
129 |
130 | # Test
131 | Use `detect.py` to test.
132 |
133 | ```shell
134 | python detect.py --source ./data/yolodata/helmet/cocolike/images --weights ./runs/train/exp/weights/best.pt
135 | ```
136 | You can see `{project}/runs/detect/` has png results.
137 |
--------------------------------------------------------------------------------
/assets/data.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/assets/data.png
--------------------------------------------------------------------------------
/assets/data2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/assets/data2.png
--------------------------------------------------------------------------------
/assets/helmet.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/assets/helmet.gif
--------------------------------------------------------------------------------
/assets/train.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/assets/train.png
--------------------------------------------------------------------------------
/data/Argoverse.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/
3 | # Example usage: python train.py --data Argoverse.yaml
4 | # parent
5 | # ├── yolov5
6 | # └── datasets
7 | # └── Argoverse ← downloads here
8 |
9 |
10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11 | path: ../datasets/Argoverse # dataset root dir
12 | train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images
13 | val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images
14 | test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview
15 |
16 | # Classes
17 | nc: 8 # number of classes
18 | names: ['person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign'] # class names
19 |
20 |
21 | # Download script/URL (optional) ---------------------------------------------------------------------------------------
22 | download: |
23 | import json
24 |
25 | from tqdm import tqdm
26 | from utils.general import download, Path
27 |
28 |
29 | def argoverse2yolo(set):
30 | labels = {}
31 | a = json.load(open(set, "rb"))
32 | for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."):
33 | img_id = annot['image_id']
34 | img_name = a['images'][img_id]['name']
35 | img_label_name = img_name[:-3] + "txt"
36 |
37 | cls = annot['category_id'] # instance class id
38 | x_center, y_center, width, height = annot['bbox']
39 | x_center = (x_center + width / 2) / 1920.0 # offset and scale
40 | y_center = (y_center + height / 2) / 1200.0 # offset and scale
41 | width /= 1920.0 # scale
42 | height /= 1200.0 # scale
43 |
44 | img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']]
45 | if not img_dir.exists():
46 | img_dir.mkdir(parents=True, exist_ok=True)
47 |
48 | k = str(img_dir / img_label_name)
49 | if k not in labels:
50 | labels[k] = []
51 | labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n")
52 |
53 | for k in labels:
54 | with open(k, "w") as f:
55 | f.writelines(labels[k])
56 |
57 |
58 | # Download
59 | dir = Path('../datasets/Argoverse') # dataset root dir
60 | urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip']
61 | download(urls, dir=dir, delete=False)
62 |
63 | # Convert
64 | annotations_dir = 'Argoverse-HD/annotations/'
65 | (dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images'
66 | for d in "train.json", "val.json":
67 | argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels
68 |
--------------------------------------------------------------------------------
/data/GlobalWheat2020.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # Global Wheat 2020 dataset http://www.global-wheat.com/
3 | # Example usage: python train.py --data GlobalWheat2020.yaml
4 | # parent
5 | # ├── yolov5
6 | # └── datasets
7 | # └── GlobalWheat2020 ← downloads here
8 |
9 |
10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11 | path: ../datasets/GlobalWheat2020 # dataset root dir
12 | train: # train images (relative to 'path') 3422 images
13 | - images/arvalis_1
14 | - images/arvalis_2
15 | - images/arvalis_3
16 | - images/ethz_1
17 | - images/rres_1
18 | - images/inrae_1
19 | - images/usask_1
20 | val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1)
21 | - images/ethz_1
22 | test: # test images (optional) 1276 images
23 | - images/utokyo_1
24 | - images/utokyo_2
25 | - images/nau_1
26 | - images/uq_1
27 |
28 | # Classes
29 | nc: 1 # number of classes
30 | names: ['wheat_head'] # class names
31 |
32 |
33 | # Download script/URL (optional) ---------------------------------------------------------------------------------------
34 | download: |
35 | from utils.general import download, Path
36 |
37 | # Download
38 | dir = Path(yaml['path']) # dataset root dir
39 | urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',
40 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']
41 | download(urls, dir=dir)
42 |
43 | # Make Directories
44 | for p in 'annotations', 'images', 'labels':
45 | (dir / p).mkdir(parents=True, exist_ok=True)
46 |
47 | # Move
48 | for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \
49 | 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':
50 | (dir / p).rename(dir / 'images' / p) # move to /images
51 | f = (dir / p).with_suffix('.json') # json file
52 | if f.exists():
53 | f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations
54 |
--------------------------------------------------------------------------------
/data/Objects365.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # Objects365 dataset https://www.objects365.org/
3 | # Example usage: python train.py --data Objects365.yaml
4 | # parent
5 | # ├── yolov5
6 | # └── datasets
7 | # └── Objects365 ← downloads here
8 |
9 |
10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11 | path: ../datasets/Objects365 # dataset root dir
12 | train: images/train # train images (relative to 'path') 1742289 images
13 | val: images/val # val images (relative to 'path') 5570 images
14 | test: # test images (optional)
15 |
16 | # Classes
17 | nc: 365 # number of classes
18 | names: ['Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup',
19 | 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book',
20 | 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag',
21 | 'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV',
22 | 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle',
23 | 'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird',
24 | 'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck',
25 | 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning',
26 | 'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife',
27 | 'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock',
28 | 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish',
29 | 'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan',
30 | 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard',
31 | 'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign',
32 | 'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat',
33 | 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard',
34 | 'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry',
35 | 'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks',
36 | 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors',
37 | 'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape',
38 | 'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck',
39 | 'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette',
40 | 'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket',
41 | 'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine',
42 | 'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine',
43 | 'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon',
44 | 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse',
45 | 'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball',
46 | 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin',
47 | 'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts',
48 | 'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit',
49 | 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD',
50 | 'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder',
51 | 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips',
52 | 'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab',
53 | 'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal',
54 | 'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart',
55 | 'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French',
56 | 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell',
57 | 'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil',
58 | 'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis']
59 |
60 |
61 | # Download script/URL (optional) ---------------------------------------------------------------------------------------
62 | download: |
63 | from pycocotools.coco import COCO
64 | from tqdm import tqdm
65 |
66 | from utils.general import download, Path
67 |
68 | # Make Directories
69 | dir = Path(yaml['path']) # dataset root dir
70 | for p in 'images', 'labels':
71 | (dir / p).mkdir(parents=True, exist_ok=True)
72 | for q in 'train', 'val':
73 | (dir / p / q).mkdir(parents=True, exist_ok=True)
74 |
75 | # Download
76 | url = "https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/train/"
77 | download([url + 'zhiyuan_objv2_train.tar.gz'], dir=dir, delete=False) # annotations json
78 | download([url + f for f in [f'patch{i}.tar.gz' for i in range(51)]], dir=dir / 'images' / 'train',
79 | curl=True, delete=False, threads=8)
80 |
81 | # Move
82 | train = dir / 'images' / 'train'
83 | for f in tqdm(train.rglob('*.jpg'), desc=f'Moving images'):
84 | f.rename(train / f.name) # move to /images/train
85 |
86 | # Labels
87 | coco = COCO(dir / 'zhiyuan_objv2_train.json')
88 | names = [x["name"] for x in coco.loadCats(coco.getCatIds())]
89 | for cid, cat in enumerate(names):
90 | catIds = coco.getCatIds(catNms=[cat])
91 | imgIds = coco.getImgIds(catIds=catIds)
92 | for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):
93 | width, height = im["width"], im["height"]
94 | path = Path(im["file_name"]) # image filename
95 | try:
96 | with open(dir / 'labels' / 'train' / path.with_suffix('.txt').name, 'a') as file:
97 | annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None)
98 | for a in coco.loadAnns(annIds):
99 | x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner)
100 | x, y = x + w / 2, y + h / 2 # xy to center
101 | file.write(f"{cid} {x / width:.5f} {y / height:.5f} {w / width:.5f} {h / height:.5f}\n")
102 |
103 | except Exception as e:
104 | print(e)
105 |
--------------------------------------------------------------------------------
/data/SKU-110K.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19
3 | # Example usage: python train.py --data SKU-110K.yaml
4 | # parent
5 | # ├── yolov5
6 | # └── datasets
7 | # └── SKU-110K ← downloads here
8 |
9 |
10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11 | path: ../datasets/SKU-110K # dataset root dir
12 | train: train.txt # train images (relative to 'path') 8219 images
13 | val: val.txt # val images (relative to 'path') 588 images
14 | test: test.txt # test images (optional) 2936 images
15 |
16 | # Classes
17 | nc: 1 # number of classes
18 | names: ['object'] # class names
19 |
20 |
21 | # Download script/URL (optional) ---------------------------------------------------------------------------------------
22 | download: |
23 | import shutil
24 | from tqdm import tqdm
25 | from utils.general import np, pd, Path, download, xyxy2xywh
26 |
27 | # Download
28 | dir = Path(yaml['path']) # dataset root dir
29 | parent = Path(dir.parent) # download dir
30 | urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz']
31 | download(urls, dir=parent, delete=False)
32 |
33 | # Rename directories
34 | if dir.exists():
35 | shutil.rmtree(dir)
36 | (parent / 'SKU110K_fixed').rename(dir) # rename dir
37 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir
38 |
39 | # Convert labels
40 | names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names
41 | for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv':
42 | x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations
43 | images, unique_images = x[:, 0], np.unique(x[:, 0])
44 | with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f:
45 | f.writelines(f'./images/{s}\n' for s in unique_images)
46 | for im in tqdm(unique_images, desc=f'Converting {dir / d}'):
47 | cls = 0 # single-class dataset
48 | with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f:
49 | for r in x[images == im]:
50 | w, h = r[6], r[7] # image width, height
51 | xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance
52 | f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label
53 |
--------------------------------------------------------------------------------
/data/VOC.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC
3 | # Example usage: python train.py --data VOC.yaml
4 | # parent
5 | # ├── yolov5
6 | # └── datasets
7 | # └── VOC ← downloads here
8 |
9 |
10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11 | path: ../datasets/VOC
12 | train: # train images (relative to 'path') 16551 images
13 | - images/train2012
14 | - images/train2007
15 | - images/val2012
16 | - images/val2007
17 | val: # val images (relative to 'path') 4952 images
18 | - images/test2007
19 | test: # test images (optional)
20 | - images/test2007
21 |
22 | # Classes
23 | nc: 20 # number of classes
24 | names: ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog',
25 | 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] # class names
26 |
27 |
28 | # Download script/URL (optional) ---------------------------------------------------------------------------------------
29 | download: |
30 | import xml.etree.ElementTree as ET
31 |
32 | from tqdm import tqdm
33 | from utils.general import download, Path
34 |
35 |
36 | def convert_label(path, lb_path, year, image_id):
37 | def convert_box(size, box):
38 | dw, dh = 1. / size[0], 1. / size[1]
39 | x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]
40 | return x * dw, y * dh, w * dw, h * dh
41 |
42 | in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml')
43 | out_file = open(lb_path, 'w')
44 | tree = ET.parse(in_file)
45 | root = tree.getroot()
46 | size = root.find('size')
47 | w = int(size.find('width').text)
48 | h = int(size.find('height').text)
49 |
50 | for obj in root.iter('object'):
51 | cls = obj.find('name').text
52 | if cls in yaml['names'] and not int(obj.find('difficult').text) == 1:
53 | xmlbox = obj.find('bndbox')
54 | bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')])
55 | cls_id = yaml['names'].index(cls) # class id
56 | out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n')
57 |
58 |
59 | # Download
60 | dir = Path(yaml['path']) # dataset root dir
61 | url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
62 | urls = [url + 'VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images
63 | url + 'VOCtest_06-Nov-2007.zip', # 438MB, 4953 images
64 | url + 'VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images
65 | download(urls, dir=dir / 'images', delete=False)
66 |
67 | # Convert
68 | path = dir / f'images/VOCdevkit'
69 | for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'):
70 | imgs_path = dir / 'images' / f'{image_set}{year}'
71 | lbs_path = dir / 'labels' / f'{image_set}{year}'
72 | imgs_path.mkdir(exist_ok=True, parents=True)
73 | lbs_path.mkdir(exist_ok=True, parents=True)
74 |
75 | image_ids = open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt').read().strip().split()
76 | for id in tqdm(image_ids, desc=f'{image_set}{year}'):
77 | f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path
78 | lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path
79 | f.rename(imgs_path / f.name) # move image
80 | convert_label(path, lb_path, year, id) # convert labels to YOLO format
81 |
--------------------------------------------------------------------------------
/data/VisDrone.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset
3 | # Example usage: python train.py --data VisDrone.yaml
4 | # parent
5 | # ├── yolov5
6 | # └── datasets
7 | # └── VisDrone ← downloads here
8 |
9 |
10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11 | path: ../datasets/VisDrone # dataset root dir
12 | train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images
13 | val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images
14 | test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images
15 |
16 | # Classes
17 | nc: 10 # number of classes
18 | names: ['pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor']
19 |
20 |
21 | # Download script/URL (optional) ---------------------------------------------------------------------------------------
22 | download: |
23 | from utils.general import download, os, Path
24 |
25 | def visdrone2yolo(dir):
26 | from PIL import Image
27 | from tqdm import tqdm
28 |
29 | def convert_box(size, box):
30 | # Convert VisDrone box to YOLO xywh box
31 | dw = 1. / size[0]
32 | dh = 1. / size[1]
33 | return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh
34 |
35 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory
36 | pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')
37 | for f in pbar:
38 | img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size
39 | lines = []
40 | with open(f, 'r') as file: # read annotation.txt
41 | for row in [x.split(',') for x in file.read().strip().splitlines()]:
42 | if row[4] == '0': # VisDrone 'ignored regions' class 0
43 | continue
44 | cls = int(row[5]) - 1
45 | box = convert_box(img_size, tuple(map(int, row[:4])))
46 | lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n")
47 | with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl:
48 | fl.writelines(lines) # write label.txt
49 |
50 |
51 | # Download
52 | dir = Path(yaml['path']) # dataset root dir
53 | urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',
54 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',
55 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',
56 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']
57 | download(urls, dir=dir)
58 |
59 | # Convert
60 | for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':
61 | visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels
62 |
--------------------------------------------------------------------------------
/data/clda.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017)
3 | # Example usage: python train.py --data coco128.yaml
4 | # parent
5 | # ├── yolov5
6 | # └── datasets
7 | # └── coco128 ← downloads here
8 |
9 |
10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11 | path: /home/data/tbw_data/face-dataset/dataset_for_jiangbo/Train/yolov5-train # dataset root dir
12 | train: images # train images (relative to 'path') 128 images
13 | val: images # val images (relative to 'path') 128 images
14 | test: # test images (optional)
15 |
16 | # Classes
17 | nc: 2 # number of classes
18 | names: ['hp_1','hp_2'] # class names
19 |
20 |
--------------------------------------------------------------------------------
/data/coco.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # COCO 2017 dataset http://cocodataset.org
3 | # Example usage: python train.py --data coco.yaml
4 | # parent
5 | # ├── yolov5
6 | # └── datasets
7 | # └── coco ← downloads here
8 |
9 |
10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11 | path: ../datasets/coco # dataset root dir
12 | train: train2017.txt # train images (relative to 'path') 118287 images
13 | val: val2017.txt # train images (relative to 'path') 5000 images
14 | test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
15 |
16 | # Classes
17 | nc: 80 # number of classes
18 | names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
19 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
20 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
21 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
22 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
23 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
24 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
25 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
26 | 'hair drier', 'toothbrush'] # class names
27 |
28 |
29 | # Download script/URL (optional)
30 | download: |
31 | from utils.general import download, Path
32 |
33 | # Download labels
34 | segments = False # segment or box labels
35 | dir = Path(yaml['path']) # dataset root dir
36 | url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
37 | urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels
38 | download(urls, dir=dir.parent)
39 |
40 | # Download data
41 | urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images
42 | 'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images
43 | 'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional)
44 | download(urls, dir=dir / 'images', threads=3)
45 |
--------------------------------------------------------------------------------
/data/coco128.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017)
3 | # Example usage: python train.py --data coco128.yaml
4 | # parent
5 | # ├── yolov5
6 | # └── datasets
7 | # └── coco128 ← downloads here
8 |
9 |
10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
11 | path: ../datasets/coco128 # dataset root dir
12 | train: images/train2017 # train images (relative to 'path') 128 images
13 | val: images/train2017 # val images (relative to 'path') 128 images
14 | test: # test images (optional)
15 |
16 | # Classes
17 | nc: 80 # number of classes
18 | names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
19 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
20 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
21 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
22 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
23 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
24 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
25 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
26 | 'hair drier', 'toothbrush'] # class names
27 |
28 |
29 | # Download script/URL (optional)
30 | download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip
--------------------------------------------------------------------------------
/data/fire.yaml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/data/fire.yaml
--------------------------------------------------------------------------------
/data/helmet.yaml:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/data/helmet.yaml
--------------------------------------------------------------------------------
/data/hyps/hyp.finetune.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # Hyperparameters for VOC finetuning
3 | # python train.py --batch 64 --weights yolov5m.pt --data VOC.yaml --img 512 --epochs 50
4 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
5 |
6 | # Hyperparameter Evolution Results
7 | # Generations: 306
8 | # P R mAP.5 mAP.5:.95 box obj cls
9 | # Metrics: 0.6 0.936 0.896 0.684 0.0115 0.00805 0.00146
10 |
11 | lr0: 0.0032
12 | lrf: 0.12
13 | momentum: 0.843
14 | weight_decay: 0.00036
15 | warmup_epochs: 2.0
16 | warmup_momentum: 0.5
17 | warmup_bias_lr: 0.05
18 | box: 0.0296
19 | cls: 0.243
20 | cls_pw: 0.631
21 | obj: 0.301
22 | obj_pw: 0.911
23 | iou_t: 0.2
24 | anchor_t: 2.91
25 | # anchors: 3.63
26 | fl_gamma: 0.0
27 | hsv_h: 0.0138
28 | hsv_s: 0.664
29 | hsv_v: 0.464
30 | degrees: 0.373
31 | translate: 0.245
32 | scale: 0.898
33 | shear: 0.602
34 | perspective: 0.0
35 | flipud: 0.00856
36 | fliplr: 0.5
37 | mosaic: 1.0
38 | mixup: 0.243
39 | copy_paste: 0.0
40 |
--------------------------------------------------------------------------------
/data/hyps/hyp.finetune_objects365.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | lr0: 0.00258
4 | lrf: 0.17
5 | momentum: 0.779
6 | weight_decay: 0.00058
7 | warmup_epochs: 1.33
8 | warmup_momentum: 0.86
9 | warmup_bias_lr: 0.0711
10 | box: 0.0539
11 | cls: 0.299
12 | cls_pw: 0.825
13 | obj: 0.632
14 | obj_pw: 1.0
15 | iou_t: 0.2
16 | anchor_t: 3.44
17 | anchors: 3.2
18 | fl_gamma: 0.0
19 | hsv_h: 0.0188
20 | hsv_s: 0.704
21 | hsv_v: 0.36
22 | degrees: 0.0
23 | translate: 0.0902
24 | scale: 0.491
25 | shear: 0.0
26 | perspective: 0.0
27 | flipud: 0.0
28 | fliplr: 0.5
29 | mosaic: 1.0
30 | mixup: 0.0
31 | copy_paste: 0.0
32 |
--------------------------------------------------------------------------------
/data/hyps/hyp.scratch-p6.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # Hyperparameters for COCO training from scratch
3 | # python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
4 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
5 |
6 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7 | lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
8 | momentum: 0.937 # SGD momentum/Adam beta1
9 | weight_decay: 0.0005 # optimizer weight decay 5e-4
10 | warmup_epochs: 3.0 # warmup epochs (fractions ok)
11 | warmup_momentum: 0.8 # warmup initial momentum
12 | warmup_bias_lr: 0.1 # warmup initial bias lr
13 | box: 0.05 # box loss gain
14 | cls: 0.3 # cls loss gain
15 | cls_pw: 1.0 # cls BCELoss positive_weight
16 | obj: 0.7 # obj loss gain (scale with pixels)
17 | obj_pw: 1.0 # obj BCELoss positive_weight
18 | iou_t: 0.20 # IoU training threshold
19 | anchor_t: 4.0 # anchor-multiple threshold
20 | # anchors: 3 # anchors per output layer (0 to ignore)
21 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
22 | hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
23 | hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
24 | hsv_v: 0.4 # image HSV-Value augmentation (fraction)
25 | degrees: 0.0 # image rotation (+/- deg)
26 | translate: 0.1 # image translation (+/- fraction)
27 | scale: 0.9 # image scale (+/- gain)
28 | shear: 0.0 # image shear (+/- deg)
29 | perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
30 | flipud: 0.0 # image flip up-down (probability)
31 | fliplr: 0.5 # image flip left-right (probability)
32 | mosaic: 1.0 # image mosaic (probability)
33 | mixup: 0.0 # image mixup (probability)
34 | copy_paste: 0.0 # segment copy-paste (probability)
35 |
--------------------------------------------------------------------------------
/data/hyps/hyp.scratch.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # Hyperparameters for COCO training from scratch
3 | # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
4 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
5 |
6 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7 | lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
8 | momentum: 0.937 # SGD momentum/Adam beta1
9 | weight_decay: 0.0005 # optimizer weight decay 5e-4
10 | warmup_epochs: 3.0 # warmup epochs (fractions ok)
11 | warmup_momentum: 0.8 # warmup initial momentum
12 | warmup_bias_lr: 0.1 # warmup initial bias lr
13 | box: 0.05 # box loss gain
14 | cls: 0.5 # cls loss gain
15 | cls_pw: 1.0 # cls BCELoss positive_weight
16 | obj: 1.0 # obj loss gain (scale with pixels)
17 | obj_pw: 1.0 # obj BCELoss positive_weight
18 | iou_t: 0.20 # IoU training threshold
19 | anchor_t: 4.0 # anchor-multiple threshold
20 | # anchors: 3 # anchors per output layer (0 to ignore)
21 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
22 | hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
23 | hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
24 | hsv_v: 0.4 # image HSV-Value augmentation (fraction)
25 | degrees: 0.0 # image rotation (+/- deg)
26 | translate: 0.1 # image translation (+/- fraction)
27 | scale: 0.5 # image scale (+/- gain)
28 | shear: 0.0 # image shear (+/- deg)
29 | perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
30 | flipud: 0.0 # image flip up-down (probability)
31 | fliplr: 0.5 # image flip left-right (probability)
32 | mosaic: 1.0 # image mosaic (probability)
33 | mixup: 0.0 # image mixup (probability)
34 | copy_paste: 0.0 # segment copy-paste (probability)
35 |
--------------------------------------------------------------------------------
/data/images/bus.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/data/images/bus.jpg
--------------------------------------------------------------------------------
/data/images/zidane.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/data/images/zidane.jpg
--------------------------------------------------------------------------------
/data/scripts/download_weights.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
3 | # Download latest models from https://github.com/ultralytics/yolov5/releases
4 | # Example usage: bash path/to/download_weights.sh
5 | # parent
6 | # └── yolov5
7 | # ├── yolov5s.pt ← downloads here
8 | # ├── yolov5m.pt
9 | # └── ...
10 |
11 | python - <= cls >= 0, f'incorrect class index {cls}'
74 |
75 | # Write YOLO label
76 | if id not in shapes:
77 | shapes[id] = Image.open(file).size
78 | box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True)
79 | with open((labels / id).with_suffix('.txt'), 'a') as f:
80 | f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt
81 | except Exception as e:
82 | print(f'WARNING: skipping one label for {file}: {e}')
83 |
84 |
85 | # Download manually from https://challenge.xviewdataset.org
86 | dir = Path(yaml['path']) # dataset root dir
87 | # urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels
88 | # 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images
89 | # 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels)
90 | # download(urls, dir=dir, delete=False)
91 |
92 | # Convert labels
93 | convert_labels(dir / 'xView_train.geojson')
94 |
95 | # Move images
96 | images = Path(dir / 'images')
97 | images.mkdir(parents=True, exist_ok=True)
98 | Path(dir / 'train_images').rename(dir / 'images' / 'train')
99 | Path(dir / 'val_images').rename(dir / 'images' / 'val')
100 |
101 | # Split
102 | autosplit(dir / 'images' / 'train')
103 |
--------------------------------------------------------------------------------
/export.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | Export a PyTorch model to TorchScript, ONNX, CoreML formats
4 |
5 | Usage:
6 | $ python path/to/export.py --weights yolov5s.pt --img 640 --batch 1
7 | """
8 |
9 | import argparse
10 | import sys
11 | import time
12 | from pathlib import Path
13 |
14 | import torch
15 | import torch.nn as nn
16 | from torch.utils.mobile_optimizer import optimize_for_mobile
17 |
18 | FILE = Path(__file__).absolute()
19 | sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path
20 |
21 | from models.common import Conv
22 | from models.yolo import Detect
23 | from models.experimental import attempt_load
24 | from utils.activations import Hardswish, SiLU
25 | from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging
26 | from utils.torch_utils import select_device
27 |
28 |
29 | def export_torchscript(model, img, file, optimize):
30 | # TorchScript model export
31 | prefix = colorstr('TorchScript:')
32 | try:
33 | print(f'\n{prefix} starting export with torch {torch.__version__}...')
34 | f = file.with_suffix('.torchscript.pt')
35 | ts = torch.jit.trace(model, img, strict=False)
36 | (optimize_for_mobile(ts) if optimize else ts).save(f)
37 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
38 | return ts
39 | except Exception as e:
40 | print(f'{prefix} export failure: {e}')
41 |
42 |
43 | def export_onnx(model, img, file, opset, train, dynamic, simplify):
44 | # ONNX model export
45 | prefix = colorstr('ONNX:')
46 | try:
47 | check_requirements(('onnx', 'onnx-simplifier'))
48 | import onnx
49 |
50 | print(f'\n{prefix} starting export with onnx {onnx.__version__}...')
51 | f = file.with_suffix('.onnx')
52 | torch.onnx.export(model, img, f, verbose=False, opset_version=opset,
53 | training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
54 | do_constant_folding=not train,
55 | input_names=['images'],
56 | output_names=['output'],
57 | dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
58 | 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
59 | } if dynamic else None)
60 |
61 | # Checks
62 | model_onnx = onnx.load(f) # load onnx model
63 | onnx.checker.check_model(model_onnx) # check onnx model
64 | # print(onnx.helper.printable_graph(model_onnx.graph)) # print
65 |
66 | # Simplify
67 | if simplify:
68 | try:
69 | import onnxsim
70 |
71 | print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
72 | model_onnx, check = onnxsim.simplify(
73 | model_onnx,
74 | dynamic_input_shape=dynamic,
75 | input_shapes={'images': list(img.shape)} if dynamic else None)
76 | assert check, 'assert check failed'
77 | onnx.save(model_onnx, f)
78 | except Exception as e:
79 | print(f'{prefix} simplifier failure: {e}')
80 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
81 | print(f"{prefix} run --dynamic ONNX model inference with: 'python detect.py --weights {f}'")
82 | except Exception as e:
83 | print(f'{prefix} export failure: {e}')
84 |
85 |
86 | def export_coreml(model, img, file):
87 | # CoreML model export
88 | prefix = colorstr('CoreML:')
89 | try:
90 | check_requirements(('coremltools',))
91 | import coremltools as ct
92 |
93 | print(f'\n{prefix} starting export with coremltools {ct.__version__}...')
94 | f = file.with_suffix('.mlmodel')
95 | model.train() # CoreML exports should be placed in model.train() mode
96 | ts = torch.jit.trace(model, img, strict=False) # TorchScript model
97 | model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
98 | model.save(f)
99 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
100 | except Exception as e:
101 | print(f'\n{prefix} export failure: {e}')
102 |
103 |
104 | def run(weights='./yolov5s.pt', # weights path
105 | img_size=(640, 640), # image (height, width)
106 | batch_size=1, # batch size
107 | device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
108 | include=('torchscript', 'onnx', 'coreml'), # include formats
109 | half=False, # FP16 half-precision export
110 | inplace=False, # set YOLOv5 Detect() inplace=True
111 | train=False, # model.train() mode
112 | optimize=False, # TorchScript: optimize for mobile
113 | dynamic=False, # ONNX: dynamic axes
114 | simplify=False, # ONNX: simplify model
115 | opset=12, # ONNX: opset version
116 | ):
117 | t = time.time()
118 | include = [x.lower() for x in include]
119 | img_size *= 2 if len(img_size) == 1 else 1 # expand
120 | file = Path(weights)
121 |
122 | # Load PyTorch model
123 | device = select_device(device)
124 | assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
125 | model = attempt_load(weights, map_location=device) # load FP32 model
126 | names = model.names
127 |
128 | # Input
129 | gs = int(max(model.stride)) # grid size (max stride)
130 | img_size = [check_img_size(x, gs) for x in img_size] # verify img_size are gs-multiples
131 | img = torch.zeros(batch_size, 3, *img_size).to(device) # image size(1,3,320,192) iDetection
132 |
133 | # Update model
134 | if half:
135 | img, model = img.half(), model.half() # to FP16
136 | model.train() if train else model.eval() # training mode = no Detect() layer grid construction
137 | for k, m in model.named_modules():
138 | if isinstance(m, Conv): # assign export-friendly activations
139 | if isinstance(m.act, nn.Hardswish):
140 | m.act = Hardswish()
141 | elif isinstance(m.act, nn.SiLU):
142 | m.act = SiLU()
143 | elif isinstance(m, Detect):
144 | m.inplace = inplace
145 | m.onnx_dynamic = dynamic
146 | # m.forward = m.forward_export # assign forward (optional)
147 |
148 | for _ in range(2):
149 | y = model(img) # dry runs
150 | print(f"\n{colorstr('PyTorch:')} starting from {weights} ({file_size(weights):.1f} MB)")
151 |
152 | # Exports
153 | if 'torchscript' in include:
154 | export_torchscript(model, img, file, optimize)
155 | if 'onnx' in include:
156 | export_onnx(model, img, file, opset, train, dynamic, simplify)
157 | if 'coreml' in include:
158 | export_coreml(model, img, file)
159 |
160 | # Finish
161 | print(f'\nExport complete ({time.time() - t:.2f}s)'
162 | f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
163 | f'\nVisualize with https://netron.app')
164 |
165 |
166 | def parse_opt():
167 | parser = argparse.ArgumentParser()
168 | parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
169 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image (height, width)')
170 | parser.add_argument('--batch-size', type=int, default=1, help='batch size')
171 | parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
172 | parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats')
173 | parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
174 | parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
175 | parser.add_argument('--train', action='store_true', help='model.train() mode')
176 | parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
177 | parser.add_argument('--dynamic', action='store_true', help='ONNX: dynamic axes')
178 | parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
179 | parser.add_argument('--opset', type=int, default=13, help='ONNX: opset version')
180 | opt = parser.parse_args()
181 | return opt
182 |
183 |
184 | def main(opt):
185 | set_logging()
186 | print(colorstr('export: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
187 | run(**vars(opt))
188 |
189 |
190 | if __name__ == "__main__":
191 | opt = parse_opt()
192 | main(opt)
193 |
--------------------------------------------------------------------------------
/hubconf.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/
4 |
5 | Usage:
6 | import torch
7 | model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
8 | """
9 |
10 | import torch
11 |
12 |
13 | def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
14 | """Creates a specified YOLOv5 model
15 |
16 | Arguments:
17 | name (str): name of model, i.e. 'yolov5s'
18 | pretrained (bool): load pretrained weights into the model
19 | channels (int): number of input channels
20 | classes (int): number of model classes
21 | autoshape (bool): apply YOLOv5 .autoshape() wrapper to model
22 | verbose (bool): print all information to screen
23 | device (str, torch.device, None): device to use for model parameters
24 |
25 | Returns:
26 | YOLOv5 pytorch model
27 | """
28 | from pathlib import Path
29 |
30 | from models.yolo import Model
31 | from models.experimental import attempt_load
32 | from utils.general import check_requirements, set_logging
33 | from utils.downloads import attempt_download
34 | from utils.torch_utils import select_device
35 |
36 | file = Path(__file__).absolute()
37 | check_requirements(requirements=file.parent / 'requirements.txt', exclude=('tensorboard', 'thop', 'opencv-python'))
38 | set_logging(verbose=verbose)
39 |
40 | save_dir = Path('') if str(name).endswith('.pt') else file.parent
41 | path = (save_dir / name).with_suffix('.pt') # checkpoint path
42 | try:
43 | device = select_device(('0' if torch.cuda.is_available() else 'cpu') if device is None else device)
44 |
45 | if pretrained and channels == 3 and classes == 80:
46 | model = attempt_load(path, map_location=device) # download/load FP32 model
47 | else:
48 | cfg = list((Path(__file__).parent / 'models').rglob(f'{name}.yaml'))[0] # model.yaml path
49 | model = Model(cfg, channels, classes) # create model
50 | if pretrained:
51 | ckpt = torch.load(attempt_download(path), map_location=device) # load
52 | msd = model.state_dict() # model state_dict
53 | csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
54 | csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
55 | model.load_state_dict(csd, strict=False) # load
56 | if len(ckpt['model'].names) == classes:
57 | model.names = ckpt['model'].names # set class names attribute
58 | if autoshape:
59 | model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
60 | return model.to(device)
61 |
62 | except Exception as e:
63 | help_url = 'https://github.com/ultralytics/yolov5/issues/36'
64 | s = 'Cache may be out of date, try `force_reload=True`. See %s for help.' % help_url
65 | raise Exception(s) from e
66 |
67 |
68 | def custom(path='path/to/model.pt', autoshape=True, verbose=True, device=None):
69 | # YOLOv5 custom or local model
70 | return _create(path, autoshape=autoshape, verbose=verbose, device=device)
71 |
72 |
73 | def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
74 | # YOLOv5-small model https://github.com/ultralytics/yolov5
75 | return _create('yolov5s', pretrained, channels, classes, autoshape, verbose, device)
76 |
77 |
78 | def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
79 | # YOLOv5-medium model https://github.com/ultralytics/yolov5
80 | return _create('yolov5m', pretrained, channels, classes, autoshape, verbose, device)
81 |
82 |
83 | def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
84 | # YOLOv5-large model https://github.com/ultralytics/yolov5
85 | return _create('yolov5l', pretrained, channels, classes, autoshape, verbose, device)
86 |
87 |
88 | def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
89 | # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
90 | return _create('yolov5x', pretrained, channels, classes, autoshape, verbose, device)
91 |
92 |
93 | def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
94 | # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
95 | return _create('yolov5s6', pretrained, channels, classes, autoshape, verbose, device)
96 |
97 |
98 | def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
99 | # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
100 | return _create('yolov5m6', pretrained, channels, classes, autoshape, verbose, device)
101 |
102 |
103 | def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
104 | # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
105 | return _create('yolov5l6', pretrained, channels, classes, autoshape, verbose, device)
106 |
107 |
108 | def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
109 | # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
110 | return _create('yolov5x6', pretrained, channels, classes, autoshape, verbose, device)
111 |
112 |
113 | if __name__ == '__main__':
114 | model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) # pretrained
115 | # model = custom(path='path/to/model.pt') # custom
116 |
117 | # Verify inference
118 | import cv2
119 | import numpy as np
120 | from PIL import Image
121 | from pathlib import Path
122 |
123 | imgs = ['data/images/zidane.jpg', # filename
124 | Path('data/images/zidane.jpg'), # Path
125 | 'https://ultralytics.com/images/zidane.jpg', # URI
126 | cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
127 | Image.open('data/images/bus.jpg'), # PIL
128 | np.zeros((320, 640, 3))] # numpy
129 |
130 | results = model(imgs) # batched inference
131 | results.print()
132 | results.save()
133 |
--------------------------------------------------------------------------------
/models/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/models/__init__.py
--------------------------------------------------------------------------------
/models/experimental.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | Experimental modules
4 | """
5 |
6 | import numpy as np
7 | import torch
8 | import torch.nn as nn
9 |
10 | from models.common import Conv
11 | from utils.downloads import attempt_download
12 |
13 |
14 | class CrossConv(nn.Module):
15 | # Cross Convolution Downsample
16 | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
17 | # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
18 | super().__init__()
19 | c_ = int(c2 * e) # hidden channels
20 | self.cv1 = Conv(c1, c_, (1, k), (1, s))
21 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
22 | self.add = shortcut and c1 == c2
23 |
24 | def forward(self, x):
25 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
26 |
27 |
28 | class Sum(nn.Module):
29 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
30 | def __init__(self, n, weight=False): # n: number of inputs
31 | super().__init__()
32 | self.weight = weight # apply weights boolean
33 | self.iter = range(n - 1) # iter object
34 | if weight:
35 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
36 |
37 | def forward(self, x):
38 | y = x[0] # no weight
39 | if self.weight:
40 | w = torch.sigmoid(self.w) * 2
41 | for i in self.iter:
42 | y = y + x[i + 1] * w[i]
43 | else:
44 | for i in self.iter:
45 | y = y + x[i + 1]
46 | return y
47 |
48 |
49 | class MixConv2d(nn.Module):
50 | # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
51 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
52 | super().__init__()
53 | groups = len(k)
54 | if equal_ch: # equal c_ per group
55 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
56 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
57 | else: # equal weight.numel() per group
58 | b = [c2] + [0] * groups
59 | a = np.eye(groups + 1, groups, k=-1)
60 | a -= np.roll(a, 1, axis=1)
61 | a *= np.array(k) ** 2
62 | a[0] = 1
63 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
64 |
65 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
66 | self.bn = nn.BatchNorm2d(c2)
67 | self.act = nn.LeakyReLU(0.1, inplace=True)
68 |
69 | def forward(self, x):
70 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
71 |
72 |
73 | class Ensemble(nn.ModuleList):
74 | # Ensemble of models
75 | def __init__(self):
76 | super().__init__()
77 |
78 | def forward(self, x, augment=False, profile=False, visualize=False):
79 | y = []
80 | for module in self:
81 | y.append(module(x, augment, profile, visualize)[0])
82 | # y = torch.stack(y).max(0)[0] # max ensemble
83 | # y = torch.stack(y).mean(0) # mean ensemble
84 | y = torch.cat(y, 1) # nms ensemble
85 | return y, None # inference, train output
86 |
87 |
88 | def attempt_load(weights, map_location=None, inplace=True, fuse=True):
89 | from models.yolo import Detect, Model
90 |
91 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
92 | model = Ensemble()
93 | for w in weights if isinstance(weights, list) else [weights]:
94 | ckpt = torch.load(attempt_download(w), map_location=map_location) # load
95 | if fuse:
96 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
97 | else:
98 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().eval()) # without layer fuse
99 |
100 |
101 | # Compatibility updates
102 | for m in model.modules():
103 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:
104 | m.inplace = inplace # pytorch 1.7.0 compatibility
105 | elif type(m) is Conv:
106 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
107 |
108 | if len(model) == 1:
109 | return model[-1] # return model
110 | else:
111 | print(f'Ensemble created with {weights}\n')
112 | for k in ['names']:
113 | setattr(model, k, getattr(model[-1], k))
114 | model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
115 | return model # return ensemble
116 |
--------------------------------------------------------------------------------
/models/hub/anchors.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | # Default anchors for COCO data
3 |
4 |
5 | # P5 -------------------------------------------------------------------------------------------------------------------
6 | # P5-640:
7 | anchors_p5_640:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 |
13 | # P6 -------------------------------------------------------------------------------------------------------------------
14 | # P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387
15 | anchors_p6_640:
16 | - [9,11, 21,19, 17,41] # P3/8
17 | - [43,32, 39,70, 86,64] # P4/16
18 | - [65,131, 134,130, 120,265] # P5/32
19 | - [282,180, 247,354, 512,387] # P6/64
20 |
21 | # P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792
22 | anchors_p6_1280:
23 | - [19,27, 44,40, 38,94] # P3/8
24 | - [96,68, 86,152, 180,137] # P4/16
25 | - [140,301, 303,264, 238,542] # P5/32
26 | - [436,615, 739,380, 925,792] # P6/64
27 |
28 | # P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187
29 | anchors_p6_1920:
30 | - [28,41, 67,59, 57,141] # P3/8
31 | - [144,103, 129,227, 270,205] # P4/16
32 | - [209,452, 455,396, 358,812] # P5/32
33 | - [653,922, 1109,570, 1387,1187] # P6/64
34 |
35 |
36 | # P7 -------------------------------------------------------------------------------------------------------------------
37 | # P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372
38 | anchors_p7_640:
39 | - [11,11, 13,30, 29,20] # P3/8
40 | - [30,46, 61,38, 39,92] # P4/16
41 | - [78,80, 146,66, 79,163] # P5/32
42 | - [149,150, 321,143, 157,303] # P6/64
43 | - [257,402, 359,290, 524,372] # P7/128
44 |
45 | # P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818
46 | anchors_p7_1280:
47 | - [19,22, 54,36, 32,77] # P3/8
48 | - [70,83, 138,71, 75,173] # P4/16
49 | - [165,159, 148,334, 375,151] # P5/32
50 | - [334,317, 251,626, 499,474] # P6/64
51 | - [750,326, 534,814, 1079,818] # P7/128
52 |
53 | # P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227
54 | anchors_p7_1920:
55 | - [29,34, 81,55, 47,115] # P3/8
56 | - [105,124, 207,107, 113,259] # P4/16
57 | - [247,238, 222,500, 563,227] # P5/32
58 | - [501,476, 376,939, 749,711] # P6/64
59 | - [1126,489, 801,1222, 1618,1227] # P7/128
60 |
--------------------------------------------------------------------------------
/models/hub/yolov3-spp.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # darknet53 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Conv, [32, 3, 1]], # 0
16 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17 | [-1, 1, Bottleneck, [64]],
18 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19 | [-1, 2, Bottleneck, [128]],
20 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21 | [-1, 8, Bottleneck, [256]],
22 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23 | [-1, 8, Bottleneck, [512]],
24 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25 | [-1, 4, Bottleneck, [1024]], # 10
26 | ]
27 |
28 | # YOLOv3-SPP head
29 | head:
30 | [[-1, 1, Bottleneck, [1024, False]],
31 | [-1, 1, SPP, [512, [5, 9, 13]]],
32 | [-1, 1, Conv, [1024, 3, 1]],
33 | [-1, 1, Conv, [512, 1, 1]],
34 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35 |
36 | [-2, 1, Conv, [256, 1, 1]],
37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
39 | [-1, 1, Bottleneck, [512, False]],
40 | [-1, 1, Bottleneck, [512, False]],
41 | [-1, 1, Conv, [256, 1, 1]],
42 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
43 |
44 | [-2, 1, Conv, [128, 1, 1]],
45 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
46 | [[-1, 6], 1, Concat, [1]], # cat backbone P3
47 | [-1, 1, Bottleneck, [256, False]],
48 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
49 |
50 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
51 | ]
52 |
--------------------------------------------------------------------------------
/models/hub/yolov3-tiny.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors:
8 | - [10,14, 23,27, 37,58] # P4/16
9 | - [81,82, 135,169, 344,319] # P5/32
10 |
11 | # YOLOv3-tiny backbone
12 | backbone:
13 | # [from, number, module, args]
14 | [[-1, 1, Conv, [16, 3, 1]], # 0
15 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2
16 | [-1, 1, Conv, [32, 3, 1]],
17 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4
18 | [-1, 1, Conv, [64, 3, 1]],
19 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8
20 | [-1, 1, Conv, [128, 3, 1]],
21 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16
22 | [-1, 1, Conv, [256, 3, 1]],
23 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32
24 | [-1, 1, Conv, [512, 3, 1]],
25 | [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11
26 | [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12
27 | ]
28 |
29 | # YOLOv3-tiny head
30 | head:
31 | [[-1, 1, Conv, [1024, 3, 1]],
32 | [-1, 1, Conv, [256, 1, 1]],
33 | [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large)
34 |
35 | [-2, 1, Conv, [128, 1, 1]],
36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
38 | [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium)
39 |
40 | [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5)
41 | ]
42 |
--------------------------------------------------------------------------------
/models/hub/yolov3.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # darknet53 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Conv, [32, 3, 1]], # 0
16 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2
17 | [-1, 1, Bottleneck, [64]],
18 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4
19 | [-1, 2, Bottleneck, [128]],
20 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8
21 | [-1, 8, Bottleneck, [256]],
22 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16
23 | [-1, 8, Bottleneck, [512]],
24 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
25 | [-1, 4, Bottleneck, [1024]], # 10
26 | ]
27 |
28 | # YOLOv3 head
29 | head:
30 | [[-1, 1, Bottleneck, [1024, False]],
31 | [-1, 1, Conv, [512, [1, 1]]],
32 | [-1, 1, Conv, [1024, 3, 1]],
33 | [-1, 1, Conv, [512, 1, 1]],
34 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
35 |
36 | [-2, 1, Conv, [256, 1, 1]],
37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38 | [[-1, 8], 1, Concat, [1]], # cat backbone P4
39 | [-1, 1, Bottleneck, [512, False]],
40 | [-1, 1, Bottleneck, [512, False]],
41 | [-1, 1, Conv, [256, 1, 1]],
42 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
43 |
44 | [-2, 1, Conv, [128, 1, 1]],
45 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
46 | [[-1, 6], 1, Concat, [1]], # cat backbone P3
47 | [-1, 1, Bottleneck, [256, False]],
48 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
49 |
50 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
51 | ]
52 |
--------------------------------------------------------------------------------
/models/hub/yolov5-bifpn.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]]
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 BiFPN head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14, 6], 1, Concat, [1]], # cat P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/hub/yolov5-fpn.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, Bottleneck, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, BottleneckCSP, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, BottleneckCSP, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 6, BottleneckCSP, [1024]], # 9
25 | ]
26 |
27 | # YOLOv5 FPN head
28 | head:
29 | [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large)
30 |
31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
33 | [-1, 1, Conv, [512, 1, 1]],
34 | [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium)
35 |
36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
38 | [-1, 1, Conv, [256, 1, 1]],
39 | [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small)
40 |
41 | [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
42 | ]
43 |
--------------------------------------------------------------------------------
/models/hub/yolov5-p2.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors: 3
8 |
9 | # YOLOv5 backbone
10 | backbone:
11 | # [from, number, module, args]
12 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
13 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14 | [-1, 3, C3, [128]],
15 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16 | [-1, 9, C3, [256]],
17 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18 | [-1, 9, C3, [512]],
19 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
20 | [-1, 1, SPP, [1024, [5, 9, 13]]],
21 | [-1, 3, C3, [1024, False]], # 9
22 | ]
23 |
24 | # YOLOv5 head
25 | head:
26 | [[-1, 1, Conv, [512, 1, 1]],
27 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
28 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
29 | [-1, 3, C3, [512, False]], # 13
30 |
31 | [-1, 1, Conv, [256, 1, 1]],
32 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
33 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
34 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
35 |
36 | [-1, 1, Conv, [128, 1, 1]],
37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
38 | [[-1, 2], 1, Concat, [1]], # cat backbone P2
39 | [-1, 1, C3, [128, False]], # 21 (P2/4-xsmall)
40 |
41 | [-1, 1, Conv, [128, 3, 2]],
42 | [[-1, 18], 1, Concat, [1]], # cat head P3
43 | [-1, 3, C3, [256, False]], # 24 (P3/8-small)
44 |
45 | [-1, 1, Conv, [256, 3, 2]],
46 | [[-1, 14], 1, Concat, [1]], # cat head P4
47 | [-1, 3, C3, [512, False]], # 27 (P4/16-medium)
48 |
49 | [-1, 1, Conv, [512, 3, 2]],
50 | [[-1, 10], 1, Concat, [1]], # cat head P5
51 | [-1, 3, C3, [1024, False]], # 30 (P5/32-large)
52 |
53 | [[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P2, P3, P4, P5)
54 | ]
55 |
--------------------------------------------------------------------------------
/models/hub/yolov5-p6.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors: 3
8 |
9 | # YOLOv5 backbone
10 | backbone:
11 | # [from, number, module, args]
12 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
13 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14 | [-1, 3, C3, [128]],
15 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16 | [-1, 9, C3, [256]],
17 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18 | [-1, 9, C3, [512]],
19 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
20 | [-1, 3, C3, [768]],
21 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
22 | [-1, 1, SPP, [1024, [3, 5, 7]]],
23 | [-1, 3, C3, [1024, False]], # 11
24 | ]
25 |
26 | # YOLOv5 head
27 | head:
28 | [[-1, 1, Conv, [768, 1, 1]],
29 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
30 | [[-1, 8], 1, Concat, [1]], # cat backbone P5
31 | [-1, 3, C3, [768, False]], # 15
32 |
33 | [-1, 1, Conv, [512, 1, 1]],
34 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
35 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
36 | [-1, 3, C3, [512, False]], # 19
37 |
38 | [-1, 1, Conv, [256, 1, 1]],
39 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
40 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
41 | [-1, 3, C3, [256, False]], # 23 (P3/8-small)
42 |
43 | [-1, 1, Conv, [256, 3, 2]],
44 | [[-1, 20], 1, Concat, [1]], # cat head P4
45 | [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
46 |
47 | [-1, 1, Conv, [512, 3, 2]],
48 | [[-1, 16], 1, Concat, [1]], # cat head P5
49 | [-1, 3, C3, [768, False]], # 29 (P5/32-large)
50 |
51 | [-1, 1, Conv, [768, 3, 2]],
52 | [[-1, 12], 1, Concat, [1]], # cat head P6
53 | [-1, 3, C3, [1024, False]], # 32 (P5/64-xlarge)
54 |
55 | [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
56 | ]
57 |
--------------------------------------------------------------------------------
/models/hub/yolov5-p7.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors: 3
8 |
9 | # YOLOv5 backbone
10 | backbone:
11 | # [from, number, module, args]
12 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
13 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
14 | [-1, 3, C3, [128]],
15 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
16 | [-1, 9, C3, [256]],
17 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
18 | [-1, 9, C3, [512]],
19 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
20 | [-1, 3, C3, [768]],
21 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
22 | [-1, 3, C3, [1024]],
23 | [-1, 1, Conv, [1280, 3, 2]], # 11-P7/128
24 | [-1, 1, SPP, [1280, [3, 5]]],
25 | [-1, 3, C3, [1280, False]], # 13
26 | ]
27 |
28 | # YOLOv5 head
29 | head:
30 | [[-1, 1, Conv, [1024, 1, 1]],
31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
32 | [[-1, 10], 1, Concat, [1]], # cat backbone P6
33 | [-1, 3, C3, [1024, False]], # 17
34 |
35 | [-1, 1, Conv, [768, 1, 1]],
36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
37 | [[-1, 8], 1, Concat, [1]], # cat backbone P5
38 | [-1, 3, C3, [768, False]], # 21
39 |
40 | [-1, 1, Conv, [512, 1, 1]],
41 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
42 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
43 | [-1, 3, C3, [512, False]], # 25
44 |
45 | [-1, 1, Conv, [256, 1, 1]],
46 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
47 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
48 | [-1, 3, C3, [256, False]], # 29 (P3/8-small)
49 |
50 | [-1, 1, Conv, [256, 3, 2]],
51 | [[-1, 26], 1, Concat, [1]], # cat head P4
52 | [-1, 3, C3, [512, False]], # 32 (P4/16-medium)
53 |
54 | [-1, 1, Conv, [512, 3, 2]],
55 | [[-1, 22], 1, Concat, [1]], # cat head P5
56 | [-1, 3, C3, [768, False]], # 35 (P5/32-large)
57 |
58 | [-1, 1, Conv, [768, 3, 2]],
59 | [[-1, 18], 1, Concat, [1]], # cat head P6
60 | [-1, 3, C3, [1024, False]], # 38 (P6/64-xlarge)
61 |
62 | [-1, 1, Conv, [1024, 3, 2]],
63 | [[-1, 14], 1, Concat, [1]], # cat head P7
64 | [-1, 3, C3, [1280, False]], # 41 (P7/128-xxlarge)
65 |
66 | [[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6, P7)
67 | ]
68 |
--------------------------------------------------------------------------------
/models/hub/yolov5-panet.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, BottleneckCSP, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, BottleneckCSP, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, BottleneckCSP, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, BottleneckCSP, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 PANet head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, BottleneckCSP, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/hub/yolov5l6.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors:
8 | - [19,27, 44,40, 38,94] # P3/8
9 | - [96,68, 86,152, 180,137] # P4/16
10 | - [140,301, 303,264, 238,542] # P5/32
11 | - [436,615, 739,380, 925,792] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
17 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18 | [-1, 3, C3, [128]],
19 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20 | [-1, 9, C3, [256]],
21 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22 | [-1, 9, C3, [512]],
23 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24 | [-1, 3, C3, [768]],
25 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26 | [-1, 1, SPP, [1024, [3, 5, 7]]],
27 | [-1, 3, C3, [1024, False]], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [[-1, 1, Conv, [768, 1, 1]],
33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34 | [[-1, 8], 1, Concat, [1]], # cat backbone P5
35 | [-1, 3, C3, [768, False]], # 15
36 |
37 | [-1, 1, Conv, [512, 1, 1]],
38 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
40 | [-1, 3, C3, [512, False]], # 19
41 |
42 | [-1, 1, Conv, [256, 1, 1]],
43 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
45 | [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46 |
47 | [-1, 1, Conv, [256, 3, 2]],
48 | [[-1, 20], 1, Concat, [1]], # cat head P4
49 | [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50 |
51 | [-1, 1, Conv, [512, 3, 2]],
52 | [[-1, 16], 1, Concat, [1]], # cat head P5
53 | [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54 |
55 | [-1, 1, Conv, [768, 3, 2]],
56 | [[-1, 12], 1, Concat, [1]], # cat head P6
57 | [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58 |
59 | [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/hub/yolov5m6.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 0.67 # model depth multiple
6 | width_multiple: 0.75 # layer channel multiple
7 | anchors:
8 | - [19,27, 44,40, 38,94] # P3/8
9 | - [96,68, 86,152, 180,137] # P4/16
10 | - [140,301, 303,264, 238,542] # P5/32
11 | - [436,615, 739,380, 925,792] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
17 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18 | [-1, 3, C3, [128]],
19 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20 | [-1, 9, C3, [256]],
21 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22 | [-1, 9, C3, [512]],
23 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24 | [-1, 3, C3, [768]],
25 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26 | [-1, 1, SPP, [1024, [3, 5, 7]]],
27 | [-1, 3, C3, [1024, False]], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [[-1, 1, Conv, [768, 1, 1]],
33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34 | [[-1, 8], 1, Concat, [1]], # cat backbone P5
35 | [-1, 3, C3, [768, False]], # 15
36 |
37 | [-1, 1, Conv, [512, 1, 1]],
38 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
40 | [-1, 3, C3, [512, False]], # 19
41 |
42 | [-1, 1, Conv, [256, 1, 1]],
43 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
45 | [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46 |
47 | [-1, 1, Conv, [256, 3, 2]],
48 | [[-1, 20], 1, Concat, [1]], # cat head P4
49 | [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50 |
51 | [-1, 1, Conv, [512, 3, 2]],
52 | [[-1, 16], 1, Concat, [1]], # cat head P5
53 | [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54 |
55 | [-1, 1, Conv, [768, 3, 2]],
56 | [[-1, 12], 1, Concat, [1]], # cat head P6
57 | [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58 |
59 | [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/hub/yolov5s-ghost.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 0.33 # model depth multiple
6 | width_multiple: 0.50 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, GhostConv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3Ghost, [128]],
18 | [-1, 1, GhostConv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3Ghost, [256]],
20 | [-1, 1, GhostConv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3Ghost, [512]],
22 | [-1, 1, GhostConv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3Ghost, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, GhostConv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3Ghost, [512, False]], # 13
33 |
34 | [-1, 1, GhostConv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3Ghost, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, GhostConv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3Ghost, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, GhostConv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3Ghost, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/hub/yolov5s-transformer.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 0.33 # model depth multiple
6 | width_multiple: 0.50 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3TR, [1024, False]], # 9 <-------- C3TR() Transformer module
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/hub/yolov5s6.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 0.33 # model depth multiple
6 | width_multiple: 0.50 # layer channel multiple
7 | anchors:
8 | - [19,27, 44,40, 38,94] # P3/8
9 | - [96,68, 86,152, 180,137] # P4/16
10 | - [140,301, 303,264, 238,542] # P5/32
11 | - [436,615, 739,380, 925,792] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
17 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18 | [-1, 3, C3, [128]],
19 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20 | [-1, 9, C3, [256]],
21 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22 | [-1, 9, C3, [512]],
23 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24 | [-1, 3, C3, [768]],
25 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26 | [-1, 1, SPP, [1024, [3, 5, 7]]],
27 | [-1, 3, C3, [1024, False]], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [[-1, 1, Conv, [768, 1, 1]],
33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34 | [[-1, 8], 1, Concat, [1]], # cat backbone P5
35 | [-1, 3, C3, [768, False]], # 15
36 |
37 | [-1, 1, Conv, [512, 1, 1]],
38 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
40 | [-1, 3, C3, [512, False]], # 19
41 |
42 | [-1, 1, Conv, [256, 1, 1]],
43 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
45 | [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46 |
47 | [-1, 1, Conv, [256, 3, 2]],
48 | [[-1, 20], 1, Concat, [1]], # cat head P4
49 | [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50 |
51 | [-1, 1, Conv, [512, 3, 2]],
52 | [[-1, 16], 1, Concat, [1]], # cat head P5
53 | [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54 |
55 | [-1, 1, Conv, [768, 3, 2]],
56 | [[-1, 12], 1, Concat, [1]], # cat head P6
57 | [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58 |
59 | [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/hub/yolov5x6.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.33 # model depth multiple
6 | width_multiple: 1.25 # layer channel multiple
7 | anchors:
8 | - [19,27, 44,40, 38,94] # P3/8
9 | - [96,68, 86,152, 180,137] # P4/16
10 | - [140,301, 303,264, 238,542] # P5/32
11 | - [436,615, 739,380, 925,792] # P6/64
12 |
13 | # YOLOv5 backbone
14 | backbone:
15 | # [from, number, module, args]
16 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
17 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18 | [-1, 3, C3, [128]],
19 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20 | [-1, 9, C3, [256]],
21 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22 | [-1, 9, C3, [512]],
23 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24 | [-1, 3, C3, [768]],
25 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26 | [-1, 1, SPP, [1024, [3, 5, 7]]],
27 | [-1, 3, C3, [1024, False]], # 11
28 | ]
29 |
30 | # YOLOv5 head
31 | head:
32 | [[-1, 1, Conv, [768, 1, 1]],
33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34 | [[-1, 8], 1, Concat, [1]], # cat backbone P5
35 | [-1, 3, C3, [768, False]], # 15
36 |
37 | [-1, 1, Conv, [512, 1, 1]],
38 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
40 | [-1, 3, C3, [512, False]], # 19
41 |
42 | [-1, 1, Conv, [256, 1, 1]],
43 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
45 | [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46 |
47 | [-1, 1, Conv, [256, 3, 2]],
48 | [[-1, 20], 1, Concat, [1]], # cat head P4
49 | [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50 |
51 | [-1, 1, Conv, [512, 3, 2]],
52 | [[-1, 16], 1, Concat, [1]], # cat head P5
53 | [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54 |
55 | [-1, 1, Conv, [768, 3, 2]],
56 | [[-1, 12], 1, Concat, [1]], # cat head P6
57 | [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58 |
59 | [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60 | ]
61 |
--------------------------------------------------------------------------------
/models/yolo.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | YOLO-specific modules
4 |
5 | Usage:
6 | $ python path/to/models/yolo.py --cfg yolov5s.yaml
7 | """
8 |
9 | import argparse
10 | import sys
11 | from copy import deepcopy
12 | from pathlib import Path
13 |
14 | FILE = Path(__file__).absolute()
15 | sys.path.append(FILE.parents[1].as_posix()) # add yolov5/ to path
16 |
17 | from models.common import *
18 | from models.experimental import *
19 | from utils.autoanchor import check_anchor_order
20 | from utils.general import make_divisible, check_file, set_logging
21 | from utils.plots import feature_visualization
22 | from utils.torch_utils import time_sync, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \
23 | select_device, copy_attr
24 |
25 | try:
26 | import thop # for FLOPs computation
27 | except ImportError:
28 | thop = None
29 |
30 | LOGGER = logging.getLogger(__name__)
31 |
32 |
33 | class Detect(nn.Module):
34 | stride = None # strides computed during build
35 | onnx_dynamic = False # ONNX export parameter
36 |
37 | def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer
38 | super().__init__()
39 | self.nc = nc # number of classes
40 | self.no = nc + 5 # number of outputs per anchor
41 | self.nl = len(anchors) # number of detection layers
42 | self.na = len(anchors[0]) // 2 # number of anchors
43 | self.grid = [torch.zeros(1)] * self.nl # init grid
44 | a = torch.tensor(anchors).float().view(self.nl, -1, 2)
45 | self.register_buffer('anchors', a) # shape(nl,na,2)
46 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
47 | self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
48 | self.inplace = inplace # use in-place ops (e.g. slice assignment)
49 |
50 | def forward(self, x):
51 | z = [] # inference output
52 | for i in range(self.nl):
53 | x[i] = self.m[i](x[i]) # conv
54 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
55 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
56 |
57 | if not self.training: # inference
58 | if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic:
59 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
60 |
61 | y = x[i].sigmoid()
62 | if self.inplace:
63 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
64 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
65 | else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
66 | xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
67 | wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.na, 1, 1, 2) # wh
68 | y = torch.cat((xy, wh, y[..., 4:]), -1)
69 | z.append(y.view(bs, -1, self.no))
70 |
71 | return x if self.training else (torch.cat(z, 1), x)
72 |
73 | @staticmethod
74 | def _make_grid(nx=20, ny=20):
75 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
76 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
77 |
78 |
79 | class Model(nn.Module):
80 | def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes
81 | super().__init__()
82 | if isinstance(cfg, dict):
83 | self.yaml = cfg # model dict
84 | else: # is *.yaml
85 | import yaml # for torch hub
86 | self.yaml_file = Path(cfg).name
87 | with open(cfg) as f:
88 | self.yaml = yaml.safe_load(f) # model dict
89 |
90 | # Define model
91 | ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
92 | if nc and nc != self.yaml['nc']:
93 | LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
94 | self.yaml['nc'] = nc # override yaml value
95 | if anchors:
96 | LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
97 | self.yaml['anchors'] = round(anchors) # override yaml value
98 | self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
99 | self.names = [str(i) for i in range(self.yaml['nc'])] # default names
100 | self.inplace = self.yaml.get('inplace', True)
101 | # LOGGER.info([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
102 |
103 | # Build strides, anchors
104 | m = self.model[-1] # Detect()
105 | if isinstance(m, Detect):
106 | s = 256 # 2x min stride
107 | m.inplace = self.inplace
108 | m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
109 | m.anchors /= m.stride.view(-1, 1, 1)
110 | check_anchor_order(m)
111 | self.stride = m.stride
112 | self._initialize_biases() # only run once
113 | # LOGGER.info('Strides: %s' % m.stride.tolist())
114 |
115 | # Init weights, biases
116 | initialize_weights(self)
117 | self.info()
118 | LOGGER.info('')
119 |
120 | def forward(self, x, augment=False, profile=False, visualize=False):
121 | if augment:
122 | return self.forward_augment(x) # augmented inference, None
123 | return self.forward_once(x, profile, visualize) # single-scale inference, train
124 |
125 | def forward_augment(self, x):
126 | img_size = x.shape[-2:] # height, width
127 | s = [1, 0.83, 0.67] # scales
128 | f = [None, 3, None] # flips (2-ud, 3-lr)
129 | y = [] # outputs
130 | for si, fi in zip(s, f):
131 | xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
132 | yi = self.forward_once(xi)[0] # forward
133 | # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
134 | yi = self._descale_pred(yi, fi, si, img_size)
135 | y.append(yi)
136 | return torch.cat(y, 1), None # augmented inference, train
137 |
138 | def forward_once(self, x, profile=False, visualize=False):
139 | y, dt = [], [] # outputs
140 | for m in self.model:
141 | if m.f != -1: # if not from previous layer
142 | x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
143 |
144 | if profile:
145 | c = isinstance(m, Detect) # copy input as inplace fix
146 | o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
147 | t = time_sync()
148 | for _ in range(10):
149 | m(x.copy() if c else x)
150 | dt.append((time_sync() - t) * 100)
151 | if m == self.model[0]:
152 | LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")
153 | LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
154 |
155 | x = m(x) # run
156 | y.append(x if m.i in self.save else None) # save output
157 |
158 | if visualize:
159 | feature_visualization(x, m.type, m.i, save_dir=visualize)
160 |
161 | if profile:
162 | LOGGER.info('%.1fms total' % sum(dt))
163 | return x
164 |
165 | def _descale_pred(self, p, flips, scale, img_size):
166 | # de-scale predictions following augmented inference (inverse operation)
167 | if self.inplace:
168 | p[..., :4] /= scale # de-scale
169 | if flips == 2:
170 | p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
171 | elif flips == 3:
172 | p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
173 | else:
174 | x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
175 | if flips == 2:
176 | y = img_size[0] - y # de-flip ud
177 | elif flips == 3:
178 | x = img_size[1] - x # de-flip lr
179 | p = torch.cat((x, y, wh, p[..., 4:]), -1)
180 | return p
181 |
182 | def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
183 | # https://arxiv.org/abs/1708.02002 section 3.3
184 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
185 | m = self.model[-1] # Detect() module
186 | for mi, s in zip(m.m, m.stride): # from
187 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
188 | b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
189 | b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
190 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
191 |
192 | def _print_biases(self):
193 | m = self.model[-1] # Detect() module
194 | for mi in m.m: # from
195 | b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
196 | LOGGER.info(
197 | ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
198 |
199 | # def _print_weights(self):
200 | # for m in self.model.modules():
201 | # if type(m) is Bottleneck:
202 | # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
203 |
204 | def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
205 | LOGGER.info('Fusing layers... ')
206 | for m in self.model.modules():
207 | if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
208 | m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
209 | delattr(m, 'bn') # remove batchnorm
210 | m.forward = m.forward_fuse # update forward
211 | self.info()
212 | return self
213 |
214 | def autoshape(self): # add AutoShape module
215 | LOGGER.info('Adding AutoShape... ')
216 | m = AutoShape(self) # wrap model
217 | copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
218 | return m
219 |
220 | def info(self, verbose=False, img_size=640): # print model information
221 | model_info(self, verbose, img_size)
222 |
223 |
224 | def parse_model(d, ch): # model_dict, input_channels(3)
225 | LOGGER.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
226 | anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
227 | na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
228 | no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
229 |
230 | layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
231 | for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
232 | m = eval(m) if isinstance(m, str) else m # eval strings
233 | for j, a in enumerate(args):
234 | try:
235 | args[j] = eval(a) if isinstance(a, str) else a # eval strings
236 | except:
237 | pass
238 |
239 | n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
240 | if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
241 | BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:
242 | c1, c2 = ch[f], args[0]
243 | if c2 != no: # if not output
244 | c2 = make_divisible(c2 * gw, 8)
245 |
246 | args = [c1, c2, *args[1:]]
247 | if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
248 | args.insert(2, n) # number of repeats
249 | n = 1
250 | elif m is nn.BatchNorm2d:
251 | args = [ch[f]]
252 | elif m is Concat:
253 | c2 = sum([ch[x] for x in f])
254 | elif m is Detect:
255 | args.append([ch[x] for x in f])
256 | if isinstance(args[1], int): # number of anchors
257 | args[1] = [list(range(args[1] * 2))] * len(f)
258 | elif m is Contract:
259 | c2 = ch[f] * args[0] ** 2
260 | elif m is Expand:
261 | c2 = ch[f] // args[0] ** 2
262 | else:
263 | c2 = ch[f]
264 |
265 | m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
266 | t = str(m)[8:-2].replace('__main__.', '') # module type
267 | np = sum([x.numel() for x in m_.parameters()]) # number params
268 | m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
269 | LOGGER.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n_, np, t, args)) # print
270 | save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
271 | layers.append(m_)
272 | if i == 0:
273 | ch = []
274 | ch.append(c2)
275 | return nn.Sequential(*layers), sorted(save)
276 |
277 |
278 | if __name__ == '__main__':
279 | parser = argparse.ArgumentParser()
280 | parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
281 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
282 | parser.add_argument('--profile', action='store_true', help='profile model speed')
283 | opt = parser.parse_args()
284 | opt.cfg = check_file(opt.cfg) # check file
285 | set_logging()
286 | device = select_device(opt.device)
287 |
288 | # Create model
289 | model = Model(opt.cfg).to(device)
290 | model.train()
291 |
292 | # Profile
293 | if opt.profile:
294 | img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
295 | y = model(img, profile=True)
296 |
297 | # Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)
298 | # from torch.utils.tensorboard import SummaryWriter
299 | # tb_writer = SummaryWriter('.')
300 | # LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")
301 | # tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph
302 |
--------------------------------------------------------------------------------
/models/yolov5l.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.0 # model depth multiple
6 | width_multiple: 1.0 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/yolov5m.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 0.67 # model depth multiple
6 | width_multiple: 0.75 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/yolov5s.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 0.33 # model depth multiple
6 | width_multiple: 0.50 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/models/yolov5x.yaml:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 |
3 | # Parameters
4 | nc: 80 # number of classes
5 | depth_multiple: 1.33 # model depth multiple
6 | width_multiple: 1.25 # layer channel multiple
7 | anchors:
8 | - [10,13, 16,30, 33,23] # P3/8
9 | - [30,61, 62,45, 59,119] # P4/16
10 | - [116,90, 156,198, 373,326] # P5/32
11 |
12 | # YOLOv5 backbone
13 | backbone:
14 | # [from, number, module, args]
15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2
16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
17 | [-1, 3, C3, [128]],
18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
19 | [-1, 9, C3, [256]],
20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
21 | [-1, 9, C3, [512]],
22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
23 | [-1, 1, SPP, [1024, [5, 9, 13]]],
24 | [-1, 3, C3, [1024, False]], # 9
25 | ]
26 |
27 | # YOLOv5 head
28 | head:
29 | [[-1, 1, Conv, [512, 1, 1]],
30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4
32 | [-1, 3, C3, [512, False]], # 13
33 |
34 | [-1, 1, Conv, [256, 1, 1]],
35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']],
36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3
37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small)
38 |
39 | [-1, 1, Conv, [256, 3, 2]],
40 | [[-1, 14], 1, Concat, [1]], # cat head P4
41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium)
42 |
43 | [-1, 1, Conv, [512, 3, 2]],
44 | [[-1, 10], 1, Concat, [1]], # cat head P5
45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large)
46 |
47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
48 | ]
49 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # pip install -r requirements.txt
2 |
3 | # base ----------------------------------------
4 | matplotlib>=3.2.2
5 | numpy>=1.18.5
6 | opencv-python>=4.1.2
7 | Pillow>=8.0.0
8 | PyYAML>=5.3.1
9 | scipy>=1.4.1
10 | torch>=1.7.0
11 | torchvision>=0.8.1
12 | tqdm>=4.41.0
13 |
14 | # logging -------------------------------------
15 | tensorboard>=2.4.1
16 | # wandb
17 |
18 | # plotting ------------------------------------
19 | seaborn>=0.11.0
20 | pandas
21 |
22 | # export --------------------------------------
23 | # coremltools>=4.1
24 | # onnx>=1.9.0
25 | # scikit-learn==0.19.2 # for coreml quantization
26 | # tensorflow==2.4.1 # for TFLite export
27 |
28 | # extras --------------------------------------
29 | # Cython # for pycocotools https://github.com/cocodataset/cocoapi/issues/172
30 | # pycocotools>=2.0 # COCO mAP
31 | # albumentations>=1.0.3
32 | thop # FLOPs computation
33 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 |
3 | import torch
4 | from PIL import ImageFont
5 |
6 | FILE = Path(__file__).absolute()
7 | ROOT = FILE.parents[1] # yolov5/ dir
8 |
9 | # Check YOLOv5 Annotator font
10 | font = 'Arial.ttf'
11 | try:
12 | ImageFont.truetype(font)
13 | except Exception as e: # download if missing
14 | url = "https://ultralytics.com/assets/" + font
15 | print(f'Downloading {url} to {ROOT / font}...')
16 | torch.hub.download_url_to_file(url, str(ROOT / font))
17 |
--------------------------------------------------------------------------------
/utils/activations.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | Activation functions
4 | """
5 |
6 | import torch
7 | import torch.nn as nn
8 | import torch.nn.functional as F
9 |
10 |
11 | # SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
12 | class SiLU(nn.Module): # export-friendly version of nn.SiLU()
13 | @staticmethod
14 | def forward(x):
15 | return x * torch.sigmoid(x)
16 |
17 |
18 | class Hardswish(nn.Module): # export-friendly version of nn.Hardswish()
19 | @staticmethod
20 | def forward(x):
21 | # return x * F.hardsigmoid(x) # for torchscript and CoreML
22 | return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
23 |
24 |
25 | # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
26 | class Mish(nn.Module):
27 | @staticmethod
28 | def forward(x):
29 | return x * F.softplus(x).tanh()
30 |
31 |
32 | class MemoryEfficientMish(nn.Module):
33 | class F(torch.autograd.Function):
34 | @staticmethod
35 | def forward(ctx, x):
36 | ctx.save_for_backward(x)
37 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
38 |
39 | @staticmethod
40 | def backward(ctx, grad_output):
41 | x = ctx.saved_tensors[0]
42 | sx = torch.sigmoid(x)
43 | fx = F.softplus(x).tanh()
44 | return grad_output * (fx + x * sx * (1 - fx * fx))
45 |
46 | def forward(self, x):
47 | return self.F.apply(x)
48 |
49 |
50 | # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
51 | class FReLU(nn.Module):
52 | def __init__(self, c1, k=3): # ch_in, kernel
53 | super().__init__()
54 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
55 | self.bn = nn.BatchNorm2d(c1)
56 |
57 | def forward(self, x):
58 | return torch.max(x, self.bn(self.conv(x)))
59 |
60 |
61 | # ACON https://arxiv.org/pdf/2009.04759.pdf ----------------------------------------------------------------------------
62 | class AconC(nn.Module):
63 | r""" ACON activation (activate or not).
64 | AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
65 | according to "Activate or Not: Learning Customized Activation" .
66 | """
67 |
68 | def __init__(self, c1):
69 | super().__init__()
70 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
71 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
72 | self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
73 |
74 | def forward(self, x):
75 | dpx = (self.p1 - self.p2) * x
76 | return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
77 |
78 |
79 | class MetaAconC(nn.Module):
80 | r""" ACON activation (activate or not).
81 | MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
82 | according to "Activate or Not: Learning Customized Activation" .
83 | """
84 |
85 | def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
86 | super().__init__()
87 | c2 = max(r, c1 // r)
88 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
89 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
90 | self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
91 | self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
92 | # self.bn1 = nn.BatchNorm2d(c2)
93 | # self.bn2 = nn.BatchNorm2d(c1)
94 |
95 | def forward(self, x):
96 | y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
97 | # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
98 | # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
99 | beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
100 | dpx = (self.p1 - self.p2) * x
101 | return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
102 |
--------------------------------------------------------------------------------
/utils/augmentations.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | Image augmentation functions
4 | """
5 |
6 | import logging
7 | import math
8 | import random
9 |
10 | import cv2
11 | import numpy as np
12 |
13 | from utils.general import colorstr, segment2box, resample_segments, check_version
14 | from utils.metrics import bbox_ioa
15 |
16 |
17 | class Albumentations:
18 | # YOLOv5 Albumentations class (optional, only used if package is installed)
19 | def __init__(self):
20 | self.transform = None
21 | try:
22 | import albumentations as A
23 | check_version(A.__version__, '1.0.3') # version requirement
24 |
25 | self.transform = A.Compose([
26 | A.Blur(p=0.1),
27 | A.MedianBlur(p=0.1),
28 | A.ToGray(p=0.01)],
29 | bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
30 |
31 | logging.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p))
32 | except ImportError: # package not installed, skip
33 | pass
34 | except Exception as e:
35 | logging.info(colorstr('albumentations: ') + f'{e}')
36 |
37 | def __call__(self, im, labels, p=1.0):
38 | if self.transform and random.random() < p:
39 | new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
40 | im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
41 | return im, labels
42 |
43 |
44 | def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
45 | # HSV color-space augmentation
46 | if hgain or sgain or vgain:
47 | r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
48 | hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
49 | dtype = im.dtype # uint8
50 |
51 | x = np.arange(0, 256, dtype=r.dtype)
52 | lut_hue = ((x * r[0]) % 180).astype(dtype)
53 | lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
54 | lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
55 |
56 | im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
57 | cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
58 |
59 |
60 | def hist_equalize(im, clahe=True, bgr=False):
61 | # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255
62 | yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
63 | if clahe:
64 | c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
65 | yuv[:, :, 0] = c.apply(yuv[:, :, 0])
66 | else:
67 | yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
68 | return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
69 |
70 |
71 | def replicate(im, labels):
72 | # Replicate labels
73 | h, w = im.shape[:2]
74 | boxes = labels[:, 1:].astype(int)
75 | x1, y1, x2, y2 = boxes.T
76 | s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
77 | for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
78 | x1b, y1b, x2b, y2b = boxes[i]
79 | bh, bw = y2b - y1b, x2b - x1b
80 | yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
81 | x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
82 | im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]
83 | labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
84 |
85 | return im, labels
86 |
87 |
88 | def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
89 | # Resize and pad image while meeting stride-multiple constraints
90 | shape = im.shape[:2] # current shape [height, width]
91 | if isinstance(new_shape, int):
92 | new_shape = (new_shape, new_shape)
93 |
94 | # Scale ratio (new / old)
95 | r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
96 | if not scaleup: # only scale down, do not scale up (for better val mAP)
97 | r = min(r, 1.0)
98 |
99 | # Compute padding
100 | ratio = r, r # width, height ratios
101 | new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
102 | dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
103 | if auto: # minimum rectangle
104 | dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
105 | elif scaleFill: # stretch
106 | dw, dh = 0.0, 0.0
107 | new_unpad = (new_shape[1], new_shape[0])
108 | ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
109 |
110 | dw /= 2 # divide padding into 2 sides
111 | dh /= 2
112 |
113 | if shape[::-1] != new_unpad: # resize
114 | im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
115 | top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
116 | left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
117 | im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
118 | return im, ratio, (dw, dh)
119 |
120 |
121 | def random_perspective(im, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
122 | border=(0, 0)):
123 | # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
124 | # targets = [cls, xyxy]
125 |
126 | height = im.shape[0] + border[0] * 2 # shape(h,w,c)
127 | width = im.shape[1] + border[1] * 2
128 |
129 | # Center
130 | C = np.eye(3)
131 | C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
132 | C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
133 |
134 | # Perspective
135 | P = np.eye(3)
136 | P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
137 | P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
138 |
139 | # Rotation and Scale
140 | R = np.eye(3)
141 | a = random.uniform(-degrees, degrees)
142 | # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
143 | s = random.uniform(1 - scale, 1 + scale)
144 | # s = 2 ** random.uniform(-scale, scale)
145 | R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
146 |
147 | # Shear
148 | S = np.eye(3)
149 | S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
150 | S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
151 |
152 | # Translation
153 | T = np.eye(3)
154 | T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
155 | T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
156 |
157 | # Combined rotation matrix
158 | M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
159 | if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
160 | if perspective:
161 | im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
162 | else: # affine
163 | im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
164 |
165 | # Visualize
166 | # import matplotlib.pyplot as plt
167 | # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
168 | # ax[0].imshow(im[:, :, ::-1]) # base
169 | # ax[1].imshow(im2[:, :, ::-1]) # warped
170 |
171 | # Transform label coordinates
172 | n = len(targets)
173 | if n:
174 | use_segments = any(x.any() for x in segments)
175 | new = np.zeros((n, 4))
176 | if use_segments: # warp segments
177 | segments = resample_segments(segments) # upsample
178 | for i, segment in enumerate(segments):
179 | xy = np.ones((len(segment), 3))
180 | xy[:, :2] = segment
181 | xy = xy @ M.T # transform
182 | xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
183 |
184 | # clip
185 | new[i] = segment2box(xy, width, height)
186 |
187 | else: # warp boxes
188 | xy = np.ones((n * 4, 3))
189 | xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
190 | xy = xy @ M.T # transform
191 | xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
192 |
193 | # create new boxes
194 | x = xy[:, [0, 2, 4, 6]]
195 | y = xy[:, [1, 3, 5, 7]]
196 | new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
197 |
198 | # clip
199 | new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
200 | new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
201 |
202 | # filter candidates
203 | i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
204 | targets = targets[i]
205 | targets[:, 1:5] = new[i]
206 |
207 | return im, targets
208 |
209 |
210 | def copy_paste(im, labels, segments, p=0.5):
211 | # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
212 | n = len(segments)
213 | if p and n:
214 | h, w, c = im.shape # height, width, channels
215 | im_new = np.zeros(im.shape, np.uint8)
216 | for j in random.sample(range(n), k=round(p * n)):
217 | l, s = labels[j], segments[j]
218 | box = w - l[3], l[2], w - l[1], l[4]
219 | ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
220 | if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
221 | labels = np.concatenate((labels, [[l[0], *box]]), 0)
222 | segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
223 | cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
224 |
225 | result = cv2.bitwise_and(src1=im, src2=im_new)
226 | result = cv2.flip(result, 1) # augment segments (flip left-right)
227 | i = result > 0 # pixels to replace
228 | # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch
229 | im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
230 |
231 | return im, labels, segments
232 |
233 |
234 | def cutout(im, labels, p=0.5):
235 | # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
236 | if random.random() < p:
237 | h, w = im.shape[:2]
238 | scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
239 | for s in scales:
240 | mask_h = random.randint(1, int(h * s)) # create random masks
241 | mask_w = random.randint(1, int(w * s))
242 |
243 | # box
244 | xmin = max(0, random.randint(0, w) - mask_w // 2)
245 | ymin = max(0, random.randint(0, h) - mask_h // 2)
246 | xmax = min(w, xmin + mask_w)
247 | ymax = min(h, ymin + mask_h)
248 |
249 | # apply random color mask
250 | im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
251 |
252 | # return unobscured labels
253 | if len(labels) and s > 0.03:
254 | box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
255 | ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
256 | labels = labels[ioa < 0.60] # remove >60% obscured labels
257 |
258 | return labels
259 |
260 |
261 | def mixup(im, labels, im2, labels2):
262 | # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
263 | r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
264 | im = (im * r + im2 * (1 - r)).astype(np.uint8)
265 | labels = np.concatenate((labels, labels2), 0)
266 | return im, labels
267 |
268 |
269 | def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
270 | # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
271 | w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
272 | w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
273 | ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
274 | return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
275 |
--------------------------------------------------------------------------------
/utils/autoanchor.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | Auto-anchor utils
4 | """
5 |
6 | import random
7 |
8 | import numpy as np
9 | import torch
10 | import yaml
11 | from tqdm import tqdm
12 |
13 | from utils.general import colorstr
14 |
15 |
16 | def check_anchor_order(m):
17 | # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
18 | a = m.anchor_grid.prod(-1).view(-1) # anchor area
19 | da = a[-1] - a[0] # delta a
20 | ds = m.stride[-1] - m.stride[0] # delta s
21 | if da.sign() != ds.sign(): # same order
22 | print('Reversing anchor order')
23 | m.anchors[:] = m.anchors.flip(0)
24 | m.anchor_grid[:] = m.anchor_grid.flip(0)
25 |
26 |
27 | def check_anchors(dataset, model, thr=4.0, imgsz=640):
28 | # Check anchor fit to data, recompute if necessary
29 | prefix = colorstr('autoanchor: ')
30 | print(f'\n{prefix}Analyzing anchors... ', end='')
31 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
32 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
33 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
34 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
35 |
36 | def metric(k): # compute metric
37 | r = wh[:, None] / k[None]
38 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
39 | best = x.max(1)[0] # best_x
40 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
41 | bpr = (best > 1. / thr).float().mean() # best possible recall
42 | return bpr, aat
43 |
44 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
45 | bpr, aat = metric(anchors)
46 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
47 | if bpr < 0.98: # threshold to recompute
48 | print('. Attempting to improve anchors, please wait...')
49 | na = m.anchor_grid.numel() // 2 # number of anchors
50 | try:
51 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
52 | except Exception as e:
53 | print(f'{prefix}ERROR: {e}')
54 | new_bpr = metric(anchors)[0]
55 | if new_bpr > bpr: # replace anchors
56 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
57 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
58 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
59 | check_anchor_order(m)
60 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
61 | else:
62 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
63 | print('') # newline
64 |
65 |
66 | def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
67 | """ Creates kmeans-evolved anchors from training dataset
68 |
69 | Arguments:
70 | dataset: path to data.yaml, or a loaded dataset
71 | n: number of anchors
72 | img_size: image size used for training
73 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
74 | gen: generations to evolve anchors using genetic algorithm
75 | verbose: print all results
76 |
77 | Return:
78 | k: kmeans evolved anchors
79 |
80 | Usage:
81 | from utils.autoanchor import *; _ = kmean_anchors()
82 | """
83 | from scipy.cluster.vq import kmeans
84 |
85 | thr = 1. / thr
86 | prefix = colorstr('autoanchor: ')
87 |
88 | def metric(k, wh): # compute metrics
89 | r = wh[:, None] / k[None]
90 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
91 | # x = wh_iou(wh, torch.tensor(k)) # iou metric
92 | return x, x.max(1)[0] # x, best_x
93 |
94 | def anchor_fitness(k): # mutation fitness
95 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
96 | return (best * (best > thr).float()).mean() # fitness
97 |
98 | def print_results(k):
99 | k = k[np.argsort(k.prod(1))] # sort small to large
100 | x, best = metric(k, wh0)
101 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
102 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
103 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
104 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')
105 | for i, x in enumerate(k):
106 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
107 | return k
108 |
109 | if isinstance(dataset, str): # *.yaml file
110 | with open(dataset, errors='ignore') as f:
111 | data_dict = yaml.safe_load(f) # model dict
112 | from utils.datasets import LoadImagesAndLabels
113 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
114 |
115 | # Get label wh
116 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
117 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
118 |
119 | # Filter
120 | i = (wh0 < 3.0).any(1).sum()
121 | if i:
122 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
123 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
124 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
125 |
126 | # Kmeans calculation
127 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
128 | s = wh.std(0) # sigmas for whitening
129 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
130 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}')
131 | k *= s
132 | wh = torch.tensor(wh, dtype=torch.float32) # filtered
133 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
134 | k = print_results(k)
135 |
136 | # Plot
137 | # k, d = [None] * 20, [None] * 20
138 | # for i in tqdm(range(1, 21)):
139 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
140 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
141 | # ax = ax.ravel()
142 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
143 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
144 | # ax[0].hist(wh[wh[:, 0]<100, 0],400)
145 | # ax[1].hist(wh[wh[:, 1]<100, 1],400)
146 | # fig.savefig('wh.png', dpi=200)
147 |
148 | # Evolve
149 | npr = np.random
150 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
151 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar
152 | for _ in pbar:
153 | v = np.ones(sh)
154 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
155 | v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
156 | kg = (k.copy() * v).clip(min=2.0)
157 | fg = anchor_fitness(kg)
158 | if fg > f:
159 | f, k = fg, kg.copy()
160 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
161 | if verbose:
162 | print_results(k)
163 |
164 | return print_results(k)
165 |
--------------------------------------------------------------------------------
/utils/aws/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/utils/aws/__init__.py
--------------------------------------------------------------------------------
/utils/aws/mime.sh:
--------------------------------------------------------------------------------
1 | # AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/
2 | # This script will run on every instance restart, not only on first start
3 | # --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA ---
4 |
5 | Content-Type: multipart/mixed; boundary="//"
6 | MIME-Version: 1.0
7 |
8 | --//
9 | Content-Type: text/cloud-config; charset="us-ascii"
10 | MIME-Version: 1.0
11 | Content-Transfer-Encoding: 7bit
12 | Content-Disposition: attachment; filename="cloud-config.txt"
13 |
14 | #cloud-config
15 | cloud_final_modules:
16 | - [scripts-user, always]
17 |
18 | --//
19 | Content-Type: text/x-shellscript; charset="us-ascii"
20 | MIME-Version: 1.0
21 | Content-Transfer-Encoding: 7bit
22 | Content-Disposition: attachment; filename="userdata.txt"
23 |
24 | #!/bin/bash
25 | # --- paste contents of userdata.sh here ---
26 | --//
27 |
--------------------------------------------------------------------------------
/utils/aws/resume.py:
--------------------------------------------------------------------------------
1 | # Resume all interrupted trainings in yolov5/ dir including DDP trainings
2 | # Usage: $ python utils/aws/resume.py
3 |
4 | import os
5 | import sys
6 | from pathlib import Path
7 |
8 | import torch
9 | import yaml
10 |
11 | sys.path.append('./') # to run '$ python *.py' files in subdirectories
12 |
13 | port = 0 # --master_port
14 | path = Path('').resolve()
15 | for last in path.rglob('*/**/last.pt'):
16 | ckpt = torch.load(last)
17 | if ckpt['optimizer'] is None:
18 | continue
19 |
20 | # Load opt.yaml
21 | with open(last.parent.parent / 'opt.yaml') as f:
22 | opt = yaml.safe_load(f)
23 |
24 | # Get device count
25 | d = opt['device'].split(',') # devices
26 | nd = len(d) # number of devices
27 | ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel
28 |
29 | if ddp: # multi-GPU
30 | port += 1
31 | cmd = f'python -m torch.distributed.run --nproc_per_node {nd} --master_port {port} train.py --resume {last}'
32 | else: # single-GPU
33 | cmd = f'python train.py --resume {last}'
34 |
35 | cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread
36 | print(cmd)
37 | os.system(cmd)
38 |
--------------------------------------------------------------------------------
/utils/aws/userdata.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
3 | # This script will run only once on first instance start (for a re-start script see mime.sh)
4 | # /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir
5 | # Use >300 GB SSD
6 |
7 | cd home/ubuntu
8 | if [ ! -d yolov5 ]; then
9 | echo "Running first-time script." # install dependencies, download COCO, pull Docker
10 | git clone https://github.com/ultralytics/yolov5 -b master && sudo chmod -R 777 yolov5
11 | cd yolov5
12 | bash data/scripts/get_coco.sh && echo "COCO done." &
13 | sudo docker pull ultralytics/yolov5:latest && echo "Docker done." &
14 | python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." &
15 | wait && echo "All tasks done." # finish background tasks
16 | else
17 | echo "Running re-start script." # resume interrupted runs
18 | i=0
19 | list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour'
20 | while IFS= read -r id; do
21 | ((i++))
22 | echo "restarting container $i: $id"
23 | sudo docker start $id
24 | # sudo docker exec -it $id python train.py --resume # single-GPU
25 | sudo docker exec -d $id python utils/aws/resume.py # multi-scenario
26 | done <<<"$list"
27 | fi
28 |
--------------------------------------------------------------------------------
/utils/callbacks.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | Callback utils
4 | """
5 |
6 |
7 | class Callbacks:
8 | """"
9 | Handles all registered callbacks for YOLOv5 Hooks
10 | """
11 |
12 | _callbacks = {
13 | 'on_pretrain_routine_start': [],
14 | 'on_pretrain_routine_end': [],
15 |
16 | 'on_train_start': [],
17 | 'on_train_epoch_start': [],
18 | 'on_train_batch_start': [],
19 | 'optimizer_step': [],
20 | 'on_before_zero_grad': [],
21 | 'on_train_batch_end': [],
22 | 'on_train_epoch_end': [],
23 |
24 | 'on_val_start': [],
25 | 'on_val_batch_start': [],
26 | 'on_val_image_end': [],
27 | 'on_val_batch_end': [],
28 | 'on_val_end': [],
29 |
30 | 'on_fit_epoch_end': [], # fit = train + val
31 | 'on_model_save': [],
32 | 'on_train_end': [],
33 |
34 | 'teardown': [],
35 | }
36 |
37 | def __init__(self):
38 | return
39 |
40 | def register_action(self, hook, name='', callback=None):
41 | """
42 | Register a new action to a callback hook
43 |
44 | Args:
45 | hook The callback hook name to register the action to
46 | name The name of the action
47 | callback The callback to fire
48 | """
49 | assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
50 | assert callable(callback), f"callback '{callback}' is not callable"
51 | self._callbacks[hook].append({'name': name, 'callback': callback})
52 |
53 | def get_registered_actions(self, hook=None):
54 | """"
55 | Returns all the registered actions by callback hook
56 |
57 | Args:
58 | hook The name of the hook to check, defaults to all
59 | """
60 | if hook:
61 | return self._callbacks[hook]
62 | else:
63 | return self._callbacks
64 |
65 | def run_callbacks(self, hook, *args, **kwargs):
66 | """
67 | Loop through the registered actions and fire all callbacks
68 | """
69 | for logger in self._callbacks[hook]:
70 | # print(f"Running callbacks.{logger['callback'].__name__}()")
71 | logger['callback'](*args, **kwargs)
72 |
73 | def on_pretrain_routine_start(self, *args, **kwargs):
74 | """
75 | Fires all registered callbacks at the start of each pretraining routine
76 | """
77 | self.run_callbacks('on_pretrain_routine_start', *args, **kwargs)
78 |
79 | def on_pretrain_routine_end(self, *args, **kwargs):
80 | """
81 | Fires all registered callbacks at the end of each pretraining routine
82 | """
83 | self.run_callbacks('on_pretrain_routine_end', *args, **kwargs)
84 |
85 | def on_train_start(self, *args, **kwargs):
86 | """
87 | Fires all registered callbacks at the start of each training
88 | """
89 | self.run_callbacks('on_train_start', *args, **kwargs)
90 |
91 | def on_train_epoch_start(self, *args, **kwargs):
92 | """
93 | Fires all registered callbacks at the start of each training epoch
94 | """
95 | self.run_callbacks('on_train_epoch_start', *args, **kwargs)
96 |
97 | def on_train_batch_start(self, *args, **kwargs):
98 | """
99 | Fires all registered callbacks at the start of each training batch
100 | """
101 | self.run_callbacks('on_train_batch_start', *args, **kwargs)
102 |
103 | def optimizer_step(self, *args, **kwargs):
104 | """
105 | Fires all registered callbacks on each optimizer step
106 | """
107 | self.run_callbacks('optimizer_step', *args, **kwargs)
108 |
109 | def on_before_zero_grad(self, *args, **kwargs):
110 | """
111 | Fires all registered callbacks before zero grad
112 | """
113 | self.run_callbacks('on_before_zero_grad', *args, **kwargs)
114 |
115 | def on_train_batch_end(self, *args, **kwargs):
116 | """
117 | Fires all registered callbacks at the end of each training batch
118 | """
119 | self.run_callbacks('on_train_batch_end', *args, **kwargs)
120 |
121 | def on_train_epoch_end(self, *args, **kwargs):
122 | """
123 | Fires all registered callbacks at the end of each training epoch
124 | """
125 | self.run_callbacks('on_train_epoch_end', *args, **kwargs)
126 |
127 | def on_val_start(self, *args, **kwargs):
128 | """
129 | Fires all registered callbacks at the start of the validation
130 | """
131 | self.run_callbacks('on_val_start', *args, **kwargs)
132 |
133 | def on_val_batch_start(self, *args, **kwargs):
134 | """
135 | Fires all registered callbacks at the start of each validation batch
136 | """
137 | self.run_callbacks('on_val_batch_start', *args, **kwargs)
138 |
139 | def on_val_image_end(self, *args, **kwargs):
140 | """
141 | Fires all registered callbacks at the end of each val image
142 | """
143 | self.run_callbacks('on_val_image_end', *args, **kwargs)
144 |
145 | def on_val_batch_end(self, *args, **kwargs):
146 | """
147 | Fires all registered callbacks at the end of each validation batch
148 | """
149 | self.run_callbacks('on_val_batch_end', *args, **kwargs)
150 |
151 | def on_val_end(self, *args, **kwargs):
152 | """
153 | Fires all registered callbacks at the end of the validation
154 | """
155 | self.run_callbacks('on_val_end', *args, **kwargs)
156 |
157 | def on_fit_epoch_end(self, *args, **kwargs):
158 | """
159 | Fires all registered callbacks at the end of each fit (train+val) epoch
160 | """
161 | self.run_callbacks('on_fit_epoch_end', *args, **kwargs)
162 |
163 | def on_model_save(self, *args, **kwargs):
164 | """
165 | Fires all registered callbacks after each model save
166 | """
167 | self.run_callbacks('on_model_save', *args, **kwargs)
168 |
169 | def on_train_end(self, *args, **kwargs):
170 | """
171 | Fires all registered callbacks at the end of training
172 | """
173 | self.run_callbacks('on_train_end', *args, **kwargs)
174 |
175 | def teardown(self, *args, **kwargs):
176 | """
177 | Fires all registered callbacks before teardown
178 | """
179 | self.run_callbacks('teardown', *args, **kwargs)
180 |
--------------------------------------------------------------------------------
/utils/downloads.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | Download utils
4 | """
5 |
6 | import os
7 | import platform
8 | import subprocess
9 | import time
10 | import urllib
11 | from pathlib import Path
12 |
13 | import requests
14 | import torch
15 |
16 |
17 | def gsutil_getsize(url=''):
18 | # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
19 | s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
20 | return eval(s.split(' ')[0]) if len(s) else 0 # bytes
21 |
22 |
23 | def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''):
24 | # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes
25 | file = Path(file)
26 | assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
27 | try: # url1
28 | print(f'Downloading {url} to {file}...')
29 | torch.hub.download_url_to_file(url, str(file))
30 | assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
31 | except Exception as e: # url2
32 | file.unlink(missing_ok=True) # remove partial downloads
33 | print(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...')
34 | os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail
35 | finally:
36 | if not file.exists() or file.stat().st_size < min_bytes: # check
37 | file.unlink(missing_ok=True) # remove partial downloads
38 | print(f"ERROR: {assert_msg}\n{error_msg}")
39 | print('')
40 |
41 |
42 | def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads import *; attempt_download()
43 | # Attempt file download if does not exist
44 | file = Path(str(file).strip().replace("'", ''))
45 |
46 | if not file.exists():
47 | # URL specified
48 | name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
49 | if str(file).startswith(('http:/', 'https:/')): # download
50 | url = str(file).replace(':/', '://') # Pathlib turns :// -> :/
51 | name = name.split('?')[0] # parse authentication https://url.com/file.txt?auth...
52 | safe_download(file=name, url=url, min_bytes=1E5)
53 | return name
54 |
55 | # GitHub assets
56 | file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
57 | try:
58 | response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
59 | assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
60 | tag = response['tag_name'] # i.e. 'v1.0'
61 | except: # fallback plan
62 | assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt',
63 | 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
64 | try:
65 | tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
66 | except:
67 | tag = 'v5.0' # current release
68 |
69 | if name in assets:
70 | safe_download(file,
71 | url=f'https://github.com/{repo}/releases/download/{tag}/{name}',
72 | # url2=f'https://storage.googleapis.com/{repo}/ckpt/{name}', # backup url (optional)
73 | min_bytes=1E5,
74 | error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/')
75 |
76 | return str(file)
77 |
78 |
79 | def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
80 | # Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download()
81 | t = time.time()
82 | file = Path(file)
83 | cookie = Path('cookie') # gdrive cookie
84 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
85 | file.unlink(missing_ok=True) # remove existing file
86 | cookie.unlink(missing_ok=True) # remove existing cookie
87 |
88 | # Attempt file download
89 | out = "NUL" if platform.system() == "Windows" else "/dev/null"
90 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
91 | if os.path.exists('cookie'): # large file
92 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
93 | else: # small file
94 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
95 | r = os.system(s) # execute, capture return
96 | cookie.unlink(missing_ok=True) # remove existing cookie
97 |
98 | # Error check
99 | if r != 0:
100 | file.unlink(missing_ok=True) # remove partial
101 | print('Download error ') # raise Exception('Download error')
102 | return r
103 |
104 | # Unzip if archive
105 | if file.suffix == '.zip':
106 | print('unzipping... ', end='')
107 | os.system(f'unzip -q {file}') # unzip
108 | file.unlink() # remove zip to free space
109 |
110 | print(f'Done ({time.time() - t:.1f}s)')
111 | return r
112 |
113 |
114 | def get_token(cookie="./cookie"):
115 | with open(cookie) as f:
116 | for line in f:
117 | if "download" in line:
118 | return line.split()[-1]
119 | return ""
120 |
121 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries ----------------------------------------------
122 | #
123 | #
124 | # def upload_blob(bucket_name, source_file_name, destination_blob_name):
125 | # # Uploads a file to a bucket
126 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
127 | #
128 | # storage_client = storage.Client()
129 | # bucket = storage_client.get_bucket(bucket_name)
130 | # blob = bucket.blob(destination_blob_name)
131 | #
132 | # blob.upload_from_filename(source_file_name)
133 | #
134 | # print('File {} uploaded to {}.'.format(
135 | # source_file_name,
136 | # destination_blob_name))
137 | #
138 | #
139 | # def download_blob(bucket_name, source_blob_name, destination_file_name):
140 | # # Uploads a blob from a bucket
141 | # storage_client = storage.Client()
142 | # bucket = storage_client.get_bucket(bucket_name)
143 | # blob = bucket.blob(source_blob_name)
144 | #
145 | # blob.download_to_filename(destination_file_name)
146 | #
147 | # print('Blob {} downloaded to {}.'.format(
148 | # source_blob_name,
149 | # destination_file_name))
150 |
--------------------------------------------------------------------------------
/utils/flask_rest_api/README.md:
--------------------------------------------------------------------------------
1 | # Flask REST API
2 |
3 | [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are
4 | commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API
5 | created using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/).
6 |
7 | ## Requirements
8 |
9 | [Flask](https://palletsprojects.com/p/flask/) is required. Install with:
10 |
11 | ```shell
12 | $ pip install Flask
13 | ```
14 |
15 | ## Run
16 |
17 | After Flask installation run:
18 |
19 | ```shell
20 | $ python3 restapi.py --port 5000
21 | ```
22 |
23 | Then use [curl](https://curl.se/) to perform a request:
24 |
25 | ```shell
26 | $ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s'
27 | ```
28 |
29 | The model inference results are returned as a JSON response:
30 |
31 | ```json
32 | [
33 | {
34 | "class": 0,
35 | "confidence": 0.8900438547,
36 | "height": 0.9318675399,
37 | "name": "person",
38 | "width": 0.3264600933,
39 | "xcenter": 0.7438579798,
40 | "ycenter": 0.5207948685
41 | },
42 | {
43 | "class": 0,
44 | "confidence": 0.8440024257,
45 | "height": 0.7155083418,
46 | "name": "person",
47 | "width": 0.6546785235,
48 | "xcenter": 0.427829951,
49 | "ycenter": 0.6334488392
50 | },
51 | {
52 | "class": 27,
53 | "confidence": 0.3771208823,
54 | "height": 0.3902671337,
55 | "name": "tie",
56 | "width": 0.0696444362,
57 | "xcenter": 0.3675483763,
58 | "ycenter": 0.7991207838
59 | },
60 | {
61 | "class": 27,
62 | "confidence": 0.3527112305,
63 | "height": 0.1540903747,
64 | "name": "tie",
65 | "width": 0.0336618312,
66 | "xcenter": 0.7814827561,
67 | "ycenter": 0.5065554976
68 | }
69 | ]
70 | ```
71 |
72 | An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given
73 | in `example_request.py`
74 |
--------------------------------------------------------------------------------
/utils/flask_rest_api/example_request.py:
--------------------------------------------------------------------------------
1 | """Perform test request"""
2 | import pprint
3 |
4 | import requests
5 |
6 | DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s"
7 | TEST_IMAGE = "zidane.jpg"
8 |
9 | image_data = open(TEST_IMAGE, "rb").read()
10 |
11 | response = requests.post(DETECTION_URL, files={"image": image_data}).json()
12 |
13 | pprint.pprint(response)
14 |
--------------------------------------------------------------------------------
/utils/flask_rest_api/restapi.py:
--------------------------------------------------------------------------------
1 | """
2 | Run a rest API exposing the yolov5s object detection model
3 | """
4 | import argparse
5 | import io
6 |
7 | import torch
8 | from PIL import Image
9 | from flask import Flask, request
10 |
11 | app = Flask(__name__)
12 |
13 | DETECTION_URL = "/v1/object-detection/yolov5s"
14 |
15 |
16 | @app.route(DETECTION_URL, methods=["POST"])
17 | def predict():
18 | if not request.method == "POST":
19 | return
20 |
21 | if request.files.get("image"):
22 | image_file = request.files["image"]
23 | image_bytes = image_file.read()
24 |
25 | img = Image.open(io.BytesIO(image_bytes))
26 |
27 | results = model(img, size=640) # reduce size=320 for faster inference
28 | return results.pandas().xyxy[0].to_json(orient="records")
29 |
30 |
31 | if __name__ == "__main__":
32 | parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model")
33 | parser.add_argument("--port", default=5000, type=int, help="port number")
34 | args = parser.parse_args()
35 |
36 | model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache
37 | app.run(host="0.0.0.0", port=args.port) # debug=True causes Restarting with stat
38 |
--------------------------------------------------------------------------------
/utils/google_app_engine/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM gcr.io/google-appengine/python
2 |
3 | # Create a virtualenv for dependencies. This isolates these packages from
4 | # system-level packages.
5 | # Use -p python3 or -p python3.7 to select python version. Default is version 2.
6 | RUN virtualenv /env -p python3
7 |
8 | # Setting these environment variables are the same as running
9 | # source /env/bin/activate.
10 | ENV VIRTUAL_ENV /env
11 | ENV PATH /env/bin:$PATH
12 |
13 | RUN apt-get update && apt-get install -y python-opencv
14 |
15 | # Copy the application's requirements.txt and run pip to install all
16 | # dependencies into the virtualenv.
17 | ADD requirements.txt /app/requirements.txt
18 | RUN pip install -r /app/requirements.txt
19 |
20 | # Add the application source code.
21 | ADD . /app
22 |
23 | # Run a WSGI server to serve the application. gunicorn must be declared as
24 | # a dependency in requirements.txt.
25 | CMD gunicorn -b :$PORT main:app
26 |
--------------------------------------------------------------------------------
/utils/google_app_engine/additional_requirements.txt:
--------------------------------------------------------------------------------
1 | # add these requirements in your app on top of the existing ones
2 | pip==19.2
3 | Flask==1.0.2
4 | gunicorn==19.9.0
5 |
--------------------------------------------------------------------------------
/utils/google_app_engine/app.yaml:
--------------------------------------------------------------------------------
1 | runtime: custom
2 | env: flex
3 |
4 | service: yolov5app
5 |
6 | liveness_check:
7 | initial_delay_sec: 600
8 |
9 | manual_scaling:
10 | instances: 1
11 | resources:
12 | cpu: 1
13 | memory_gb: 4
14 | disk_size_gb: 20
--------------------------------------------------------------------------------
/utils/loggers/__init__.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | Logging utils
4 | """
5 |
6 | import warnings
7 | from threading import Thread
8 |
9 | import torch
10 | from torch.utils.tensorboard import SummaryWriter
11 |
12 | from utils.general import colorstr, emojis
13 | from utils.loggers.wandb.wandb_utils import WandbLogger
14 | from utils.plots import plot_images, plot_results
15 | from utils.torch_utils import de_parallel
16 |
17 | LOGGERS = ('csv', 'tb', 'wandb') # text-file, TensorBoard, Weights & Biases
18 |
19 | try:
20 | import wandb
21 |
22 | assert hasattr(wandb, '__version__') # verify package import not local dir
23 | except (ImportError, AssertionError):
24 | wandb = None
25 |
26 |
27 | class Loggers():
28 | # YOLOv5 Loggers class
29 | def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS):
30 | self.save_dir = save_dir
31 | self.weights = weights
32 | self.opt = opt
33 | self.hyp = hyp
34 | self.logger = logger # for printing results to console
35 | self.include = include
36 | self.keys = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss
37 | 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', # metrics
38 | 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss
39 | 'x/lr0', 'x/lr1', 'x/lr2'] # params
40 | for k in LOGGERS:
41 | setattr(self, k, None) # init empty logger dictionary
42 | self.csv = True # always log to csv
43 |
44 | # Message
45 | if not wandb:
46 | prefix = colorstr('Weights & Biases: ')
47 | s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)"
48 | print(emojis(s))
49 |
50 | # TensorBoard
51 | s = self.save_dir
52 | if 'tb' in self.include and not self.opt.evolve:
53 | prefix = colorstr('TensorBoard: ')
54 | self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/")
55 | self.tb = SummaryWriter(str(s))
56 |
57 | # W&B
58 | if wandb and 'wandb' in self.include:
59 | wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://')
60 | run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None
61 | self.opt.hyp = self.hyp # add hyperparameters
62 | self.wandb = WandbLogger(self.opt, run_id)
63 | else:
64 | self.wandb = None
65 |
66 | def on_pretrain_routine_end(self):
67 | # Callback runs on pre-train routine end
68 | paths = self.save_dir.glob('*labels*.jpg') # training labels
69 | if self.wandb:
70 | self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]})
71 |
72 | def on_train_batch_end(self, ni, model, imgs, targets, paths, plots, sync_bn):
73 | # Callback runs on train batch end
74 | if plots:
75 | if ni == 0:
76 | if not sync_bn: # tb.add_graph() --sync known issue https://github.com/ultralytics/yolov5/issues/3754
77 | with warnings.catch_warnings():
78 | warnings.simplefilter('ignore') # suppress jit trace warning
79 | self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), [])
80 | if ni < 3:
81 | f = self.save_dir / f'train_batch{ni}.jpg' # filename
82 | Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()
83 | if self.wandb and ni == 10:
84 | files = sorted(self.save_dir.glob('train*.jpg'))
85 | self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]})
86 |
87 | def on_train_epoch_end(self, epoch):
88 | # Callback runs on train epoch end
89 | if self.wandb:
90 | self.wandb.current_epoch = epoch + 1
91 |
92 | def on_val_image_end(self, pred, predn, path, names, im):
93 | # Callback runs on val image end
94 | if self.wandb:
95 | self.wandb.val_one_image(pred, predn, path, names, im)
96 |
97 | def on_val_end(self):
98 | # Callback runs on val end
99 | if self.wandb:
100 | files = sorted(self.save_dir.glob('val*.jpg'))
101 | self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]})
102 |
103 | def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):
104 | # Callback runs at the end of each fit (train+val) epoch
105 | x = {k: v for k, v in zip(self.keys, vals)} # dict
106 | if self.csv:
107 | file = self.save_dir / 'results.csv'
108 | n = len(x) + 1 # number of cols
109 | s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header
110 | with open(file, 'a') as f:
111 | f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n')
112 |
113 | if self.tb:
114 | for k, v in x.items():
115 | self.tb.add_scalar(k, v, epoch)
116 |
117 | if self.wandb:
118 | self.wandb.log(x)
119 | self.wandb.end_epoch(best_result=best_fitness == fi)
120 |
121 | def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
122 | # Callback runs on model save event
123 | if self.wandb:
124 | if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1:
125 | self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)
126 |
127 | def on_train_end(self, last, best, plots, epoch):
128 | # Callback runs on training end
129 | if plots:
130 | plot_results(file=self.save_dir / 'results.csv') # save results.png
131 | files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]]
132 | files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter
133 |
134 | if self.tb:
135 | import cv2
136 | for f in files:
137 | self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')
138 |
139 | if self.wandb:
140 | self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]})
141 | # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model
142 | if not self.opt.evolve:
143 | wandb.log_artifact(str(best if best.exists() else last), type='model',
144 | name='run_' + self.wandb.wandb_run.id + '_model',
145 | aliases=['latest', 'best', 'stripped'])
146 | self.wandb.finish_run()
147 | else:
148 | self.wandb.finish_run()
149 | self.wandb = WandbLogger(self.opt)
150 |
--------------------------------------------------------------------------------
/utils/loggers/wandb/README.md:
--------------------------------------------------------------------------------
1 | 📚 This guide explains how to use **Weights & Biases** (W&B) with YOLOv5 🚀.
2 | * [About Weights & Biases](#about-weights-&-biases)
3 | * [First-Time Setup](#first-time-setup)
4 | * [Viewing runs](#viewing-runs)
5 | * [Advanced Usage: Dataset Versioning and Evaluation](#advanced-usage)
6 | * [Reports: Share your work with the world!](#reports)
7 |
8 | ## About Weights & Biases
9 | Think of [W&B](https://wandb.ai/site?utm_campaign=repo_yolo_wandbtutorial) like GitHub for machine learning models. With a few lines of code, save everything you need to debug, compare and reproduce your models — architecture, hyperparameters, git commits, model weights, GPU usage, and even datasets and predictions.
10 |
11 | Used by top researchers including teams at OpenAI, Lyft, Github, and MILA, W&B is part of the new standard of best practices for machine learning. How W&B can help you optimize your machine learning workflows:
12 |
13 | * [Debug](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Free-2) model performance in real time
14 | * [GPU usage](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#System-4), visualized automatically
15 | * [Custom charts](https://wandb.ai/wandb/customizable-charts/reports/Powerful-Custom-Charts-To-Debug-Model-Peformance--VmlldzoyNzY4ODI) for powerful, extensible visualization
16 | * [Share insights](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Share-8) interactively with collaborators
17 | * [Optimize hyperparameters](https://docs.wandb.com/sweeps) efficiently
18 | * [Track](https://docs.wandb.com/artifacts) datasets, pipelines, and production models
19 |
20 | ## First-Time Setup
21 |
22 | Toggle Details
23 | When you first train, W&B will prompt you to create a new account and will generate an **API key** for you. If you are an existing user you can retrieve your key from https://wandb.ai/authorize. This key is used to tell W&B where to log your data. You only need to supply your key once, and then it is remembered on the same device.
24 |
25 | W&B will create a cloud **project** (default is 'YOLOv5') for your training runs, and each new training run will be provided a unique run **name** within that project as project/name. You can also manually set your project and run name as:
26 |
27 | ```shell
28 | $ python train.py --project ... --name ...
29 | ```
30 |
31 |
32 |
33 |
34 | ## Viewing Runs
35 |
36 | Toggle Details
37 | Run information streams from your environment to the W&B cloud console as you train. This allows you to monitor and even cancel runs in realtime . All important information is logged:
38 |
39 | * Training & Validation losses
40 | * Metrics: Precision, Recall, mAP@0.5, mAP@0.5:0.95
41 | * Learning Rate over time
42 | * A bounding box debugging panel, showing the training progress over time
43 | * GPU: Type, **GPU Utilization**, power, temperature, **CUDA memory usage**
44 | * System: Disk I/0, CPU utilization, RAM memory usage
45 | * Your trained model as W&B Artifact
46 | * Environment: OS and Python types, Git repository and state, **training command**
47 |
48 |
49 |
50 |
51 | ## Advanced Usage
52 | You can leverage W&B artifacts and Tables integration to easily visualize and manage your datasets, models and training evaluations. Here are some quick examples to get you started.
53 |
54 | 1. Visualize and Version Datasets
55 | Log, visualize, dynamically query, and understand your data with W&B Tables. You can use the following command to log your dataset as a W&B Table. This will generate a {dataset}_wandb.yaml
file which can be used to train from dataset artifact.
56 |
57 | Usage
58 | Code $ python utils/logger/wandb/log_dataset.py --project ... --name ... --data ..
59 |
60 | 
61 |
62 |
63 | 2: Train and Log Evaluation simultaneousy
64 | This is an extension of the previous section, but it'll also training after uploading the dataset. This also evaluation Table
65 | Evaluation table compares your predictions and ground truths across the validation set for each epoch. It uses the references to the already uploaded datasets,
66 | so no images will be uploaded from your system more than once.
67 |
68 | Usage
69 | Code $ python utils/logger/wandb/log_dataset.py --data .. --upload_data
70 |
71 | 
72 |
73 |
74 | 3: Train using dataset artifact
75 | When you upload a dataset as described in the first section, you get a new config file with an added `_wandb` to its name. This file contains the information that
76 | can be used to train a model directly from the dataset artifact. This also logs evaluation
77 |
78 | Usage
79 | Code $ python utils/logger/wandb/log_dataset.py --data {data}_wandb.yaml
80 |
81 | 
82 |
83 |
84 | 4: Save model checkpoints as artifacts
85 | To enable saving and versioning checkpoints of your experiment, pass `--save_period n` with the base cammand, where `n` represents checkpoint interval.
86 | You can also log both the dataset and model checkpoints simultaneously. If not passed, only the final model will be logged
87 |
88 |
89 | Usage
90 | Code $ python train.py --save_period 1
91 |
92 | 
93 |
94 |
95 |
96 |
97 | 5: Resume runs from checkpoint artifacts.
98 | Any run can be resumed using artifacts if the --resume
argument starts with wandb-artifact://
prefix followed by the run path, i.e, wandb-artifact://username/project/runid
. This doesn't require the model checkpoint to be present on the local system.
99 |
100 |
101 | Usage
102 | Code $ python train.py --resume wandb-artifact://{run_path}
103 |
104 | 
105 |
106 |
107 | 6: Resume runs from dataset artifact & checkpoint artifacts.
108 | Local dataset or model checkpoints are not required. This can be used to resume runs directly on a different device
109 | The syntax is same as the previous section, but you'll need to lof both the dataset and model checkpoints as artifacts, i.e, set bot --upload_dataset
or
110 | train from _wandb.yaml
file and set --save_period
111 |
112 |
113 | Usage
114 | Code $ python train.py --resume wandb-artifact://{run_path}
115 |
116 | 
117 |
118 |
119 |
120 |
121 |
122 |
123 | Reports
124 | W&B Reports can be created from your saved runs for sharing online. Once a report is created you will receive a link you can use to publically share your results. Here is an example report created from the COCO128 tutorial trainings of all four YOLOv5 models ([link](https://wandb.ai/glenn-jocher/yolov5_tutorial/reports/YOLOv5-COCO128-Tutorial-Results--VmlldzozMDI5OTY)).
125 |
126 |
127 |
128 | ## Environments
129 | YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):
130 |
131 | * **Google Colab and Kaggle** notebooks with free GPU: [](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb) [](https://www.kaggle.com/ultralytics/yolov5)
132 | * **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart)
133 | * **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart)
134 | * **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) [](https://hub.docker.com/r/ultralytics/yolov5)
135 |
136 | ## Status
137 | 
138 |
139 | If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), validation ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on MacOS, Windows, and Ubuntu every 24 hours and on every commit.
140 |
141 |
--------------------------------------------------------------------------------
/utils/loggers/wandb/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RichardoMrMu/yolov5-helmet-detection-python/6a4083f0eefe502fe6ce9dd679beebe0b7569d41/utils/loggers/wandb/__init__.py
--------------------------------------------------------------------------------
/utils/loggers/wandb/log_dataset.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 | from wandb_utils import WandbLogger
4 |
5 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
6 |
7 |
8 | def create_dataset_artifact(opt):
9 | logger = WandbLogger(opt, None, job_type='Dataset Creation') # TODO: return value unused
10 |
11 |
12 | if __name__ == '__main__':
13 | parser = argparse.ArgumentParser()
14 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
15 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
16 | parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project')
17 | parser.add_argument('--entity', default=None, help='W&B entity')
18 | parser.add_argument('--name', type=str, default='log dataset', help='name of W&B run')
19 |
20 | opt = parser.parse_args()
21 | opt.resume = False # Explicitly disallow resume check for dataset upload job
22 |
23 | create_dataset_artifact(opt)
24 |
--------------------------------------------------------------------------------
/utils/loggers/wandb/sweep.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from pathlib import Path
3 |
4 | import wandb
5 |
6 | FILE = Path(__file__).absolute()
7 | sys.path.append(FILE.parents[3].as_posix()) # add utils/ to path
8 |
9 | from train import train, parse_opt
10 | from utils.general import increment_path
11 | from utils.torch_utils import select_device
12 |
13 |
14 | def sweep():
15 | wandb.init()
16 | # Get hyp dict from sweep agent
17 | hyp_dict = vars(wandb.config).get("_items")
18 |
19 | # Workaround: get necessary opt args
20 | opt = parse_opt(known=True)
21 | opt.batch_size = hyp_dict.get("batch_size")
22 | opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve))
23 | opt.epochs = hyp_dict.get("epochs")
24 | opt.nosave = True
25 | opt.data = hyp_dict.get("data")
26 | device = select_device(opt.device, batch_size=opt.batch_size)
27 |
28 | # train
29 | train(hyp_dict, opt, device)
30 |
31 |
32 | if __name__ == "__main__":
33 | sweep()
34 |
--------------------------------------------------------------------------------
/utils/loggers/wandb/sweep.yaml:
--------------------------------------------------------------------------------
1 | # Hyperparameters for training
2 | # To set range-
3 | # Provide min and max values as:
4 | # parameter:
5 | #
6 | # min: scalar
7 | # max: scalar
8 | # OR
9 | #
10 | # Set a specific list of search space-
11 | # parameter:
12 | # values: [scalar1, scalar2, scalar3...]
13 | #
14 | # You can use grid, bayesian and hyperopt search strategy
15 | # For more info on configuring sweeps visit - https://docs.wandb.ai/guides/sweeps/configuration
16 |
17 | program: utils/loggers/wandb/sweep.py
18 | method: random
19 | metric:
20 | name: metrics/mAP_0.5
21 | goal: maximize
22 |
23 | parameters:
24 | # hyperparameters: set either min, max range or values list
25 | data:
26 | value: "data/coco128.yaml"
27 | batch_size:
28 | values: [64]
29 | epochs:
30 | values: [10]
31 |
32 | lr0:
33 | distribution: uniform
34 | min: 1e-5
35 | max: 1e-1
36 | lrf:
37 | distribution: uniform
38 | min: 0.01
39 | max: 1.0
40 | momentum:
41 | distribution: uniform
42 | min: 0.6
43 | max: 0.98
44 | weight_decay:
45 | distribution: uniform
46 | min: 0.0
47 | max: 0.001
48 | warmup_epochs:
49 | distribution: uniform
50 | min: 0.0
51 | max: 5.0
52 | warmup_momentum:
53 | distribution: uniform
54 | min: 0.0
55 | max: 0.95
56 | warmup_bias_lr:
57 | distribution: uniform
58 | min: 0.0
59 | max: 0.2
60 | box:
61 | distribution: uniform
62 | min: 0.02
63 | max: 0.2
64 | cls:
65 | distribution: uniform
66 | min: 0.2
67 | max: 4.0
68 | cls_pw:
69 | distribution: uniform
70 | min: 0.5
71 | max: 2.0
72 | obj:
73 | distribution: uniform
74 | min: 0.2
75 | max: 4.0
76 | obj_pw:
77 | distribution: uniform
78 | min: 0.5
79 | max: 2.0
80 | iou_t:
81 | distribution: uniform
82 | min: 0.1
83 | max: 0.7
84 | anchor_t:
85 | distribution: uniform
86 | min: 2.0
87 | max: 8.0
88 | fl_gamma:
89 | distribution: uniform
90 | min: 0.0
91 | max: 0.1
92 | hsv_h:
93 | distribution: uniform
94 | min: 0.0
95 | max: 0.1
96 | hsv_s:
97 | distribution: uniform
98 | min: 0.0
99 | max: 0.9
100 | hsv_v:
101 | distribution: uniform
102 | min: 0.0
103 | max: 0.9
104 | degrees:
105 | distribution: uniform
106 | min: 0.0
107 | max: 45.0
108 | translate:
109 | distribution: uniform
110 | min: 0.0
111 | max: 0.9
112 | scale:
113 | distribution: uniform
114 | min: 0.0
115 | max: 0.9
116 | shear:
117 | distribution: uniform
118 | min: 0.0
119 | max: 10.0
120 | perspective:
121 | distribution: uniform
122 | min: 0.0
123 | max: 0.001
124 | flipud:
125 | distribution: uniform
126 | min: 0.0
127 | max: 1.0
128 | fliplr:
129 | distribution: uniform
130 | min: 0.0
131 | max: 1.0
132 | mosaic:
133 | distribution: uniform
134 | min: 0.0
135 | max: 1.0
136 | mixup:
137 | distribution: uniform
138 | min: 0.0
139 | max: 1.0
140 | copy_paste:
141 | distribution: uniform
142 | min: 0.0
143 | max: 1.0
144 |
--------------------------------------------------------------------------------
/utils/loss.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | Loss functions
4 | """
5 |
6 | import torch
7 | import torch.nn as nn
8 |
9 | from utils.metrics import bbox_iou
10 | from utils.torch_utils import is_parallel
11 |
12 |
13 | def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
14 | # return positive, negative label smoothing BCE targets
15 | return 1.0 - 0.5 * eps, 0.5 * eps
16 |
17 |
18 | class BCEBlurWithLogitsLoss(nn.Module):
19 | # BCEwithLogitLoss() with reduced missing label effects.
20 | def __init__(self, alpha=0.05):
21 | super(BCEBlurWithLogitsLoss, self).__init__()
22 | self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
23 | self.alpha = alpha
24 |
25 | def forward(self, pred, true):
26 | loss = self.loss_fcn(pred, true)
27 | pred = torch.sigmoid(pred) # prob from logits
28 | dx = pred - true # reduce only missing label effects
29 | # dx = (pred - true).abs() # reduce missing label and false label effects
30 | alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
31 | loss *= alpha_factor
32 | return loss.mean()
33 |
34 |
35 | class FocalLoss(nn.Module):
36 | # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
37 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
38 | super(FocalLoss, self).__init__()
39 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
40 | self.gamma = gamma
41 | self.alpha = alpha
42 | self.reduction = loss_fcn.reduction
43 | self.loss_fcn.reduction = 'none' # required to apply FL to each element
44 |
45 | def forward(self, pred, true):
46 | loss = self.loss_fcn(pred, true)
47 | # p_t = torch.exp(-loss)
48 | # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
49 |
50 | # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
51 | pred_prob = torch.sigmoid(pred) # prob from logits
52 | p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
53 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
54 | modulating_factor = (1.0 - p_t) ** self.gamma
55 | loss *= alpha_factor * modulating_factor
56 |
57 | if self.reduction == 'mean':
58 | return loss.mean()
59 | elif self.reduction == 'sum':
60 | return loss.sum()
61 | else: # 'none'
62 | return loss
63 |
64 |
65 | class QFocalLoss(nn.Module):
66 | # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
67 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
68 | super(QFocalLoss, self).__init__()
69 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
70 | self.gamma = gamma
71 | self.alpha = alpha
72 | self.reduction = loss_fcn.reduction
73 | self.loss_fcn.reduction = 'none' # required to apply FL to each element
74 |
75 | def forward(self, pred, true):
76 | loss = self.loss_fcn(pred, true)
77 |
78 | pred_prob = torch.sigmoid(pred) # prob from logits
79 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
80 | modulating_factor = torch.abs(true - pred_prob) ** self.gamma
81 | loss *= alpha_factor * modulating_factor
82 |
83 | if self.reduction == 'mean':
84 | return loss.mean()
85 | elif self.reduction == 'sum':
86 | return loss.sum()
87 | else: # 'none'
88 | return loss
89 |
90 |
91 | class ComputeLoss:
92 | # Compute losses
93 | def __init__(self, model, autobalance=False):
94 | super(ComputeLoss, self).__init__()
95 | self.sort_obj_iou = False
96 | device = next(model.parameters()).device # get model device
97 | h = model.hyp # hyperparameters
98 |
99 | # Define criteria
100 | BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
101 | BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
102 |
103 | # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
104 | self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
105 |
106 | # Focal loss
107 | g = h['fl_gamma'] # focal loss gamma
108 | if g > 0:
109 | BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
110 |
111 | det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
112 | self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
113 | self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
114 | self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
115 | for k in 'na', 'nc', 'nl', 'anchors':
116 | setattr(self, k, getattr(det, k))
117 |
118 | def __call__(self, p, targets): # predictions, targets, model
119 | device = targets.device
120 | lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
121 | tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
122 |
123 | # Losses
124 | for i, pi in enumerate(p): # layer index, layer predictions
125 | b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
126 | tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
127 |
128 | n = b.shape[0] # number of targets
129 | if n:
130 | ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
131 |
132 | # Regression
133 | pxy = ps[:, :2].sigmoid() * 2. - 0.5
134 | pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
135 | pbox = torch.cat((pxy, pwh), 1) # predicted box
136 | iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
137 | lbox += (1.0 - iou).mean() # iou loss
138 |
139 | # Objectness
140 | score_iou = iou.detach().clamp(0).type(tobj.dtype)
141 | if self.sort_obj_iou:
142 | sort_id = torch.argsort(score_iou)
143 | b, a, gj, gi, score_iou = b[sort_id], a[sort_id], gj[sort_id], gi[sort_id], score_iou[sort_id]
144 | tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * score_iou # iou ratio
145 |
146 | # Classification
147 | if self.nc > 1: # cls loss (only if multiple classes)
148 | t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
149 | t[range(n), tcls[i]] = self.cp
150 | lcls += self.BCEcls(ps[:, 5:], t) # BCE
151 |
152 | # Append targets to text file
153 | # with open('targets.txt', 'a') as file:
154 | # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
155 |
156 | obji = self.BCEobj(pi[..., 4], tobj)
157 | lobj += obji * self.balance[i] # obj loss
158 | if self.autobalance:
159 | self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
160 |
161 | if self.autobalance:
162 | self.balance = [x / self.balance[self.ssi] for x in self.balance]
163 | lbox *= self.hyp['box']
164 | lobj *= self.hyp['obj']
165 | lcls *= self.hyp['cls']
166 | bs = tobj.shape[0] # batch size
167 |
168 | return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
169 |
170 | def build_targets(self, p, targets):
171 | # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
172 | na, nt = self.na, targets.shape[0] # number of anchors, targets
173 | tcls, tbox, indices, anch = [], [], [], []
174 | gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
175 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
176 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
177 |
178 | g = 0.5 # bias
179 | off = torch.tensor([[0, 0],
180 | [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
181 | # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
182 | ], device=targets.device).float() * g # offsets
183 |
184 | for i in range(self.nl):
185 | anchors = self.anchors[i]
186 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
187 |
188 | # Match targets to anchors
189 | t = targets * gain
190 | if nt:
191 | # Matches
192 | r = t[:, :, 4:6] / anchors[:, None] # wh ratio
193 | j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
194 | # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
195 | t = t[j] # filter
196 |
197 | # Offsets
198 | gxy = t[:, 2:4] # grid xy
199 | gxi = gain[[2, 3]] - gxy # inverse
200 | j, k = ((gxy % 1. < g) & (gxy > 1.)).T
201 | l, m = ((gxi % 1. < g) & (gxi > 1.)).T
202 | j = torch.stack((torch.ones_like(j), j, k, l, m))
203 | t = t.repeat((5, 1, 1))[j]
204 | offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
205 | else:
206 | t = targets[0]
207 | offsets = 0
208 |
209 | # Define
210 | b, c = t[:, :2].long().T # image, class
211 | gxy = t[:, 2:4] # grid xy
212 | gwh = t[:, 4:6] # grid wh
213 | gij = (gxy - offsets).long()
214 | gi, gj = gij.T # grid xy indices
215 |
216 | # Append
217 | a = t[:, 6].long() # anchor indices
218 | indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
219 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
220 | anch.append(anchors[a]) # anchors
221 | tcls.append(c) # class
222 |
223 | return tcls, tbox, indices, anch
224 |
--------------------------------------------------------------------------------
/utils/metrics.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2 | """
3 | Model validation metrics
4 | """
5 |
6 | import math
7 | import warnings
8 | from pathlib import Path
9 |
10 | import matplotlib.pyplot as plt
11 | import numpy as np
12 | import torch
13 |
14 |
15 | def fitness(x):
16 | # Model fitness as a weighted combination of metrics
17 | w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
18 | return (x[:, :4] * w).sum(1)
19 |
20 |
21 | def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()):
22 | """ Compute the average precision, given the recall and precision curves.
23 | Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
24 | # Arguments
25 | tp: True positives (nparray, nx1 or nx10).
26 | conf: Objectness value from 0-1 (nparray).
27 | pred_cls: Predicted object classes (nparray).
28 | target_cls: True object classes (nparray).
29 | plot: Plot precision-recall curve at mAP@0.5
30 | save_dir: Plot save directory
31 | # Returns
32 | The average precision as computed in py-faster-rcnn.
33 | """
34 |
35 | # Sort by objectness
36 | i = np.argsort(-conf)
37 | tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
38 |
39 | # Find unique classes
40 | unique_classes = np.unique(target_cls)
41 | nc = unique_classes.shape[0] # number of classes, number of detections
42 |
43 | # Create Precision-Recall curve and compute AP for each class
44 | px, py = np.linspace(0, 1, 1000), [] # for plotting
45 | ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
46 | for ci, c in enumerate(unique_classes):
47 | i = pred_cls == c
48 | n_l = (target_cls == c).sum() # number of labels
49 | n_p = i.sum() # number of predictions
50 |
51 | if n_p == 0 or n_l == 0:
52 | continue
53 | else:
54 | # Accumulate FPs and TPs
55 | fpc = (1 - tp[i]).cumsum(0)
56 | tpc = tp[i].cumsum(0)
57 |
58 | # Recall
59 | recall = tpc / (n_l + 1e-16) # recall curve
60 | r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
61 |
62 | # Precision
63 | precision = tpc / (tpc + fpc) # precision curve
64 | p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
65 |
66 | # AP from recall-precision curve
67 | for j in range(tp.shape[1]):
68 | ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
69 | if plot and j == 0:
70 | py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
71 |
72 | # Compute F1 (harmonic mean of precision and recall)
73 | f1 = 2 * p * r / (p + r + 1e-16)
74 | if plot:
75 | plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
76 | plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
77 | plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
78 | plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
79 |
80 | i = f1.mean(0).argmax() # max F1 index
81 | return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32')
82 |
83 |
84 | def compute_ap(recall, precision):
85 | """ Compute the average precision, given the recall and precision curves
86 | # Arguments
87 | recall: The recall curve (list)
88 | precision: The precision curve (list)
89 | # Returns
90 | Average precision, precision curve, recall curve
91 | """
92 |
93 | # Append sentinel values to beginning and end
94 | mrec = np.concatenate(([0.0], recall, [1.0]))
95 | mpre = np.concatenate(([1.0], precision, [0.0]))
96 |
97 | # Compute the precision envelope
98 | mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
99 |
100 | # Integrate area under curve
101 | method = 'interp' # methods: 'continuous', 'interp'
102 | if method == 'interp':
103 | x = np.linspace(0, 1, 101) # 101-point interp (COCO)
104 | ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
105 | else: # 'continuous'
106 | i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
107 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
108 |
109 | return ap, mpre, mrec
110 |
111 |
112 | class ConfusionMatrix:
113 | # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
114 | def __init__(self, nc, conf=0.25, iou_thres=0.45):
115 | self.matrix = np.zeros((nc + 1, nc + 1))
116 | self.nc = nc # number of classes
117 | self.conf = conf
118 | self.iou_thres = iou_thres
119 |
120 | def process_batch(self, detections, labels):
121 | """
122 | Return intersection-over-union (Jaccard index) of boxes.
123 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
124 | Arguments:
125 | detections (Array[N, 6]), x1, y1, x2, y2, conf, class
126 | labels (Array[M, 5]), class, x1, y1, x2, y2
127 | Returns:
128 | None, updates confusion matrix accordingly
129 | """
130 | detections = detections[detections[:, 4] > self.conf]
131 | gt_classes = labels[:, 0].int()
132 | detection_classes = detections[:, 5].int()
133 | iou = box_iou(labels[:, 1:], detections[:, :4])
134 |
135 | x = torch.where(iou > self.iou_thres)
136 | if x[0].shape[0]:
137 | matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
138 | if x[0].shape[0] > 1:
139 | matches = matches[matches[:, 2].argsort()[::-1]]
140 | matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
141 | matches = matches[matches[:, 2].argsort()[::-1]]
142 | matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
143 | else:
144 | matches = np.zeros((0, 3))
145 |
146 | n = matches.shape[0] > 0
147 | m0, m1, _ = matches.transpose().astype(np.int16)
148 | for i, gc in enumerate(gt_classes):
149 | j = m0 == i
150 | if n and sum(j) == 1:
151 | self.matrix[detection_classes[m1[j]], gc] += 1 # correct
152 | else:
153 | self.matrix[self.nc, gc] += 1 # background FP
154 |
155 | if n:
156 | for i, dc in enumerate(detection_classes):
157 | if not any(m1 == i):
158 | self.matrix[dc, self.nc] += 1 # background FN
159 |
160 | def matrix(self):
161 | return self.matrix
162 |
163 | def plot(self, normalize=True, save_dir='', names=()):
164 | try:
165 | import seaborn as sn
166 |
167 | array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-6) if normalize else 1) # normalize columns
168 | array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
169 |
170 | fig = plt.figure(figsize=(12, 9), tight_layout=True)
171 | sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
172 | labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
173 | with warnings.catch_warnings():
174 | warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered
175 | sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
176 | xticklabels=names + ['background FP'] if labels else "auto",
177 | yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
178 | fig.axes[0].set_xlabel('True')
179 | fig.axes[0].set_ylabel('Predicted')
180 | fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
181 | plt.close()
182 | except Exception as e:
183 | print(f'WARNING: ConfusionMatrix plot failure: {e}')
184 |
185 | def print(self):
186 | for i in range(self.nc + 1):
187 | print(' '.join(map(str, self.matrix[i])))
188 |
189 |
190 | def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
191 | # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
192 | box2 = box2.T
193 |
194 | # Get the coordinates of bounding boxes
195 | if x1y1x2y2: # x1, y1, x2, y2 = box1
196 | b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
197 | b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
198 | else: # transform from xywh to xyxy
199 | b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
200 | b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
201 | b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
202 | b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
203 |
204 | # Intersection area
205 | inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
206 | (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
207 |
208 | # Union Area
209 | w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
210 | w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
211 | union = w1 * h1 + w2 * h2 - inter + eps
212 |
213 | iou = inter / union
214 | if GIoU or DIoU or CIoU:
215 | cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
216 | ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
217 | if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
218 | c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
219 | rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +
220 | (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared
221 | if DIoU:
222 | return iou - rho2 / c2 # DIoU
223 | elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
224 | v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
225 | with torch.no_grad():
226 | alpha = v / (v - iou + (1 + eps))
227 | return iou - (rho2 / c2 + v * alpha) # CIoU
228 | else: # GIoU https://arxiv.org/pdf/1902.09630.pdf
229 | c_area = cw * ch + eps # convex area
230 | return iou - (c_area - union) / c_area # GIoU
231 | else:
232 | return iou # IoU
233 |
234 |
235 | def box_iou(box1, box2):
236 | # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
237 | """
238 | Return intersection-over-union (Jaccard index) of boxes.
239 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
240 | Arguments:
241 | box1 (Tensor[N, 4])
242 | box2 (Tensor[M, 4])
243 | Returns:
244 | iou (Tensor[N, M]): the NxM matrix containing the pairwise
245 | IoU values for every element in boxes1 and boxes2
246 | """
247 |
248 | def box_area(box):
249 | # box = 4xn
250 | return (box[2] - box[0]) * (box[3] - box[1])
251 |
252 | area1 = box_area(box1.T)
253 | area2 = box_area(box2.T)
254 |
255 | # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
256 | inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
257 | return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
258 |
259 |
260 | def bbox_ioa(box1, box2, eps=1E-7):
261 | """ Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2
262 | box1: np.array of shape(4)
263 | box2: np.array of shape(nx4)
264 | returns: np.array of shape(n)
265 | """
266 |
267 | box2 = box2.transpose()
268 |
269 | # Get the coordinates of bounding boxes
270 | b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
271 | b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
272 |
273 | # Intersection area
274 | inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
275 | (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
276 |
277 | # box2 area
278 | box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps
279 |
280 | # Intersection over box2 area
281 | return inter_area / box2_area
282 |
283 |
284 | def wh_iou(wh1, wh2):
285 | # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
286 | wh1 = wh1[:, None] # [N,1,2]
287 | wh2 = wh2[None] # [1,M,2]
288 | inter = torch.min(wh1, wh2).prod(2) # [N,M]
289 | return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)
290 |
291 |
292 | # Plots ----------------------------------------------------------------------------------------------------------------
293 |
294 | def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
295 | # Precision-recall curve
296 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
297 | py = np.stack(py, axis=1)
298 |
299 | if 0 < len(names) < 21: # display per-class legend if < 21 classes
300 | for i, y in enumerate(py.T):
301 | ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
302 | else:
303 | ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
304 |
305 | ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
306 | ax.set_xlabel('Recall')
307 | ax.set_ylabel('Precision')
308 | ax.set_xlim(0, 1)
309 | ax.set_ylim(0, 1)
310 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
311 | fig.savefig(Path(save_dir), dpi=250)
312 | plt.close()
313 |
314 |
315 | def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
316 | # Metric-confidence curve
317 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
318 |
319 | if 0 < len(names) < 21: # display per-class legend if < 21 classes
320 | for i, y in enumerate(py):
321 | ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
322 | else:
323 | ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
324 |
325 | y = py.mean(0)
326 | ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
327 | ax.set_xlabel(xlabel)
328 | ax.set_ylabel(ylabel)
329 | ax.set_xlim(0, 1)
330 | ax.set_ylim(0, 1)
331 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
332 | fig.savefig(Path(save_dir), dpi=250)
333 | plt.close()
334 |
--------------------------------------------------------------------------------