├── .DS_Store
├── LICENSE
├── MR.png
├── README.md
├── __pycache__
├── ds_fusion.cpython-37.pyc
├── full_arrange.cpython-37.pyc
├── global_var.cpython-37.pyc
└── test.cpython-37.pyc
├── cft.png
├── data
├── GlobalWheat2020.yaml
├── VisDrone.yaml
├── argoverse_hd.yaml
├── coco.yaml
├── coco128.yaml
├── hyp.finetune.yaml
├── hyp.scratch.yaml
├── images
│ ├── bus.jpg
│ └── zidane.jpg
├── multispectral
│ ├── FLIR_aligned.yaml
│ ├── LLVIP.yaml
│ └── vedai_color_2.yaml
├── scripts
│ ├── get_argoverse_hd.sh
│ ├── get_coco.sh
│ └── get_voc.sh
└── voc.yaml
├── detect_twostream.py
├── example.png
├── global_var.py
├── hubconf.py
├── models
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-37.pyc
│ ├── common.cpython-37.pyc
│ ├── experimental.cpython-37.pyc
│ ├── yolo.cpython-37.pyc
│ └── yolo_test.cpython-37.pyc
├── common.py
├── experimental.py
├── export.py
├── hub
│ ├── anchors.yaml
│ ├── yolov3-spp.yaml
│ ├── yolov3-tiny.yaml
│ ├── yolov3.yaml
│ ├── yolov5-fpn.yaml
│ ├── yolov5-p2.yaml
│ ├── yolov5-p6.yaml
│ ├── yolov5-p7.yaml
│ ├── yolov5-panet.yaml
│ ├── yolov5l6.yaml
│ ├── yolov5m6.yaml
│ ├── yolov5s-transformer.yaml
│ ├── yolov5s6.yaml
│ └── yolov5x6.yaml
├── transformer
│ ├── yolov5l_fusion_add_FLIR_aligned.yaml
│ ├── yolov5l_fusion_add_llvip.yaml
│ ├── yolov5l_fusion_transformer_FLIR.yaml
│ ├── yolov5l_fusion_transformer_FLIR_aligned.yaml
│ ├── yolov5l_fusion_transformer_llvip.yaml
│ ├── yolov5l_fusion_transformer_vedai.yaml
│ ├── yolov5l_fusion_transformerx3_FLIR_aligned.yaml
│ ├── yolov5l_fusion_transformerx3_llvip.yaml
│ ├── yolov5s_fusion_add_vedai.yaml
│ ├── yolov5s_fusion_transformer_vedai.yaml
│ ├── yolov5s_fusion_transformerx3_vedai.yaml
│ ├── yolov5x_fusion_transformer_FLIR.yaml
│ └── yolov5x_fusion_transformer_FLIR_aligned.yaml
├── yolo.py
├── yolo_test.py
├── yolov5l.yaml
├── yolov5m.yaml
├── yolov5s.yaml
└── yolov5x.yaml
├── requirements.txt
├── test.py
├── train.py
├── utils
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-37.pyc
│ ├── autoanchor.cpython-37.pyc
│ ├── datasets.cpython-37.pyc
│ ├── ds_fusion.cpython-37.pyc
│ ├── general.cpython-37.pyc
│ ├── google_utils.cpython-37.pyc
│ ├── gradcam.cpython-37.pyc
│ ├── loss.cpython-37.pyc
│ ├── metrics.cpython-37.pyc
│ ├── plots.cpython-37.pyc
│ └── torch_utils.cpython-37.pyc
├── activations.py
├── autoanchor.py
├── aws
│ ├── __init__.py
│ ├── mime.sh
│ ├── resume.py
│ └── userdata.sh
├── datasets.py
├── ds_fusion.py
├── flask_rest_api
│ ├── README.md
│ ├── example_request.py
│ └── restapi.py
├── general.py
├── google_app_engine
│ ├── Dockerfile
│ ├── additional_requirements.txt
│ └── app.yaml
├── google_utils.py
├── gradcam.py
├── loss.py
├── metrics.py
├── plots.py
├── torch_utils.py
└── wandb_logging
│ ├── __init__.py
│ ├── __pycache__
│ ├── __init__.cpython-37.pyc
│ └── wandb_utils.cpython-37.pyc
│ ├── log_dataset.py
│ └── wandb_utils.py
└── video
├── demo.gif
└── demo1.gif
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/.DS_Store
--------------------------------------------------------------------------------
/MR.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/MR.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Multispectral-Object-Detection
2 |
3 | [](https://paperswithcode.com/sota/multispectral-object-detection-on-flir?p=cross-modality-fusion-transformer-for)
4 |
5 | [](https://paperswithcode.com/sota/pedestrian-detection-on-llvip?p=cross-modality-fusion-transformer-for)
6 |
7 | [](https://github.com/DocF/multispectral-object-detection/)
8 | 
9 | [](https://github.com/DocF/multispectral-object-detection)
10 |
11 |
12 | ## Intro
13 | Official Code for [Cross-Modality Fusion Transformer for Multispectral Object Detection](https://arxiv.org/abs/2111.00273).
14 |
15 | Multispectral Object Detection with Transformer and Yolov5
16 |
17 | ## Abstract
18 | Multispectral image pairs can provide the combined information, making object detection applications more reliable and robust in the open world.
19 | To fully exploit the different modalities, we present a simple yet effective cross-modality feature fusion approach, named Cross-Modality Fusion Transformer (CFT) in this paper.
20 | Unlike prior CNNs-based works, guided by the Transformer scheme, our network learns long-range dependencies and integrates global contextual information in the feature extraction stage.
21 | More importantly, by leveraging the self attention of the Transformer, the network can naturally carry out simultaneous intra-modality and inter-modality fusion, and robustly capture the latent interactions between RGB and Thermal domains, thereby significantly improving the performance of multispectral object detection.
22 | Extensive experiments and ablation studies on multiple datasets demonstrate that our approach is effective and achieves state-of-the-art detection performance.
23 | ### Demo
24 | **Night Scene**
25 |
26 |

27 |
28 |
29 | **Day Scene**
30 |
31 |

32 |
33 |
34 |
35 | ### Overview
36 |
37 |

38 |
39 |
40 | ## Citation
41 | If you use this repo for your research, please cite our paper:
42 |
43 | ```
44 | @article{qingyun2022cross,
45 | title={Cross-modality attentive feature fusion for object detection in multispectral remote sensing imagery},
46 | author={Qingyun, Fang and Zhaokui, Wang},
47 | journal={Pattern Recognition},
48 | volume={130},
49 | pages={108786},
50 | year={2022},
51 | publisher={Elsevier}
52 | }
53 | @article{fang2021cross,
54 | title={Cross-Modality Fusion Transformer for Multispectral Object Detection},
55 | author={Fang Qingyun and Han Dapeng and Wang Zhaokui},
56 | journal={arXiv preprint arXiv:2111.00273},
57 | year={2021}
58 | }
59 | ```
60 |
61 |
62 |
63 | ## Installation
64 | Python>=3.6.0 is required with all requirements.txt installed including PyTorch>=1.7 (The same as yolov5 https://github.com/ultralytics/yolov5 ).
65 |
66 | #### Clone the repo
67 | git clone https://github.com/DocF/multispectral-object-detection
68 |
69 | #### Install requirements
70 | ```bash
71 | $ cd multispectral-object-detection
72 | $ pip install -r requirements.txt
73 | ```
74 |
75 | ## Dataset
76 | -[FLIR] [[Google Drive]](http://shorturl.at/ahAY4) [[Baidu Drive]](https://pan.baidu.com/s/1z2GHVD3WVlGsVzBR1ajSrQ?pwd=qwer) ```extraction code:qwer```
77 |
78 | A new aligned version.
79 |
80 | -[LLVIP] [download](https://github.com/bupt-ai-cz/LLVIP)
81 |
82 | -[VEDAI] [download](https://downloads.greyc.fr/vedai/)
83 |
84 |
85 | You need to convert all annotations to YOLOv5 format.
86 |
87 | Refer: https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data
88 |
89 | ## Run
90 | #### Download the pretrained weights
91 | yolov5 weights (pre-train)
92 |
93 | -[yolov5s] [google drive](https://drive.google.com/file/d/1UGAsaOvV7jVrk0RvFVYL6Vq0K7NQLD8H/view?usp=sharing)
94 |
95 | -[yolov5m] [google drive](https://drive.google.com/file/d/1qB7L2vtlGppGjHp5xpXCKw14YHhbV4s1/view?usp=sharing)
96 |
97 | -[yolov5l] [google drive](https://drive.google.com/file/d/12OFGLF73CqTgOCMJAycZ8lB4eW19D0nb/view?usp=sharing)
98 |
99 | -[yolov5x] [google drive](https://drive.google.com/file/d/1e9xiQImx84KFQ_a7XXpn608I3rhRmKEn/view?usp=sharing)
100 |
101 | CFT weights
102 |
103 | -[LLVIP] [google drive](https://drive.google.com/file/d/18yLDUOxNXQ17oypQ-fAV9OS9DESOZQtV/view?usp=sharing)
104 |
105 | -[FLIR] [google drive](https://drive.google.com/file/d/1PwEOgT5ZOTjoKT2LpOzvCsxsVgwP8NIJ/view)
106 |
107 |
108 | #### Change the data cfg
109 | some example in data/multispectral/
110 |
111 | #### Change the model cfg
112 | some example in models/transformer/
113 |
114 | note!!! we used xxxx_transfomerx3_dataset.yaml in our paper.
115 |
116 | ### Train Test and Detect
117 | train: ``` python train.py```
118 |
119 | test: ``` python test.py```
120 |
121 | detect: ``` python detect_twostream.py```
122 |
123 | ## Results
124 |
125 | |Dataset|CFT|mAP50|mAP75|mAP|
126 | |:---------: |------------|:-----:|:-----------------:|:-------------:|
127 | |FLIR||73.0|32.0|37.4|
128 | |FLIR| ✔️ |**78.7 (Δ5.7)**|**35.5 (Δ3.5)**|**40.2 (Δ2.8)**|
129 | |LLVIP||95.8|71.4|62.3|
130 | |LLVIP| ✔️ |**97.5 (Δ1.7)**|**72.9 (Δ1.5)**|**63.6 (Δ1.3)**|
131 | |VEDAI||79.7 | 47.7 | 46.8
132 | |VEDAI| ✔️ |**85.3 (Δ5.6)**|**65.9(Δ18.2)**|**56.0 (Δ9.2)**|
133 |
134 |
135 | ### LLVIP
136 | Log Average Miss Rate
137 | |Model| Log Average Miss Rate |
138 | |:---------: |:--------------:|
139 | |YOLOv3-RGB|37.70%|
140 | |YOLOv3-IR|17.73%|
141 | |YOLOv5-RGB|22.59%|
142 | |YOLOv5-IR|10.66%|
143 | |Baseline(Ours)|**6.91%**|
144 | |CFT(Ours)|**5.40%**|
145 |
146 | Miss Rate - FPPI curve
147 |
148 |

149 |
150 |
151 | #### References
152 |
153 | https://github.com/ultralytics/yolov5
154 |
155 |
156 |
--------------------------------------------------------------------------------
/__pycache__/ds_fusion.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/__pycache__/ds_fusion.cpython-37.pyc
--------------------------------------------------------------------------------
/__pycache__/full_arrange.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/__pycache__/full_arrange.cpython-37.pyc
--------------------------------------------------------------------------------
/__pycache__/global_var.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/__pycache__/global_var.cpython-37.pyc
--------------------------------------------------------------------------------
/__pycache__/test.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/__pycache__/test.cpython-37.pyc
--------------------------------------------------------------------------------
/cft.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/cft.png
--------------------------------------------------------------------------------
/data/GlobalWheat2020.yaml:
--------------------------------------------------------------------------------
1 | # Global Wheat 2020 dataset http://www.global-wheat.com/
2 | # Train command: python train.py --data GlobalWheat2020.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /datasets/GlobalWheat2020
6 | # /yolov5
7 |
8 |
9 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
10 | train: # 3422 images
11 | - ../datasets/GlobalWheat2020/images/arvalis_1
12 | - ../datasets/GlobalWheat2020/images/arvalis_2
13 | - ../datasets/GlobalWheat2020/images/arvalis_3
14 | - ../datasets/GlobalWheat2020/images/ethz_1
15 | - ../datasets/GlobalWheat2020/images/rres_1
16 | - ../datasets/GlobalWheat2020/images/inrae_1
17 | - ../datasets/GlobalWheat2020/images/usask_1
18 |
19 | val: # 748 images (WARNING: train set contains ethz_1)
20 | - ../datasets/GlobalWheat2020/images/ethz_1
21 |
22 | test: # 1276
23 | - ../datasets/GlobalWheat2020/images/utokyo_1
24 | - ../datasets/GlobalWheat2020/images/utokyo_2
25 | - ../datasets/GlobalWheat2020/images/nau_1
26 | - ../datasets/GlobalWheat2020/images/uq_1
27 |
28 | # number of classes
29 | nc: 1
30 |
31 | # class names
32 | names: [ 'wheat_head' ]
33 |
34 |
35 | # download command/URL (optional) --------------------------------------------------------------------------------------
36 | download: |
37 | from utils.general import download, Path
38 |
39 | # Download
40 | dir = Path('../datasets/GlobalWheat2020') # dataset directory
41 | urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',
42 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']
43 | download(urls, dir=dir)
44 |
45 | # Make Directories
46 | for p in 'annotations', 'images', 'labels':
47 | (dir / p).mkdir(parents=True, exist_ok=True)
48 |
49 | # Move
50 | for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \
51 | 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':
52 | (dir / p).rename(dir / 'images' / p) # move to /images
53 | f = (dir / p).with_suffix('.json') # json file
54 | if f.exists():
55 | f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations
56 |
--------------------------------------------------------------------------------
/data/VisDrone.yaml:
--------------------------------------------------------------------------------
1 | # VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset
2 | # Train command: python train.py --data VisDrone.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /VisDrone
6 | # /yolov5
7 |
8 |
9 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
10 | train: ../VisDrone/VisDrone2019-DET-train/images # 6471 images
11 | val: ../VisDrone/VisDrone2019-DET-val/images # 548 images
12 | test: ../VisDrone/VisDrone2019-DET-test-dev/images # 1610 images
13 |
14 | # number of classes
15 | nc: 10
16 |
17 | # class names
18 | names: [ 'pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor' ]
19 |
20 |
21 | # download command/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('../VisDrone') # dataset directory
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/argoverse_hd.yaml:
--------------------------------------------------------------------------------
1 | # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/
2 | # Train command: python train.py --data argoverse_hd.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /argoverse
6 | # /yolov5
7 |
8 |
9 | # download command/URL (optional)
10 | download: bash data/scripts/get_argoverse_hd.sh
11 |
12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 | train: ../argoverse/Argoverse-1.1/images/train/ # 39384 images
14 | val: ../argoverse/Argoverse-1.1/images/val/ # 15062 iamges
15 | test: ../argoverse/Argoverse-1.1/images/test/ # Submit to: https://eval.ai/web/challenges/challenge-page/800/overview
16 |
17 | # number of classes
18 | nc: 8
19 |
20 | # class names
21 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign' ]
22 |
--------------------------------------------------------------------------------
/data/coco.yaml:
--------------------------------------------------------------------------------
1 | # COCO 2017 dataset http://cocodataset.org
2 | # Train command: python train.py --data coco.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /coco
6 | # /yolov5
7 |
8 |
9 | # download command/URL (optional)
10 | download: bash data/scripts/get_coco.sh
11 |
12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 | train: ../coco/train2017.txt # 118287 images
14 | val: ../coco/val2017.txt # 5000 images
15 | test: ../coco/test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
16 |
17 | # number of classes
18 | nc: 80
19 |
20 | # class names
21 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
22 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
23 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
24 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
25 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
26 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
27 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
28 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
29 | 'hair drier', 'toothbrush' ]
30 |
31 | # Print classes
32 | # with open('data/coco.yaml') as f:
33 | # d = yaml.safe_load(f) # dict
34 | # for i, x in enumerate(d['names']):
35 | # print(i, x)
36 |
--------------------------------------------------------------------------------
/data/coco128.yaml:
--------------------------------------------------------------------------------
1 | # COCO 2017 dataset http://cocodataset.org - first 128 training images
2 | # Train command: python train.py --data coco128.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /coco128
6 | # /yolov5
7 |
8 |
9 | # download command/URL (optional)
10 | download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip
11 |
12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 | train: ../coco128/images/train2017/ # 128 images
14 | val: ../coco128/images/train2017/ # 128 images
15 |
16 | # number of classes
17 | nc: 80
18 |
19 | # class names
20 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
21 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
22 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
23 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
24 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
25 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
26 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
27 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
28 | 'hair drier', 'toothbrush' ]
29 |
--------------------------------------------------------------------------------
/data/hyp.finetune.yaml:
--------------------------------------------------------------------------------
1 | # Hyperparameters for VOC finetuning
2 | # python train.py --batch 64 --weights yolov5m.pt --data voc.yaml --img 512 --epochs 50
3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4 |
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.02 #(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 |
--------------------------------------------------------------------------------
/data/hyp.scratch.yaml:
--------------------------------------------------------------------------------
1 | # Hyperparameters for COCO training from scratch
2 | # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4 |
5 |
6 | lr0: 0.01 # initial learning rate ( original 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 |
--------------------------------------------------------------------------------
/data/images/bus.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/data/images/bus.jpg
--------------------------------------------------------------------------------
/data/images/zidane.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/data/images/zidane.jpg
--------------------------------------------------------------------------------
/data/multispectral/FLIR_aligned.yaml:
--------------------------------------------------------------------------------
1 | # COCO 2017 dataset http://cocodataset.org - first 128 training images
2 | # Train command: python train.py --data coco128.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /coco128
6 | # /yolov5
7 |
8 |
9 | # download command/URL (optional)
10 | download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip
11 |
12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 | train_rgb: /home/fqy/Data/FLIR_ADAS_1_3/align/yolo/rgb/align_train.txt # 128 images
14 | val_rgb: /home/fqy/Data/FLIR_ADAS_1_3/align/yolo/rgb/align_validation.txt # 128 images
15 | train_ir: /home/fqy/Data/FLIR_ADAS_1_3/align/yolo/ir/align_train.txt # 128 images
16 | val_ir: /home/fqy/Data/FLIR_ADAS_1_3/align/yolo/ir/align_validation.txt # 128 images
17 |
18 | # number of classes
19 | nc: 3
20 |
21 | # class names
22 | names: [ 'person','car','bicycle']
23 |
--------------------------------------------------------------------------------
/data/multispectral/LLVIP.yaml:
--------------------------------------------------------------------------------
1 | # COCO 2017 dataset http://cocodataset.org - first 128 training images
2 | # Train command: python train.py --data coco128.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /coco128
6 | # /yolov5
7 |
8 |
9 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
10 | train_rgb: /home/fqy/DATA/LLVIP/visible/train.txt
11 | val_rgb: /home/fqy/DATA/LLVIP/visible/test.txt
12 | train_ir: /home/fqy/DATA/LLVIP/infrared/train.txt
13 | val_ir: /home/fqy/DATA/LLVIP/infrared/test.txt
14 |
15 | # number of classes
16 | nc: 1
17 |
18 | # class names
19 | names: [ 'person']
20 |
--------------------------------------------------------------------------------
/data/multispectral/vedai_color_2.yaml:
--------------------------------------------------------------------------------
1 | # COCO 2017 dataset http://cocodataset.org - first 128 training images
2 | # Train command: python train.py --data coco128.yaml
3 | # Default dataset location is next to YOLOv5:
4 | # /parent_folder
5 | # /coco128
6 | # /yolov5
7 |
8 |
9 | # download command/URL (optional)
10 | download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip
11 |
12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
13 | train_rgb: /home/fqy/Data/vedai/Vehicules1024/Images/color/fold01.txt # 128 images
14 | val_rgb: /home/fqy/Data/vedai/Vehicules1024/Images/color/fold01test.txt # 128 images
15 | train_ir: /home/fqy/Data/vedai/Vehicules1024/Images/ir/fold01.txt # 128 images
16 | val_ir: /home/fqy/Data/vedai/Vehicules1024/Images/ir/fold01test.txt # 128 images
17 |
18 | # number of classes
19 | nc: 9
20 |
21 | # class names
22 | names: [ 'car', 'truck', 'pickup','tractor','camping car','boat','plane','van','other']
23 |
24 |
--------------------------------------------------------------------------------
/data/scripts/get_argoverse_hd.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/
3 | # Download command: bash data/scripts/get_argoverse_hd.sh
4 | # Train command: python train.py --data argoverse_hd.yaml
5 | # Default dataset location is next to YOLOv5:
6 | # /parent_folder
7 | # /argoverse
8 | # /yolov5
9 |
10 | # Download/unzip images
11 | d='../argoverse/' # unzip directory
12 | mkdir $d
13 | url=https://argoverse-hd.s3.us-east-2.amazonaws.com/
14 | f=Argoverse-HD-Full.zip
15 | curl -L $url$f -o $f && unzip -q $f -d $d && rm $f download, unzip, remove in background
16 | wait # finish background tasks
17 |
18 | cd ../argoverse/Argoverse-1.1/
19 | ln -s tracking images
20 |
21 | cd ../Argoverse-HD/annotations/
22 |
23 | python3 - "$@" <train.txt
84 | cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt >train.all.txt
85 |
86 | mkdir ../VOC ../VOC/images ../VOC/images/train ../VOC/images/val
87 | mkdir ../VOC/labels ../VOC/labels/train ../VOC/labels/val
88 |
89 | python3 - "$@" <= 1
97 | p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
98 | else:
99 | p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
100 | p, s, im0_, frame = path, '', im0s_.copy(), getattr(dataset2, 'frame', 0)
101 |
102 | p = Path(p) # to Path
103 | save_path = str(save_dir / p.name) # img.jpg
104 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
105 | s += '%gx%g ' % img.shape[2:] # print string
106 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
107 | # print(gn)
108 |
109 | # # ----------------------------------------------------------------------------
110 | # # 画GT,替换det
111 | # #
112 | # # ---------------------------------------------------------------------------
113 | # annoPath = "/home/fqy/proj/paper/test_result/gt/"
114 | # annoName = (path_.split("/")[-1]).split(".")[0] + ".txt"
115 | # annoPath += annoName
116 | # # print(annoPath)
117 | # gt = np.loadtxt(annoPath)
118 | # gt = gt.reshape((-1, 5))
119 | # ones = np.ones((gt.shape[0], 1))
120 | # gt = np.hstack((gt, ones))
121 | # gt[:, [0,1,2,3,4,5]] = gt[:, [1,2,3,4,5,0]]
122 | # gt = torch.from_numpy(gt).to(device)
123 | # # print(gt[:, :4])
124 | # gt[:, :4] = xywh2xyxy(gt[:, :4]) * 640
125 | #
126 | # det = gt
127 |
128 | # print(det)
129 | if len(det):
130 | # Rescale boxes from img_size to im0 size
131 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
132 |
133 | # Print results
134 | for c in det[:, -1].unique():
135 | n = (det[:, -1] == c).sum() # detections per class
136 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
137 |
138 | # Write results
139 | for *xyxy, conf, cls in reversed(det):
140 | if save_txt: # Write to file
141 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
142 | line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
143 | with open(txt_path + '.txt', 'a') as f:
144 | f.write(('%g ' * len(line)).rstrip() % line + '\n')
145 |
146 | if save_img or opt.save_crop or view_img: # Add bbox to image
147 | c = int(cls) # integer class
148 | label = None if opt.hide_labels else (names[c] if opt.hide_conf else f'{names[c]} {conf:.2f}')
149 |
150 | plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=opt.line_thickness)
151 | plot_one_box(xyxy, im0_, label=label, color=colors(c, True), line_thickness=opt.line_thickness)
152 | if opt.save_crop:
153 | save_one_box(xyxy, im0s, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
154 |
155 | # Print time (inference + NMS)
156 | print(f'{s}Done. ({t2 - t1:.6f}s, {1/(t2 - t1):.6f}Hz)')
157 | # add all the fps
158 | img_num += 1
159 | fps_sum += 1/(t2 - t1)
160 |
161 | # Stream results
162 | if view_img:
163 | cv2.imshow(str(p), im0)
164 | cv2.waitKey(1) # 1 millisecond
165 |
166 | # Save results (image with detections)
167 | if save_img:
168 | if dataset.mode == 'image':
169 | save_path_rgb = save_path.split('.')[0] + '_rgb.' + save_path.split('.')[1]
170 | save_path_ir = save_path.split('.')[0] + '_ir.' + save_path.split('.')[1]
171 | print(save_path_rgb)
172 | cv2.imwrite(save_path_rgb, im0)
173 | cv2.imwrite(save_path_ir, im0_)
174 | else: # 'video' or 'stream'
175 | if vid_path != save_path: # new video
176 | vid_path = save_path
177 | if isinstance(vid_writer, cv2.VideoWriter):
178 | vid_writer.release() # release previous video writer
179 | if vid_cap: # video
180 | fps = vid_cap.get(cv2.CAP_PROP_FPS)
181 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
182 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
183 | else: # stream
184 | fps, w, h = 30, im0.shape[1], im0.shape[0]
185 | save_path += '.mp4'
186 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
187 | vid_writer.write(im0)
188 |
189 | if save_txt or save_img:
190 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
191 | print(f"Results saved to {save_dir}{s}")
192 |
193 | print(f'Done. ({time.time() - t0:.3f}s)')
194 | print(f'Average Speed: {fps_sum/img_num:.6f}Hz')
195 |
196 |
197 | if __name__ == '__main__':
198 | parser = argparse.ArgumentParser()
199 | parser.add_argument('--weights', nargs='+', type=str, default='/home/fqy/proj/multispectral-object-detection/best.pt', help='model.pt path(s)')
200 | parser.add_argument('--source1', type=str, default='/home/fqy/DATA/FLIR_ADAS_1_3/align/yolo/test/rgb/', help='source') # file/folder, 0 for webcam
201 | parser.add_argument('--source2', type=str, default='/home/fqy/DATA/FLIR_ADAS_1_3/align/yolo/test/ir', help='source') # file/folder, 0 for webcam
202 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
203 | parser.add_argument('--conf-thres', type=float, default=0.4, help='object confidence threshold')
204 | parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
205 | parser.add_argument('--device', default='0', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
206 | parser.add_argument('--view-img', default=False, action='store_true', help='display results')
207 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
208 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
209 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
210 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
211 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
212 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
213 | parser.add_argument('--augment', action='store_true', help='augmented inference')
214 | parser.add_argument('--update', action='store_true', help='update all models')
215 | parser.add_argument('--project', default='runs/detect', help='save results to project/name')
216 | parser.add_argument('--name', default='exp', help='save results to project/name')
217 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
218 | parser.add_argument('--line-thickness', default=2, type=int, help='bounding box thickness (pixels)')
219 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
220 | parser.add_argument('--hide-conf', default=True, action='store_true', help='hide confidences')
221 | opt = parser.parse_args()
222 | print(opt)
223 | check_requirements(exclude=('pycocotools', 'thop'))
224 |
225 | with torch.no_grad():
226 | if opt.update: # update all models (to fix SourceChangeWarning)
227 | for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
228 | detect(opt=opt)
229 | strip_optimizer(opt.weights)
230 | else:
231 | print("helloxxxxxxxxxxxxxxxxxxxx")
232 | detect(opt=opt)
233 |
--------------------------------------------------------------------------------
/example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/example.png
--------------------------------------------------------------------------------
/global_var.py:
--------------------------------------------------------------------------------
1 | # @Time : 2021/6/22 下午4:46
2 | # @Author : Richard FANG
3 | # @File : global_var.py.py
4 | # @Software: PyCharm
5 |
6 |
7 | def _init(): # 初始化
8 | global _global_dict
9 | _global_dict = {}
10 |
11 |
12 | def set_value(key, value):
13 | # 定义一个全局变量
14 | _global_dict[key] = value
15 |
16 |
17 | def get_value(key):
18 | # 获得一个全局变量,不存在则提示读取对应变量失败
19 | try:
20 | return _global_dict[key]
21 | except:
22 | print('读取'+key+'失败\r\n')
--------------------------------------------------------------------------------
/hubconf.py:
--------------------------------------------------------------------------------
1 | """YOLOv5 PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/
2 |
3 | Usage:
4 | import torch
5 | model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
6 | """
7 |
8 | from pathlib import Path
9 |
10 | import torch
11 |
12 | from models.yolo import Model
13 | from utils.general import check_requirements, set_logging
14 | from utils.google_utils import attempt_download
15 | from utils.torch_utils import select_device
16 |
17 | dependencies = ['torch', 'yaml']
18 | check_requirements(Path(__file__).parent / 'requirements.txt', exclude=('pycocotools', 'thop'))
19 |
20 |
21 | def create(name, pretrained, channels, classes, autoshape, verbose):
22 | """Creates a specified YOLOv5 model
23 |
24 | Arguments:
25 | name (str): name of model, i.e. 'yolov5s'
26 | pretrained (bool): load pretrained weights into the model
27 | channels (int): number of input channels
28 | classes (int): number of model classes
29 |
30 | Returns:
31 | pytorch model
32 | """
33 | try:
34 | set_logging(verbose=verbose)
35 |
36 | cfg = list((Path(__file__).parent / 'models').rglob(f'{name}.yaml'))[0] # model.yaml path
37 | model = Model(cfg, channels, classes)
38 | if pretrained:
39 | fname = f'{name}.pt' # checkpoint filename
40 | attempt_download(fname) # download if not found locally
41 | ckpt = torch.load(fname, map_location=torch.device('cpu')) # load
42 | msd = model.state_dict() # model state_dict
43 | csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
44 | csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
45 | model.load_state_dict(csd, strict=False) # load
46 | if len(ckpt['model'].names) == classes:
47 | model.names = ckpt['model'].names # set class names attribute
48 | if autoshape:
49 | model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
50 | device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
51 | return model.to(device)
52 |
53 | except Exception as e:
54 | help_url = 'https://github.com/ultralytics/yolov5/issues/36'
55 | s = 'Cache maybe be out of date, try force_reload=True. See %s for help.' % help_url
56 | raise Exception(s) from e
57 |
58 |
59 | def custom(path_or_model='path/to/model.pt', autoshape=True, verbose=True):
60 | """YOLOv5-custom model https://github.com/ultralytics/yolov5
61 |
62 | Arguments (3 options):
63 | path_or_model (str): 'path/to/model.pt'
64 | path_or_model (dict): torch.load('path/to/model.pt')
65 | path_or_model (nn.Module): torch.load('path/to/model.pt')['model']
66 |
67 | Returns:
68 | pytorch model
69 | """
70 | set_logging(verbose=verbose)
71 |
72 | model = torch.load(path_or_model) if isinstance(path_or_model, str) else path_or_model # load checkpoint
73 | if isinstance(model, dict):
74 | model = model['ema' if model.get('ema') else 'model'] # load model
75 |
76 | hub_model = Model(model.yaml).to(next(model.parameters()).device) # create
77 | hub_model.load_state_dict(model.float().state_dict()) # load state_dict
78 | hub_model.names = model.names # class names
79 | if autoshape:
80 | hub_model = hub_model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
81 | device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
82 | return hub_model.to(device)
83 |
84 |
85 | def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
86 | # YOLOv5-small model https://github.com/ultralytics/yolov5
87 | return create('yolov5s', pretrained, channels, classes, autoshape, verbose)
88 |
89 |
90 | def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
91 | # YOLOv5-medium model https://github.com/ultralytics/yolov5
92 | return create('yolov5m', pretrained, channels, classes, autoshape, verbose)
93 |
94 |
95 | def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
96 | # YOLOv5-large model https://github.com/ultralytics/yolov5
97 | return create('yolov5l', pretrained, channels, classes, autoshape, verbose)
98 |
99 |
100 | def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
101 | # YOLOv5-xlarge model https://github.com/ultralytics/yolov5
102 | return create('yolov5x', pretrained, channels, classes, autoshape, verbose)
103 |
104 |
105 | def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
106 | # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5
107 | return create('yolov5s6', pretrained, channels, classes, autoshape, verbose)
108 |
109 |
110 | def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
111 | # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5
112 | return create('yolov5m6', pretrained, channels, classes, autoshape, verbose)
113 |
114 |
115 | def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
116 | # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5
117 | return create('yolov5l6', pretrained, channels, classes, autoshape, verbose)
118 |
119 |
120 | def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True):
121 | # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5
122 | return create('yolov5x6', pretrained, channels, classes, autoshape, verbose)
123 |
124 |
125 | if __name__ == '__main__':
126 | model = create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) # pretrained
127 | # model = custom(path_or_model='path/to/model.pt') # custom
128 |
129 | # Verify inference
130 | import cv2
131 | import numpy as np
132 | from PIL import Image
133 |
134 | imgs = ['data/images/zidane.jpg', # filename
135 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg', # URI
136 | cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV
137 | Image.open('data/images/bus.jpg'), # PIL
138 | np.zeros((320, 640, 3))] # numpy
139 |
140 | results = model(imgs) # batched inference
141 | results.print()
142 | results.save()
143 |
--------------------------------------------------------------------------------
/models/__init__.py:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/models/__pycache__/__init__.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/models/__pycache__/__init__.cpython-37.pyc
--------------------------------------------------------------------------------
/models/__pycache__/common.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/models/__pycache__/common.cpython-37.pyc
--------------------------------------------------------------------------------
/models/__pycache__/experimental.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/models/__pycache__/experimental.cpython-37.pyc
--------------------------------------------------------------------------------
/models/__pycache__/yolo.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/models/__pycache__/yolo.cpython-37.pyc
--------------------------------------------------------------------------------
/models/__pycache__/yolo_test.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/models/__pycache__/yolo_test.cpython-37.pyc
--------------------------------------------------------------------------------
/models/experimental.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 experimental modules
2 |
3 | import numpy as np
4 | import torch
5 | import torch.nn as nn
6 |
7 | from models.common import Conv, DWConv
8 | from utils.google_utils import attempt_download
9 |
10 |
11 | class CrossConv(nn.Module):
12 | # Cross Convolution Downsample
13 | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
14 | # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
15 | super(CrossConv, self).__init__()
16 | c_ = int(c2 * e) # hidden channels
17 | self.cv1 = Conv(c1, c_, (1, k), (1, s))
18 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
19 | self.add = shortcut and c1 == c2
20 |
21 | def forward(self, x):
22 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
23 |
24 |
25 | class Sum(nn.Module):
26 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
27 | def __init__(self, n, weight=False): # n: number of inputs
28 | super(Sum, self).__init__()
29 | self.weight = weight # apply weights boolean
30 | self.iter = range(n - 1) # iter object
31 | if weight:
32 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
33 |
34 | def forward(self, x):
35 | y = x[0] # no weight
36 | if self.weight:
37 | w = torch.sigmoid(self.w) * 2
38 | for i in self.iter:
39 | y = y + x[i + 1] * w[i]
40 | else:
41 | for i in self.iter:
42 | y = y + x[i + 1]
43 | return y
44 |
45 |
46 | class GhostConv(nn.Module):
47 | # Ghost Convolution https://github.com/huawei-noah/ghostnet
48 | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
49 | super(GhostConv, self).__init__()
50 | c_ = c2 // 2 # hidden channels
51 | self.cv1 = Conv(c1, c_, k, s, None, g, act)
52 | self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
53 |
54 | def forward(self, x):
55 | y = self.cv1(x)
56 | return torch.cat([y, self.cv2(y)], 1)
57 |
58 |
59 | class GhostBottleneck(nn.Module):
60 | # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
61 | def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
62 | super(GhostBottleneck, self).__init__()
63 | c_ = c2 // 2
64 | self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
65 | DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
66 | GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
67 | self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
68 | Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
69 |
70 | def forward(self, x):
71 | return self.conv(x) + self.shortcut(x)
72 |
73 |
74 | class MixConv2d(nn.Module):
75 | # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595
76 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
77 | super(MixConv2d, self).__init__()
78 | groups = len(k)
79 | if equal_ch: # equal c_ per group
80 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
81 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
82 | else: # equal weight.numel() per group
83 | b = [c2] + [0] * groups
84 | a = np.eye(groups + 1, groups, k=-1)
85 | a -= np.roll(a, 1, axis=1)
86 | a *= np.array(k) ** 2
87 | a[0] = 1
88 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
89 |
90 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
91 | self.bn = nn.BatchNorm2d(c2)
92 | self.act = nn.LeakyReLU(0.1, inplace=True)
93 |
94 | def forward(self, x):
95 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
96 |
97 |
98 | class Ensemble(nn.ModuleList):
99 | # Ensemble of models
100 | def __init__(self):
101 | super(Ensemble, self).__init__()
102 |
103 | def forward(self, x, augment=False):
104 | y = []
105 | for module in self:
106 | y.append(module(x, augment)[0])
107 | # y = torch.stack(y).max(0)[0] # max ensemble
108 | # y = torch.stack(y).mean(0) # mean ensemble
109 | y = torch.cat(y, 1) # nms ensemble
110 | return y, None # inference, train output
111 |
112 |
113 | def attempt_load(weights, map_location=None):
114 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
115 | model = Ensemble()
116 | for w in weights if isinstance(weights, list) else [weights]:
117 | attempt_download(w)
118 | ckpt = torch.load(w, map_location=map_location) # load
119 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
120 |
121 | # Compatibility updates
122 | for m in model.modules():
123 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
124 | m.inplace = True # pytorch 1.7.0 compatibility
125 | elif type(m) is Conv:
126 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
127 |
128 | if len(model) == 1:
129 | return model[-1] # return model
130 | else:
131 | print('Ensemble created with %s\n' % weights)
132 | for k in ['names', 'stride']:
133 | setattr(model, k, getattr(model[-1], k))
134 | return model # return ensemble
135 |
--------------------------------------------------------------------------------
/models/export.py:
--------------------------------------------------------------------------------
1 | """Exports a YOLOv5 *.pt model to ONNX and TorchScript formats
2 |
3 | Usage:
4 | $ export PYTHONPATH="$PWD" && python models/export.py --weights yolov5s.pt --img 640 --batch 1
5 | """
6 |
7 | import argparse
8 | import sys
9 | import time
10 | from pathlib import Path
11 |
12 | sys.path.append(Path(__file__).parent.parent.absolute().__str__()) # to run '$ python *.py' files in subdirectories
13 |
14 | import torch
15 | import torch.nn as nn
16 | from torch.utils.mobile_optimizer import optimize_for_mobile
17 |
18 | import models
19 | from models.experimental import attempt_load
20 | from utils.activations import Hardswish, SiLU
21 | from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging
22 | from utils.torch_utils import select_device
23 |
24 | if __name__ == '__main__':
25 | parser = argparse.ArgumentParser()
26 | parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path')
27 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
28 | parser.add_argument('--batch-size', type=int, default=1, help='batch size')
29 | parser.add_argument('--grid', action='store_true', help='export Detect() layer grid')
30 | parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
31 | parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') # ONNX-only
32 | parser.add_argument('--simplify', action='store_true', help='simplify ONNX model') # ONNX-only
33 | opt = parser.parse_args()
34 | opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
35 | print(opt)
36 | set_logging()
37 | t = time.time()
38 |
39 | # Load PyTorch model
40 | device = select_device(opt.device)
41 | model = attempt_load(opt.weights, map_location=device) # load FP32 model
42 | labels = model.names
43 |
44 | # Checks
45 | gs = int(max(model.stride)) # grid size (max stride)
46 | opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
47 |
48 | # Input
49 | img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
50 |
51 | # Update model
52 | for k, m in model.named_modules():
53 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
54 | if isinstance(m, models.common.Conv): # assign export-friendly activations
55 | if isinstance(m.act, nn.Hardswish):
56 | m.act = Hardswish()
57 | elif isinstance(m.act, nn.SiLU):
58 | m.act = SiLU()
59 | # elif isinstance(m, models.yolo.Detect):
60 | # m.forward = m.forward_export # assign forward (optional)
61 | model.model[-1].export = not opt.grid # set Detect() layer grid export
62 | for _ in range(2):
63 | y = model(img) # dry runs
64 | print(f"\n{colorstr('PyTorch:')} starting from {opt.weights} ({file_size(opt.weights):.1f} MB)")
65 |
66 | # TorchScript export -----------------------------------------------------------------------------------------------
67 | prefix = colorstr('TorchScript:')
68 | try:
69 | print(f'\n{prefix} starting export with torch {torch.__version__}...')
70 | f = opt.weights.replace('.pt', '.torchscript.pt') # filename
71 | ts = torch.jit.trace(model, img, strict=False)
72 | ts = optimize_for_mobile(ts) # https://pytorch.org/tutorials/recipes/script_optimized.html
73 | ts.save(f)
74 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
75 | except Exception as e:
76 | print(f'{prefix} export failure: {e}')
77 |
78 | # ONNX export ------------------------------------------------------------------------------------------------------
79 | prefix = colorstr('ONNX:')
80 | try:
81 | import onnx
82 |
83 | print(f'{prefix} starting export with onnx {onnx.__version__}...')
84 | f = opt.weights.replace('.pt', '.onnx') # filename
85 | torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
86 | dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
87 | 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None)
88 |
89 | # Checks
90 | model_onnx = onnx.load(f) # load onnx model
91 | onnx.checker.check_model(model_onnx) # check onnx model
92 | # print(onnx.helper.printable_graph(model_onnx.graph)) # print
93 |
94 | # Simplify
95 | if opt.simplify:
96 | try:
97 | check_requirements(['onnx-simplifier'])
98 | import onnxsim
99 |
100 | print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
101 | model_onnx, check = onnxsim.simplify(model_onnx,
102 | dynamic_input_shape=opt.dynamic,
103 | input_shapes={'images': list(img.shape)} if opt.dynamic else None)
104 | assert check, 'assert check failed'
105 | onnx.save(model_onnx, f)
106 | except Exception as e:
107 | print(f'{prefix} simplifier failure: {e}')
108 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
109 | except Exception as e:
110 | print(f'{prefix} export failure: {e}')
111 |
112 | # CoreML export ----------------------------------------------------------------------------------------------------
113 | prefix = colorstr('CoreML:')
114 | try:
115 | import coremltools as ct
116 |
117 | print(f'{prefix} starting export with coremltools {ct.__version__}...')
118 | # convert model from torchscript and apply pixel scaling as per detect.py
119 | model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
120 | f = opt.weights.replace('.pt', '.mlmodel') # filename
121 | model.save(f)
122 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
123 | except Exception as e:
124 | print(f'{prefix} export failure: {e}')
125 |
126 | # Finish
127 | print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.')
128 |
--------------------------------------------------------------------------------
/models/hub/anchors.yaml:
--------------------------------------------------------------------------------
1 | # Default YOLOv5 anchors for COCO data
2 |
3 |
4 | # P5 -------------------------------------------------------------------------------------------------------------------
5 | # P5-640:
6 | anchors_p5_640:
7 | - [ 10,13, 16,30, 33,23 ] # P3/8
8 | - [ 30,61, 62,45, 59,119 ] # P4/16
9 | - [ 116,90, 156,198, 373,326 ] # P5/32
10 |
11 |
12 | # P6 -------------------------------------------------------------------------------------------------------------------
13 | # 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
14 | anchors_p6_640:
15 | - [ 9,11, 21,19, 17,41 ] # P3/8
16 | - [ 43,32, 39,70, 86,64 ] # P4/16
17 | - [ 65,131, 134,130, 120,265 ] # P5/32
18 | - [ 282,180, 247,354, 512,387 ] # P6/64
19 |
20 | # 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
21 | anchors_p6_1280:
22 | - [ 19,27, 44,40, 38,94 ] # P3/8
23 | - [ 96,68, 86,152, 180,137 ] # P4/16
24 | - [ 140,301, 303,264, 238,542 ] # P5/32
25 | - [ 436,615, 739,380, 925,792 ] # P6/64
26 |
27 | # 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
28 | anchors_p6_1920:
29 | - [ 28,41, 67,59, 57,141 ] # P3/8
30 | - [ 144,103, 129,227, 270,205 ] # P4/16
31 | - [ 209,452, 455,396, 358,812 ] # P5/32
32 | - [ 653,922, 1109,570, 1387,1187 ] # P6/64
33 |
34 |
35 | # P7 -------------------------------------------------------------------------------------------------------------------
36 | # 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
37 | anchors_p7_640:
38 | - [ 11,11, 13,30, 29,20 ] # P3/8
39 | - [ 30,46, 61,38, 39,92 ] # P4/16
40 | - [ 78,80, 146,66, 79,163 ] # P5/32
41 | - [ 149,150, 321,143, 157,303 ] # P6/64
42 | - [ 257,402, 359,290, 524,372 ] # P7/128
43 |
44 | # 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
45 | anchors_p7_1280:
46 | - [ 19,22, 54,36, 32,77 ] # P3/8
47 | - [ 70,83, 138,71, 75,173 ] # P4/16
48 | - [ 165,159, 148,334, 375,151 ] # P5/32
49 | - [ 334,317, 251,626, 499,474 ] # P6/64
50 | - [ 750,326, 534,814, 1079,818 ] # P7/128
51 |
52 | # 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
53 | anchors_p7_1920:
54 | - [ 29,34, 81,55, 47,115 ] # P3/8
55 | - [ 105,124, 207,107, 113,259 ] # P4/16
56 | - [ 247,238, 222,500, 563,227 ] # P5/32
57 | - [ 501,476, 376,939, 749,711 ] # P6/64
58 | - [ 1126,489, 801,1222, 1618,1227 ] # P7/128
59 |
--------------------------------------------------------------------------------
/models/hub/yolov3-spp.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
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-fpn.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
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 | [ [ 24, 27, 30 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5)
54 | ]
55 |
--------------------------------------------------------------------------------
/models/hub/yolov5-p6.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.67 # model depth multiple
4 | width_multiple: 0.75 # layer channel multiple
5 |
6 | # anchors
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-transformer.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.33 # model depth multiple
4 | width_multiple: 1.25 # layer channel multiple
5 |
6 | # anchors
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/transformer/yolov5l_fusion_add_FLIR_aligned.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 3 # number of classes
3 | depth_multiple: 1.00 # model depth multiple
4 | width_multiple: 1.00 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | [-1, 1, Focus, [64, 3]], # 0-P1/2
18 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
19 | [-1, 3, C3, [128]],
20 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
21 | [-1, 9, C3, [256]],
22 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
23 | [-1, 9, C3, [512]],
24 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
25 | [-1, 1, SPP, [1024, [5, 9, 13]]],
26 | [-1, 3, C3, [1024, False]], # 9
27 |
28 | [-4, 1, Focus, [64, 3]], # 10-P1/2
29 | [-1, 1, Conv, [128, 3, 2]], # 11-P2/4
30 | [-1, 3, C3, [128]],
31 | [-1, 1, Conv, [256, 3, 2]], # 13-P3/8
32 | [-1, 9, C3, [256]],
33 | [-1, 1, Conv, [512, 3, 2]], # 15-P4/16
34 | [-1, 9, C3, [512]],
35 | [-1, 1, Conv, [1024, 3, 2]], # 17-P5/32
36 | [-1, 1, SPP, [1024, [5, 9, 13]]],
37 | [-1, 3, C3, [1024, False]], # 19
38 |
39 | ######### Add Block #############
40 | [[4,14], 1, Add, [1]], # 20 two stream fuse
41 | [[6,16], 1, Add, [1]], # 21 two stream fuse
42 | [[9,19], 1, Add, [1]], # 22 two stream fuse
43 | ]
44 |
45 |
46 | # YOLOv5 head
47 | head:
48 | [[-1, 1, Conv, [512, 1, 1]], # 23
49 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 24
50 | [[-1,21], 1, Concat, [1]], # 25 cat backbone P4
51 | [-1, 3, C3, [512, False]], # 26
52 |
53 | [-1, 1, Conv, [256, 1, 1]], # 27
54 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 28
55 | [[-1,20], 1, Concat, [1]], # 29 cat backbone P3
56 | [-1, 3, C3, [256, False]], # 30 (P3/8-small)
57 |
58 | [-1, 1, Conv, [256, 3, 2]], # 31
59 | [[-1,27], 1, Concat, [1]], # 32 cat head P4
60 | [-1, 3, C3, [512, False]], # 33 (P4/16-medium)
61 |
62 | [-1, 1, Conv, [512, 3, 2]], # 34
63 | [[-1,23], 1, Concat, [1]], # 35 cat head P5
64 | [-1, 3, C3, [1024, False]], # 36 (P5/32-large)
65 |
66 | [[30, 33, 36], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
67 | ]
68 |
--------------------------------------------------------------------------------
/models/transformer/yolov5l_fusion_add_llvip.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 1 # number of classes
3 | depth_multiple: 1.00 # model depth multiple
4 | width_multiple: 1.00 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | [-1, 1, Focus, [64, 3]], # 0-P1/2
18 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
19 | [-1, 3, C3, [128]],
20 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
21 | [-1, 9, C3, [256]],
22 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
23 | [-1, 9, C3, [512]],
24 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
25 | [-1, 1, SPP, [1024, [5, 9, 13]]],
26 | [-1, 3, C3, [1024, False]], # 9
27 |
28 | [-4, 1, Focus, [64, 3]], # 10-P1/2
29 | [-1, 1, Conv, [128, 3, 2]], # 11-P2/4
30 | [-1, 3, C3, [128]],
31 | [-1, 1, Conv, [256, 3, 2]], # 13-P3/8
32 | [-1, 9, C3, [256]],
33 | [-1, 1, Conv, [512, 3, 2]], # 15-P4/16
34 | [-1, 9, C3, [512]],
35 | [-1, 1, Conv, [1024, 3, 2]], # 17-P5/32
36 | [-1, 1, SPP, [1024, [5, 9, 13]]],
37 | [-1, 3, C3, [1024, False]], # 19
38 |
39 | ######### Add Block #############
40 | [[4,14], 1, Add, [1]], # 20 two stream fuse
41 | [[6,16], 1, Add, [1]], # 21 two stream fuse
42 | [[9,19], 1, Add, [1]], # 22 two stream fuse
43 | ]
44 |
45 |
46 | # YOLOv5 head
47 | head:
48 | [[-1, 1, Conv, [512, 1, 1]], # 23
49 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 24
50 | [[-1,21], 1, Concat, [1]], # 25 cat backbone P4
51 | [-1, 3, C3, [512, False]], # 26
52 |
53 | [-1, 1, Conv, [256, 1, 1]], # 27
54 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 28
55 | [[-1,20], 1, Concat, [1]], # 29 cat backbone P3
56 | [-1, 3, C3, [256, False]], # 30 (P3/8-small)
57 |
58 | [-1, 1, Conv, [256, 3, 2]], # 31
59 | [[-1,27], 1, Concat, [1]], # 32 cat head P4
60 | [-1, 3, C3, [512, False]], # 33 (P4/16-medium)
61 |
62 | [-1, 1, Conv, [512, 3, 2]], # 34
63 | [[-1,23], 1, Concat, [1]], # 35 cat head P5
64 | [-1, 3, C3, [1024, False]], # 36 (P5/32-large)
65 |
66 | [[30, 33, 36], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
67 | ]
68 |
--------------------------------------------------------------------------------
/models/transformer/yolov5l_fusion_transformer_FLIR.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 3 # number of classes
3 | depth_multiple: 1.00 # model depth multiple
4 | width_multiple: 1.00 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | ######### TransformerBlock One #############
18 | # stream one
19 | [-1, 1, Focus, [64, 3]], # 0-P1/2
20 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
21 | [-1, 3, C3, [128]], # 2-P2/4
22 | # stream two
23 | [-4, 1, Focus, [64, 3]], # 3-P1/2
24 | [-1, 1, Conv, [128, 3, 2]], # 4-P2/4
25 | [-1, 3, C3, [128]], # 5-P2/4
26 | # transformer fusion
27 | [[2,5], 1, GPT, [128]], # 6-P2/4
28 | [[2,6], 1, Add2, [128,0]], # 7-P2/4 stream one:x+trans[0]
29 | [[5,6], 1, Add2, [128,1]], # 8-P2/4 stream two:x+trans[1]
30 |
31 | ######### TransformerBlock Two #############
32 | # stream one
33 | [7, 1, Conv, [256, 3, 2]], # 9-P3/8
34 | [-1, 9, C3, [256]], # 10-P3/8
35 | # stream two
36 | [8, 1, Conv, [256, 3, 2]], # 11-P3/8
37 | [-1, 9, C3, [256]], # 12-P3/8
38 | # transformer fusion
39 | [[10,12], 1, GPT, [256]], # 13-P3/8
40 | [[10,13], 1, Add2, [256,0]], # 14-P3/8 stream one x+trans[0]
41 | [[12,13], 1, Add2, [256,1]], # 15-P3/8 stream two x+trans[1]
42 |
43 |
44 | ######### TransformerBlock Three #############
45 | # stream one
46 | [14, 1, Conv, [512, 3, 2]], # 16-P4/16
47 | [-1, 9, C3, [512]], # 17-P4/16
48 | # stream two
49 | [15, 1, Conv, [512, 3, 2]], # 18-P4/16
50 | [-1, 9, C3, [512]], # 19-P4/16
51 | # transformer fusion
52 | [[17,19], 1, GPT, [512]], # 20-P3/8
53 | [[17,20], 1, Add2, [512,0]], # 21-P3/8 stream one x+trans[0]
54 | [[19,20], 1, Add2, [512,1]], # 22-P3/8 stream two x+trans[1]
55 |
56 |
57 | ######### TransformerBlock Four #############
58 | # stream one
59 | [-2, 1, Conv, [1024, 3, 2]], # 23-P5/32
60 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 24-P5/32
61 | [-1, 3, C3, [1024, False]], # 25-P5/32
62 | # stream two
63 | [22, 1, Conv, [1024, 3, 2]], # 26-P5/32
64 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 27-P5/32
65 | [-1, 3, C3, [1024, False]], # 28-P5/32
66 | # transformer fusion
67 | [[25,28], 1, GPT, [1024]], # 29-P5/32
68 | [[25,29], 1, Add2, [1024,0]], # 30-P5/32 stream one x+trans[0]
69 | [[28,29], 1, Add2, [1024,1]], # 31-P5/32 stream two x+trans[1]
70 |
71 |
72 | ######### Add Block #############
73 | [[14,15], 1, Add, [1]], # 32-P3/8 fusion backbone P3
74 | [[21,22], 1, Add, [1]], # 33-P4/16 fusion backbone P4
75 | [[30,31], 1, Add, [1]], # 34-P5/32 fusion backbone P5
76 |
77 | ]
78 |
79 |
80 | # YOLOv5 head
81 | head:
82 | [
83 | [-1, 1, Conv, [512, 1, 1]], # 35
84 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 36
85 | [[-1,33], 1, Concat, [1]], # 37 cat backbone P4
86 | [-1, 3, C3, [512, False]], # 38
87 |
88 | [-1, 1, Conv, [256, 1, 1]], # 39
89 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 40
90 | [[-1,32], 1, Concat, [1]], # 41 cat backbone P3
91 | [-1, 3, C3, [256, False]], # 42 (P3/8-small)
92 |
93 | [-1, 1, Conv, [256, 3, 2]], # 43
94 | [[-1,39], 1, Concat, [1]], # 44 cat head P4
95 | [-1, 3, C3, [512, False]], # 45 (P4/16-medium)
96 |
97 | [-1, 1, Conv, [512, 3, 2]], # 46
98 | [[-1,35], 1, Concat, [1]], # 47 cat head P5
99 | [-1, 3, C3, [1024, False]], # 48 (P5/32-large)
100 |
101 | [[42, 45, 48], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
102 | ]
103 |
--------------------------------------------------------------------------------
/models/transformer/yolov5l_fusion_transformer_FLIR_aligned.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 3 # number of classes
3 | depth_multiple: 1.00 # model depth multiple
4 | width_multiple: 1.00 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | ######### TransformerBlock One #############
18 | # stream one
19 | [-1, 1, Focus, [64, 3]], # 0-P1/2
20 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
21 | [-1, 3, C3, [128]], # 2-P2/4
22 | # stream two
23 | [-4, 1, Focus, [64, 3]], # 3-P1/2
24 | [-1, 1, Conv, [128, 3, 2]], # 4-P2/4
25 | [-1, 3, C3, [128]], # 5-P2/4
26 | # transformer fusion
27 | [[2,5], 1, GPT, [128]], # 6-P2/4
28 | [[2,6], 1, Add2, [128,0]], # 7-P2/4 stream one:x+trans[0]
29 | [[5,6], 1, Add2, [128,1]], # 8-P2/4 stream two:x+trans[1]
30 |
31 | ######### TransformerBlock Two #############
32 | # stream one
33 | [7, 1, Conv, [256, 3, 2]], # 9-P3/8
34 | [-1, 9, C3, [256]], # 10-P3/8
35 | # stream two
36 | [8, 1, Conv, [256, 3, 2]], # 11-P3/8
37 | [-1, 9, C3, [256]], # 12-P3/8
38 | # transformer fusion
39 | [[10,12], 1, GPT, [256]], # 13-P3/8
40 | [[10,13], 1, Add2, [256,0]], # 14-P3/8 stream one x+trans[0]
41 | [[12,13], 1, Add2, [256,1]], # 15-P3/8 stream two x+trans[1]
42 |
43 |
44 | ######### TransformerBlock Three #############
45 | # stream one
46 | [14, 1, Conv, [512, 3, 2]], # 16-P4/16
47 | [-1, 9, C3, [512]], # 17-P4/16
48 | # stream two
49 | [15, 1, Conv, [512, 3, 2]], # 18-P4/16
50 | [-1, 9, C3, [512]], # 19-P4/16
51 | # transformer fusion
52 | [[17,19], 1, GPT, [512]], # 20-P3/8
53 | [[17,20], 1, Add2, [512,0]], # 21-P3/8 stream one x+trans[0]
54 | [[19,20], 1, Add2, [512,1]], # 22-P3/8 stream two x+trans[1]
55 |
56 |
57 | ######### TransformerBlock Four #############
58 | # stream one
59 | [-2, 1, Conv, [1024, 3, 2]], # 23-P5/32
60 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 24-P5/32
61 | [-1, 3, C3, [1024, False]], # 25-P5/32
62 | # stream two
63 | [22, 1, Conv, [1024, 3, 2]], # 26-P5/32
64 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 27-P5/32
65 | [-1, 3, C3, [1024, False]], # 28-P5/32
66 | # transformer fusion
67 | [[25,28], 1, GPT, [1024]], # 29-P5/32
68 | [[25,29], 1, Add2, [1024,0]], # 30-P5/32 stream one x+trans[0]
69 | [[28,29], 1, Add2, [1024,1]], # 31-P5/32 stream two x+trans[1]
70 |
71 |
72 | ######### Add Block #############
73 | [[14,15], 1, Add, [1]], # 32-P3/8 fusion backbone P3
74 | [[21,22], 1, Add, [1]], # 33-P4/16 fusion backbone P4
75 | [[30,31], 1, Add, [1]], # 34-P5/32 fusion backbone P5
76 |
77 | ]
78 |
79 |
80 | # YOLOv5 head
81 | head:
82 | [
83 | [-1, 1, Conv, [512, 1, 1]], # 35
84 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 36
85 | [[-1,33], 1, Concat, [1]], # 37 cat backbone P4
86 | [-1, 3, C3, [512, False]], # 38
87 |
88 | [-1, 1, Conv, [256, 1, 1]], # 39
89 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 40
90 | [[-1,32], 1, Concat, [1]], # 41 cat backbone P3
91 | [-1, 3, C3, [256, False]], # 42 (P3/8-small)
92 |
93 | [-1, 1, Conv, [256, 3, 2]], # 43
94 | [[-1,39], 1, Concat, [1]], # 44 cat head P4
95 | [-1, 3, C3, [512, False]], # 45 (P4/16-medium)
96 |
97 | [-1, 1, Conv, [512, 3, 2]], # 46
98 | [[-1,35], 1, Concat, [1]], # 47 cat head P5
99 | [-1, 3, C3, [1024, False]], # 48 (P5/32-large)
100 |
101 | [[42, 45, 48], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
102 | ]
103 |
--------------------------------------------------------------------------------
/models/transformer/yolov5l_fusion_transformer_llvip.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 1 # number of classes
3 | depth_multiple: 1.00 # model depth multiple
4 | width_multiple: 1.00 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | ######### TransformerBlock One #############
18 | # stream one
19 | [-1, 1, Focus, [64, 3]], # 0-P1/2
20 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
21 | [-1, 3, C3, [128]], # 2-P2/4
22 | # stream two
23 | [-4, 1, Focus, [64, 3]], # 3-P1/2
24 | [-1, 1, Conv, [128, 3, 2]], # 4-P2/4
25 | [-1, 3, C3, [128]], # 5-P2/4
26 | # transformer fusion
27 | [[2,5], 1, GPT, [128]], # 6-P2/4
28 | [[2,6], 1, Add2, [128,0]], # 7-P2/4 stream one:x+trans[0]
29 | [[5,6], 1, Add2, [128,1]], # 8-P2/4 stream two:x+trans[1]
30 |
31 | ######### TransformerBlock Two #############
32 | # stream one
33 | [7, 1, Conv, [256, 3, 2]], # 9-P3/8
34 | [-1, 9, C3, [256]], # 10-P3/8
35 | # stream two
36 | [8, 1, Conv, [256, 3, 2]], # 11-P3/8
37 | [-1, 9, C3, [256]], # 12-P3/8
38 | # transformer fusion
39 | [[10,12], 1, GPT, [256]], # 13-P3/8
40 | [[10,13], 1, Add2, [256,0]], # 14-P3/8 stream one x+trans[0]
41 | [[12,13], 1, Add2, [256,1]], # 15-P3/8 stream two x+trans[1]
42 |
43 |
44 | ######### TransformerBlock Three #############
45 | # stream one
46 | [14, 1, Conv, [512, 3, 2]], # 16-P4/16
47 | [-1, 9, C3, [512]], # 17-P4/16
48 | # stream two
49 | [15, 1, Conv, [512, 3, 2]], # 18-P4/16
50 | [-1, 9, C3, [512]], # 19-P4/16
51 | # transformer fusion
52 | [[17,19], 1, GPT, [512]], # 20-P3/8
53 | [[17,20], 1, Add2, [512,0]], # 21-P3/8 stream one x+trans[0]
54 | [[19,20], 1, Add2, [512,1]], # 22-P3/8 stream two x+trans[1]
55 |
56 |
57 | ######### TransformerBlock Four #############
58 | # stream one
59 | [-2, 1, Conv, [1024, 3, 2]], # 23-P5/32
60 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 24-P5/32
61 | [-1, 3, C3, [1024, False]], # 25-P5/32
62 | # stream two
63 | [22, 1, Conv, [1024, 3, 2]], # 26-P5/32
64 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 27-P5/32
65 | [-1, 3, C3, [1024, False]], # 28-P5/32
66 | # transformer fusion
67 | [[25,28], 1, GPT, [1024]], # 29-P5/32
68 | [[25,29], 1, Add2, [1024,0]], # 30-P5/32 stream one x+trans[0]
69 | [[28,29], 1, Add2, [1024,1]], # 31-P5/32 stream two x+trans[1]
70 |
71 |
72 | ######### Add Block #############
73 | [[14,15], 1, Add, [1]], # 32-P3/8 fusion backbone P3
74 | [[21,22], 1, Add, [1]], # 33-P4/16 fusion backbone P4
75 | [[30,31], 1, Add, [1]], # 34-P5/32 fusion backbone P5
76 |
77 | ]
78 |
79 |
80 | # YOLOv5 head
81 | head:
82 | [
83 | [-1, 1, Conv, [512, 1, 1]], # 35
84 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 36
85 | [[-1,33], 1, Concat, [1]], # 37 cat backbone P4
86 | [-1, 3, C3, [512, False]], # 38
87 |
88 | [-1, 1, Conv, [256, 1, 1]], # 39
89 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 40
90 | [[-1,32], 1, Concat, [1]], # 41 cat backbone P3
91 | [-1, 3, C3, [256, False]], # 42 (P3/8-small)
92 |
93 | [-1, 1, Conv, [256, 3, 2]], # 43
94 | [[-1,39], 1, Concat, [1]], # 44 cat head P4
95 | [-1, 3, C3, [512, False]], # 45 (P4/16-medium)
96 |
97 | [-1, 1, Conv, [512, 3, 2]], # 46
98 | [[-1,35], 1, Concat, [1]], # 47 cat head P5
99 | [-1, 3, C3, [1024, False]], # 48 (P5/32-large)
100 |
101 | [[42, 45, 48], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
102 | ]
103 |
--------------------------------------------------------------------------------
/models/transformer/yolov5l_fusion_transformer_vedai.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 9 # number of classes
3 | depth_multiple: 1.00 # model depth multiple
4 | width_multiple: 1.00 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | ######### TransformerBlock One #############
18 | # stream one
19 | [-1, 1, Focus, [64, 3]], # 0-P1/2
20 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
21 | [-1, 3, C3, [128]], # 2-P2/4
22 | # stream two
23 | [-4, 1, Focus, [64, 3]], # 3-P1/2
24 | [-1, 1, Conv, [128, 3, 2]], # 4-P2/4
25 | [-1, 3, C3, [128]], # 5-P2/4
26 | # transformer fusion
27 | [[2,5], 1, GPT, [128]], # 6-P2/4
28 | [[2,6], 1, Add2, [128,0]], # 7-P2/4 stream one:x+trans[0]
29 | [[5,6], 1, Add2, [128,1]], # 8-P2/4 stream two:x+trans[1]
30 |
31 | ######### TransformerBlock Two #############
32 | # stream one
33 | [7, 1, Conv, [256, 3, 2]], # 9-P3/8
34 | [-1, 9, C3, [256]], # 10-P3/8
35 | # stream two
36 | [8, 1, Conv, [256, 3, 2]], # 11-P3/8
37 | [-1, 9, C3, [256]], # 12-P3/8
38 | # transformer fusion
39 | [[10,12], 1, GPT, [256]], # 13-P3/8
40 | [[10,13], 1, Add2, [256,0]], # 14-P3/8 stream one x+trans[0]
41 | [[12,13], 1, Add2, [256,1]], # 15-P3/8 stream two x+trans[1]
42 |
43 |
44 | ######### TransformerBlock Three #############
45 | # stream one
46 | [14, 1, Conv, [512, 3, 2]], # 16-P4/16
47 | [-1, 9, C3, [512]], # 17-P4/16
48 | # stream two
49 | [15, 1, Conv, [512, 3, 2]], # 18-P4/16
50 | [-1, 9, C3, [512]], # 19-P4/16
51 | # transformer fusion
52 | [[17,19], 1, GPT, [512]], # 20-P3/8
53 | [[17,20], 1, Add2, [512,0]], # 21-P3/8 stream one x+trans[0]
54 | [[19,20], 1, Add2, [512,1]], # 22-P3/8 stream two x+trans[1]
55 |
56 |
57 | ######### TransformerBlock Four #############
58 | # stream one
59 | [-2, 1, Conv, [1024, 3, 2]], # 23-P5/32
60 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 24-P5/32
61 | [-1, 3, C3, [1024, False]], # 25-P5/32
62 | # stream two
63 | [22, 1, Conv, [1024, 3, 2]], # 26-P5/32
64 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 27-P5/32
65 | [-1, 3, C3, [1024, False]], # 28-P5/32
66 | # transformer fusion
67 | [[25,28], 1, GPT, [1024]], # 29-P5/32
68 | [[25,29], 1, Add2, [1024,0]], # 30-P5/32 stream one x+trans[0]
69 | [[28,29], 1, Add2, [1024,1]], # 31-P5/32 stream two x+trans[1]
70 |
71 |
72 | ######### Add Block #############
73 | [[14,15], 1, Add, [1]], # 32-P3/8 fusion backbone P3
74 | [[21,22], 1, Add, [1]], # 33-P4/16 fusion backbone P4
75 | [[30,31], 1, Add, [1]], # 34-P5/32 fusion backbone P5
76 |
77 | ]
78 |
79 |
80 | # YOLOv5 head
81 | head:
82 | [
83 | [-1, 1, Conv, [512, 1, 1]], # 35
84 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 36
85 | [[-1,33], 1, Concat, [1]], # 37 cat backbone P4
86 | [-1, 3, C3, [512, False]], # 38
87 |
88 | [-1, 1, Conv, [256, 1, 1]], # 39
89 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 40
90 | [[-1,32], 1, Concat, [1]], # 41 cat backbone P3
91 | [-1, 3, C3, [256, False]], # 42 (P3/8-small)
92 |
93 | [-1, 1, Conv, [256, 3, 2]], # 43
94 | [[-1,39], 1, Concat, [1]], # 44 cat head P4
95 | [-1, 3, C3, [512, False]], # 45 (P4/16-medium)
96 |
97 | [-1, 1, Conv, [512, 3, 2]], # 46
98 | [[-1,35], 1, Concat, [1]], # 47 cat head P5
99 | [-1, 3, C3, [1024, False]], # 48 (P5/32-large)
100 |
101 | [[42, 45, 48], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
102 | ]
103 |
--------------------------------------------------------------------------------
/models/transformer/yolov5l_fusion_transformerx3_FLIR_aligned.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 3 # number of classes
3 | depth_multiple: 1.00 # model depth multiple
4 | width_multiple: 1.00 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | ######### TransformerBlock One #############
18 | # stream one
19 | [-1, 1, Focus, [64, 3]], # 0-P1/2
20 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
21 | [-1, 3, C3, [128]], # 2-P2/4
22 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
23 | [-1, 9, C3, [256]], # 4-P3/8
24 | # stream two
25 | [-4, 1, Focus, [64, 3]], # 5-P1/2
26 | [-1, 1, Conv, [128, 3, 2]], # 6-P2/4
27 | [-1, 3, C3, [128]], # 7-P2/4
28 | [-1, 1, Conv, [256, 3, 2]], # 8-P3/8
29 | [-1, 9, C3, [256]], # 9-P3/8
30 |
31 |
32 | ######### TransformerBlock Two #############
33 | # transformer fusion
34 | [[4,9], 1, GPT, [256]], # 10-P3/8
35 | [[4,10], 1, Add2, [256,0]], # 11-P3/8 stream one x+trans[0]
36 | [[9,10], 1, Add2, [256,1]], # 12-P3/8 stream two x+trans[1]
37 |
38 |
39 | ######### TransformerBlock Three #############
40 | # stream one
41 | [11, 1, Conv, [512, 3, 2]], # 13-P4/16
42 | [-1, 9, C3, [512]], # 14-P4/16
43 | # stream two
44 | [12, 1, Conv, [512, 3, 2]], # 15-P4/16
45 | [-1, 9, C3, [512]], # 16-P4/16
46 | # transformer fusion
47 | [[14,16], 1, GPT, [512]], # 17-P3/8
48 | [[14,17], 1, Add2, [512,0]], # 18-P3/8 stream one x+trans[0]
49 | [[16,17], 1, Add2, [512,1]], # 19-P3/8 stream two x+trans[1]
50 |
51 |
52 | ######### TransformerBlock Four #############
53 | # stream one
54 | [18, 1, Conv, [1024, 3, 2]], # 20-P5/32
55 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 21-P5/32
56 | [-1, 3, C3, [1024, False]], # 22-P5/32
57 | # stream two
58 | [19, 1, Conv, [1024, 3, 2]], # 23-P5/32
59 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 24-P5/32
60 | [-1, 3, C3, [1024, False]], # 25-P5/32
61 | # transformer fusion
62 | [[22,25], 1, GPT, [1024]], # 26-P5/32
63 | [[22,26], 1, Add2, [1024,0]], # 27-P5/32 stream one x+trans[0]
64 | [[25,26], 1, Add2, [1024,1]], # 28-P5/32 stream two x+trans[1]
65 |
66 |
67 | ######### Add Block #############
68 | [[11,12], 1, Add, [1]], # 29-P3/8 fusion backbone P3
69 | [[18,19], 1, Add, [1]], # 30-P4/16 fusion backbone P4
70 | [[27,28], 1, Add, [1]], # 31-P5/32 fusion backbone P5
71 |
72 | ]
73 |
74 |
75 | # YOLOv5 head
76 | head:
77 | [
78 | [-1, 1, Conv, [512, 1, 1]], # 32
79 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 33
80 | [[-1,30], 1, Concat, [1]], # 34 cat backbone P4
81 | [-1, 3, C3, [512, False]], # 35
82 |
83 | [-1, 1, Conv, [256, 1, 1]], # 36
84 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 37
85 | [[-1,29], 1, Concat, [1]], # 38 cat backbone P3
86 | [-1, 3, C3, [256, False]], # 39 (P3/8-small)
87 |
88 | [-1, 1, Conv, [256, 3, 2]], # 40
89 | [[-1,36], 1, Concat, [1]], # 41 cat head P4
90 | [-1, 3, C3, [512, False]], # 42 (P4/16-medium)
91 |
92 | [-1, 1, Conv, [512, 3, 2]], # 43
93 | [[-1,32], 1, Concat, [1]], # 44 cat head P5
94 | [-1, 3, C3, [1024, False]], # 45 (P5/32-large)
95 |
96 | [[39, 42, 45], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
97 | ]
98 |
--------------------------------------------------------------------------------
/models/transformer/yolov5l_fusion_transformerx3_llvip.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 1 # number of classes
3 | depth_multiple: 1.00 # model depth multiple
4 | width_multiple: 1.00 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | ######### TransformerBlock One #############
18 | # stream one
19 | [-1, 1, Focus, [64, 3]], # 0-P1/2
20 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
21 | [-1, 3, C3, [128]], # 2-P2/4
22 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
23 | [-1, 9, C3, [256]], # 4-P3/8
24 | # stream two
25 | [-4, 1, Focus, [64, 3]], # 5-P1/2
26 | [-1, 1, Conv, [128, 3, 2]], # 6-P2/4
27 | [-1, 3, C3, [128]], # 7-P2/4
28 | [-1, 1, Conv, [256, 3, 2]], # 8-P3/8
29 | [-1, 9, C3, [256]], # 9-P3/8
30 |
31 |
32 | ######### TransformerBlock Two #############
33 | # transformer fusion
34 | [[4,9], 1, GPT, [256]], # 10-P3/8
35 | [[4,10], 1, Add2, [256,0]], # 11-P3/8 stream one x+trans[0]
36 | [[9,10], 1, Add2, [256,1]], # 12-P3/8 stream two x+trans[1]
37 |
38 |
39 | ######### TransformerBlock Three #############
40 | # stream one
41 | [11, 1, Conv, [512, 3, 2]], # 13-P4/16
42 | [-1, 9, C3, [512]], # 14-P4/16
43 | # stream two
44 | [12, 1, Conv, [512, 3, 2]], # 15-P4/16
45 | [-1, 9, C3, [512]], # 16-P4/16
46 | # transformer fusion
47 | [[14,16], 1, GPT, [512]], # 17-P3/8
48 | [[14,17], 1, Add2, [512,0]], # 18-P3/8 stream one x+trans[0]
49 | [[16,17], 1, Add2, [512,1]], # 19-P3/8 stream two x+trans[1]
50 |
51 |
52 | ######### TransformerBlock Four #############
53 | # stream one
54 | [18, 1, Conv, [1024, 3, 2]], # 20-P5/32
55 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 21-P5/32
56 | [-1, 3, C3, [1024, False]], # 22-P5/32
57 | # stream two
58 | [19, 1, Conv, [1024, 3, 2]], # 23-P5/32
59 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 24-P5/32
60 | [-1, 3, C3, [1024, False]], # 25-P5/32
61 | # transformer fusion
62 | [[22,25], 1, GPT, [1024]], # 26-P5/32
63 | [[22,26], 1, Add2, [1024,0]], # 27-P5/32 stream one x+trans[0]
64 | [[25,26], 1, Add2, [1024,1]], # 28-P5/32 stream two x+trans[1]
65 |
66 |
67 | ######### Add Block #############
68 | [[11,12], 1, Add, [1]], # 29-P3/8 fusion backbone P3
69 | [[18,19], 1, Add, [1]], # 30-P4/16 fusion backbone P4
70 | [[27,28], 1, Add, [1]], # 31-P5/32 fusion backbone P5
71 |
72 | ]
73 |
74 |
75 | # YOLOv5 head
76 | head:
77 | [
78 | [-1, 1, Conv, [512, 1, 1]], # 32
79 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 33
80 | [[-1,30], 1, Concat, [1]], # 34 cat backbone P4
81 | [-1, 3, C3, [512, False]], # 35
82 |
83 | [-1, 1, Conv, [256, 1, 1]], # 36
84 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 37
85 | [[-1,29], 1, Concat, [1]], # 38 cat backbone P3
86 | [-1, 3, C3, [256, False]], # 39 (P3/8-small)
87 |
88 | [-1, 1, Conv, [256, 3, 2]], # 40
89 | [[-1,36], 1, Concat, [1]], # 41 cat head P4
90 | [-1, 3, C3, [512, False]], # 42 (P4/16-medium)
91 |
92 | [-1, 1, Conv, [512, 3, 2]], # 43
93 | [[-1,32], 1, Concat, [1]], # 44 cat head P5
94 | [-1, 3, C3, [1024, False]], # 45 (P5/32-large)
95 |
96 | [[39, 42, 45], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
97 | ]
98 |
--------------------------------------------------------------------------------
/models/transformer/yolov5s_fusion_add_vedai.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 9 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | [-1, 1, Focus, [64, 3]], # 0-P1/2
18 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
19 | [-1, 3, C3, [128]],
20 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
21 | [-1, 9, C3, [256]],
22 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
23 | [-1, 9, C3, [512]],
24 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
25 | [-1, 1, SPP, [1024, [5, 9, 13]]],
26 | [-1, 3, C3, [1024, False]], # 9
27 |
28 | [-4, 1, Focus, [64, 3]], # 10-P1/2
29 | [-1, 1, Conv, [128, 3, 2]], # 11-P2/4
30 | [-1, 3, C3, [128]],
31 | [-1, 1, Conv, [256, 3, 2]], # 13-P3/8
32 | [-1, 9, C3, [256]],
33 | [-1, 1, Conv, [512, 3, 2]], # 15-P4/16
34 | [-1, 9, C3, [512]],
35 | [-1, 1, Conv, [1024, 3, 2]], # 17-P5/32
36 | [-1, 1, SPP, [1024, [5, 9, 13]]],
37 | [-1, 3, C3, [1024, False]], # 19
38 |
39 | ######### Add Block #############
40 | [[4,14], 1, Add, [1]], # 20 two stream fuse
41 | [[6,16], 1, Add, [1]], # 21 two stream fuse
42 | [[9,19], 1, Add, [1]], # 22 two stream fuse
43 | ]
44 |
45 |
46 | # YOLOv5 head
47 | head:
48 | [[-1, 1, Conv, [512, 1, 1]], # 23
49 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 24
50 | [[-1,21], 1, Concat, [1]], # 25 cat backbone P4
51 | [-1, 3, C3, [512, False]], # 26
52 |
53 | [-1, 1, Conv, [256, 1, 1]], # 27
54 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 28
55 | [[-1,20], 1, Concat, [1]], # 29 cat backbone P3
56 | [-1, 3, C3, [256, False]], # 30 (P3/8-small)
57 |
58 | [-1, 1, Conv, [256, 3, 2]], # 31
59 | [[-1,27], 1, Concat, [1]], # 32 cat head P4
60 | [-1, 3, C3, [512, False]], # 33 (P4/16-medium)
61 |
62 | [-1, 1, Conv, [512, 3, 2]], # 34
63 | [[-1,23], 1, Concat, [1]], # 35 cat head P5
64 | [-1, 3, C3, [1024, False]], # 36 (P5/32-large)
65 |
66 | [[30, 33, 36], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
67 | ]
68 |
--------------------------------------------------------------------------------
/models/transformer/yolov5s_fusion_transformer_vedai.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 9 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | ######### TransformerBlock One #############
18 | # stream one
19 | [-1, 1, Focus, [64, 3]], # 0-P1/2
20 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
21 | [-1, 3, C3, [128]], # 2-P2/4
22 | # stream two
23 | [-4, 1, Focus, [64, 3]], # 3-P1/2
24 | [-1, 1, Conv, [128, 3, 2]], # 4-P2/4
25 | [-1, 3, C3, [128]], # 5-P2/4
26 | # transformer fusion
27 | [[2,5], 1, GPT, [128]], # 6-P2/4
28 | [[2,6], 1, Add2, [128,0]], # 7-P2/4 stream one:x+trans[0]
29 | [[5,6], 1, Add2, [128,1]], # 8-P2/4 stream two:x+trans[1]
30 |
31 | ######### TransformerBlock Two #############
32 | # stream one
33 | [7, 1, Conv, [256, 3, 2]], # 9-P3/8
34 | [-1, 9, C3, [256]], # 10-P3/8
35 | # stream two
36 | [8, 1, Conv, [256, 3, 2]], # 11-P3/8
37 | [-1, 9, C3, [256]], # 12-P3/8
38 | # transformer fusion
39 | [[10,12], 1, GPT, [256]], # 13-P3/8
40 | [[10,13], 1, Add2, [256,0]], # 14-P3/8 stream one x+trans[0]
41 | [[12,13], 1, Add2, [256,1]], # 15-P3/8 stream two x+trans[1]
42 |
43 |
44 | ######### TransformerBlock Three #############
45 | # stream one
46 | [14, 1, Conv, [512, 3, 2]], # 16-P4/16
47 | [-1, 9, C3, [512]], # 17-P4/16
48 | # stream two
49 | [15, 1, Conv, [512, 3, 2]], # 18-P4/16
50 | [-1, 9, C3, [512]], # 19-P4/16
51 | # transformer fusion
52 | [[17,19], 1, GPT, [512]], # 20-P3/8
53 | [[17,20], 1, Add2, [512,0]], # 21-P3/8 stream one x+trans[0]
54 | [[19,20], 1, Add2, [512,1]], # 22-P3/8 stream two x+trans[1]
55 |
56 |
57 | ######### TransformerBlock Four #############
58 | # stream one
59 | [-2, 1, Conv, [1024, 3, 2]], # 23-P5/32
60 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 24-P5/32
61 | [-1, 3, C3, [1024, False]], # 25-P5/32
62 | # stream two
63 | [22, 1, Conv, [1024, 3, 2]], # 26-P5/32
64 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 27-P5/32
65 | [-1, 3, C3, [1024, False]], # 28-P5/32
66 | # transformer fusion
67 | [[25,28], 1, GPT, [1024]], # 29-P5/32
68 | [[25,29], 1, Add2, [1024,0]], # 30-P5/32 stream one x+trans[0]
69 | [[28,29], 1, Add2, [1024,1]], # 31-P5/32 stream two x+trans[1]
70 |
71 |
72 | ######### Add Block #############
73 | [[14,15], 1, Add, [1]], # 32-P3/8 fusion backbone P3
74 | [[21,22], 1, Add, [1]], # 33-P4/16 fusion backbone P4
75 | [[30,31], 1, Add, [1]], # 34-P5/32 fusion backbone P5
76 |
77 | ]
78 |
79 |
80 | # YOLOv5 head
81 | head:
82 | [
83 | [-1, 1, Conv, [512, 1, 1]], # 35
84 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 36
85 | [[-1,33], 1, Concat, [1]], # 37 cat backbone P4
86 | [-1, 3, C3, [512, False]], # 38
87 |
88 | [-1, 1, Conv, [256, 1, 1]], # 39
89 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 40
90 | [[-1,32], 1, Concat, [1]], # 41 cat backbone P3
91 | [-1, 3, C3, [256, False]], # 42 (P3/8-small)
92 |
93 | [-1, 1, Conv, [256, 3, 2]], # 43
94 | [[-1,39], 1, Concat, [1]], # 44 cat head P4
95 | [-1, 3, C3, [512, False]], # 45 (P4/16-medium)
96 |
97 | [-1, 1, Conv, [512, 3, 2]], # 46
98 | [[-1,35], 1, Concat, [1]], # 47 cat head P5
99 | [-1, 3, C3, [1024, False]], # 48 (P5/32-large)
100 |
101 | [[42, 45, 48], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
102 | ]
103 |
--------------------------------------------------------------------------------
/models/transformer/yolov5s_fusion_transformerx3_vedai.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 9 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | ######### TransformerBlock One #############
18 | # stream one
19 | [-1, 1, Focus, [64, 3]], # 0-P1/2
20 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
21 | [-1, 3, C3, [128]], # 2-P2/4
22 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
23 | [-1, 9, C3, [256]], # 4-P3/8
24 | # stream two
25 | [-4, 1, Focus, [64, 3]], # 5-P1/2
26 | [-1, 1, Conv, [128, 3, 2]], # 6-P2/4
27 | [-1, 3, C3, [128]], # 7-P2/4
28 | [-1, 1, Conv, [256, 3, 2]], # 8-P3/8
29 | [-1, 9, C3, [256]], # 9-P3/8
30 |
31 |
32 | ######### TransformerBlock Two #############
33 | # transformer fusion
34 | [[4,9], 1, GPT, [256]], # 10-P3/8
35 | [[4,10], 1, Add2, [256,0]], # 11-P3/8 stream one x+trans[0]
36 | [[9,10], 1, Add2, [256,1]], # 12-P3/8 stream two x+trans[1]
37 |
38 |
39 | ######### TransformerBlock Three #############
40 | # stream one
41 | [11, 1, Conv, [512, 3, 2]], # 13-P4/16
42 | [-1, 9, C3, [512]], # 14-P4/16
43 | # stream two
44 | [12, 1, Conv, [512, 3, 2]], # 15-P4/16
45 | [-1, 9, C3, [512]], # 16-P4/16
46 | # transformer fusion
47 | [[14,16], 1, GPT, [512]], # 17-P3/8
48 | [[14,17], 1, Add2, [512,0]], # 18-P3/8 stream one x+trans[0]
49 | [[16,17], 1, Add2, [512,1]], # 19-P3/8 stream two x+trans[1]
50 |
51 |
52 | ######### TransformerBlock Four #############
53 | # stream one
54 | [18, 1, Conv, [1024, 3, 2]], # 20-P5/32
55 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 21-P5/32
56 | [-1, 3, C3, [1024, False]], # 22-P5/32
57 | # stream two
58 | [19, 1, Conv, [1024, 3, 2]], # 23-P5/32
59 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 24-P5/32
60 | [-1, 3, C3, [1024, False]], # 25-P5/32
61 | # transformer fusion
62 | [[22,25], 1, GPT, [1024]], # 26-P5/32
63 | [[22,26], 1, Add2, [1024,0]], # 27-P5/32 stream one x+trans[0]
64 | [[25,26], 1, Add2, [1024,1]], # 28-P5/32 stream two x+trans[1]
65 |
66 |
67 | ######### Add Block #############
68 | [[11,12], 1, Add, [1]], # 29-P3/8 fusion backbone P3
69 | [[18,19], 1, Add, [1]], # 30-P4/16 fusion backbone P4
70 | [[27,28], 1, Add, [1]], # 31-P5/32 fusion backbone P5
71 |
72 | ]
73 |
74 |
75 | # YOLOv5 head
76 | head:
77 | [
78 | [-1, 1, Conv, [512, 1, 1]], # 32
79 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 33
80 | [[-1,30], 1, Concat, [1]], # 34 cat backbone P4
81 | [-1, 3, C3, [512, False]], # 35
82 |
83 | [-1, 1, Conv, [256, 1, 1]], # 36
84 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 37
85 | [[-1,29], 1, Concat, [1]], # 38 cat backbone P3
86 | [-1, 3, C3, [256, False]], # 39 (P3/8-small)
87 |
88 | [-1, 1, Conv, [256, 3, 2]], # 40
89 | [[-1,36], 1, Concat, [1]], # 41 cat head P4
90 | [-1, 3, C3, [512, False]], # 42 (P4/16-medium)
91 |
92 | [-1, 1, Conv, [512, 3, 2]], # 43
93 | [[-1,32], 1, Concat, [1]], # 44 cat head P5
94 | [-1, 3, C3, [1024, False]], # 45 (P5/32-large)
95 |
96 | [[39, 42, 45], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
97 | ]
98 |
--------------------------------------------------------------------------------
/models/transformer/yolov5x_fusion_transformer_FLIR.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 3 # number of classes
3 | depth_multiple: 1.33 # model depth multiple
4 | width_multiple: 1.25 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | ######### TransformerBlock One #############
18 | # stream one
19 | [-1, 1, Focus, [64, 3]], # 0-P1/2
20 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
21 | [-1, 3, C3, [128]], # 2-P2/4
22 | # stream two
23 | [-4, 1, Focus, [64, 3]], # 3-P1/2
24 | [-1, 1, Conv, [128, 3, 2]], # 4-P2/4
25 | [-1, 3, C3, [128]], # 5-P2/4
26 | # transformer fusion
27 | [[2,5], 1, GPT, [128]], # 6-P2/4
28 | [[2,6], 1, Add2, [128,0]], # 7-P2/4 stream one:x+trans[0]
29 | [[5,6], 1, Add2, [128,1]], # 8-P2/4 stream two:x+trans[1]
30 |
31 | ######### TransformerBlock Two #############
32 | # stream one
33 | [7, 1, Conv, [256, 3, 2]], # 9-P3/8
34 | [-1, 9, C3, [256]], # 10-P3/8
35 | # stream two
36 | [8, 1, Conv, [256, 3, 2]], # 11-P3/8
37 | [-1, 9, C3, [256]], # 12-P3/8
38 | # transformer fusion
39 | [[10,12], 1, GPT, [256]], # 13-P3/8
40 | [[10,13], 1, Add2, [256,0]], # 14-P3/8 stream one x+trans[0]
41 | [[12,13], 1, Add2, [256,1]], # 15-P3/8 stream two x+trans[1]
42 |
43 |
44 | ######### TransformerBlock Three #############
45 | # stream one
46 | [14, 1, Conv, [512, 3, 2]], # 16-P4/16
47 | [-1, 9, C3, [512]], # 17-P4/16
48 | # stream two
49 | [15, 1, Conv, [512, 3, 2]], # 18-P4/16
50 | [-1, 9, C3, [512]], # 19-P4/16
51 | # transformer fusion
52 | [[17,19], 1, GPT, [512]], # 20-P3/8
53 | [[17,20], 1, Add2, [512,0]], # 21-P3/8 stream one x+trans[0]
54 | [[19,20], 1, Add2, [512,1]], # 22-P3/8 stream two x+trans[1]
55 |
56 |
57 | ######### TransformerBlock Four #############
58 | # stream one
59 | [-2, 1, Conv, [1024, 3, 2]], # 23-P5/32
60 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 24-P5/32
61 | [-1, 3, C3, [1024, False]], # 25-P5/32
62 | # stream two
63 | [22, 1, Conv, [1024, 3, 2]], # 26-P5/32
64 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 27-P5/32
65 | [-1, 3, C3, [1024, False]], # 28-P5/32
66 | # transformer fusion
67 | [[25,28], 1, GPT, [1024]], # 29-P5/32
68 | [[25,29], 1, Add2, [1024,0]], # 30-P5/32 stream one x+trans[0]
69 | [[28,29], 1, Add2, [1024,1]], # 31-P5/32 stream two x+trans[1]
70 |
71 |
72 | ######### Add Block #############
73 | [[14,15], 1, Add, [1]], # 32-P3/8 fusion backbone P3
74 | [[21,22], 1, Add, [1]], # 33-P4/16 fusion backbone P4
75 | [[30,31], 1, Add, [1]], # 34-P5/32 fusion backbone P5
76 |
77 | ]
78 |
79 |
80 | # YOLOv5 head
81 | head:
82 | [
83 | [-1, 1, Conv, [512, 1, 1]], # 35
84 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 36
85 | [[-1,33], 1, Concat, [1]], # 37 cat backbone P4
86 | [-1, 3, C3, [512, False]], # 38
87 |
88 | [-1, 1, Conv, [256, 1, 1]], # 39
89 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 40
90 | [[-1,32], 1, Concat, [1]], # 41 cat backbone P3
91 | [-1, 3, C3, [256, False]], # 42 (P3/8-small)
92 |
93 | [-1, 1, Conv, [256, 3, 2]], # 43
94 | [[-1,39], 1, Concat, [1]], # 44 cat head P4
95 | [-1, 3, C3, [512, False]], # 45 (P4/16-medium)
96 |
97 | [-1, 1, Conv, [512, 3, 2]], # 46
98 | [[-1,35], 1, Concat, [1]], # 47 cat head P5
99 | [-1, 3, C3, [1024, False]], # 48 (P5/32-large)
100 |
101 | [[42, 45, 48], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
102 | ]
103 |
--------------------------------------------------------------------------------
/models/transformer/yolov5x_fusion_transformer_FLIR_aligned.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 3 # number of classes
3 | depth_multiple: 1.33 # model depth multiple
4 | width_multiple: 1.25 # layer channel multiple
5 |
6 | # anchors
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 | # Two Stream
16 | [
17 | ######### TransformerBlock One #############
18 | # stream one
19 | [-1, 1, Focus, [64, 3]], # 0-P1/2
20 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
21 | [-1, 3, C3, [128]], # 2-P2/4
22 | # stream two
23 | [-4, 1, Focus, [64, 3]], # 3-P1/2
24 | [-1, 1, Conv, [128, 3, 2]], # 4-P2/4
25 | [-1, 3, C3, [128]], # 5-P2/4
26 | # transformer fusion
27 | [[2,5], 1, GPT, [128]], # 6-P2/4
28 | [[2,6], 1, Add2, [128,0]], # 7-P2/4 stream one:x+trans[0]
29 | [[5,6], 1, Add2, [128,1]], # 8-P2/4 stream two:x+trans[1]
30 |
31 | ######### TransformerBlock Two #############
32 | # stream one
33 | [7, 1, Conv, [256, 3, 2]], # 9-P3/8
34 | [-1, 9, C3, [256]], # 10-P3/8
35 | # stream two
36 | [8, 1, Conv, [256, 3, 2]], # 11-P3/8
37 | [-1, 9, C3, [256]], # 12-P3/8
38 | # transformer fusion
39 | [[10,12], 1, GPT, [256]], # 13-P3/8
40 | [[10,13], 1, Add2, [256,0]], # 14-P3/8 stream one x+trans[0]
41 | [[12,13], 1, Add2, [256,1]], # 15-P3/8 stream two x+trans[1]
42 |
43 |
44 | ######### TransformerBlock Three #############
45 | # stream one
46 | [14, 1, Conv, [512, 3, 2]], # 16-P4/16
47 | [-1, 9, C3, [512]], # 17-P4/16
48 | # stream two
49 | [15, 1, Conv, [512, 3, 2]], # 18-P4/16
50 | [-1, 9, C3, [512]], # 19-P4/16
51 | # transformer fusion
52 | [[17,19], 1, GPT, [512]], # 20-P3/8
53 | [[17,20], 1, Add2, [512,0]], # 21-P3/8 stream one x+trans[0]
54 | [[19,20], 1, Add2, [512,1]], # 22-P3/8 stream two x+trans[1]
55 |
56 |
57 | ######### TransformerBlock Four #############
58 | # stream one
59 | [-2, 1, Conv, [1024, 3, 2]], # 23-P5/32
60 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 24-P5/32
61 | [-1, 3, C3, [1024, False]], # 25-P5/32
62 | # stream two
63 | [22, 1, Conv, [1024, 3, 2]], # 26-P5/32
64 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 27-P5/32
65 | [-1, 3, C3, [1024, False]], # 28-P5/32
66 | # transformer fusion
67 | [[25,28], 1, GPT, [1024]], # 29-P5/32
68 | [[25,29], 1, Add2, [1024,0]], # 30-P5/32 stream one x+trans[0]
69 | [[28,29], 1, Add2, [1024,1]], # 31-P5/32 stream two x+trans[1]
70 |
71 |
72 | ######### Add Block #############
73 | [[14,15], 1, Add, [1]], # 32-P3/8 fusion backbone P3
74 | [[21,22], 1, Add, [1]], # 33-P4/16 fusion backbone P4
75 | [[30,31], 1, Add, [1]], # 34-P5/32 fusion backbone P5
76 |
77 | ]
78 |
79 |
80 | # YOLOv5 head
81 | head:
82 | [
83 | [-1, 1, Conv, [512, 1, 1]], # 35
84 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 36
85 | [[-1,33], 1, Concat, [1]], # 37 cat backbone P4
86 | [-1, 3, C3, [512, False]], # 38
87 |
88 | [-1, 1, Conv, [256, 1, 1]], # 39
89 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 40
90 | [[-1,32], 1, Concat, [1]], # 41 cat backbone P3
91 | [-1, 3, C3, [256, False]], # 42 (P3/8-small)
92 |
93 | [-1, 1, Conv, [256, 3, 2]], # 43
94 | [[-1,39], 1, Concat, [1]], # 44 cat head P4
95 | [-1, 3, C3, [512, False]], # 45 (P4/16-medium)
96 |
97 | [-1, 1, Conv, [512, 3, 2]], # 46
98 | [[-1,35], 1, Concat, [1]], # 47 cat head P5
99 | [-1, 3, C3, [1024, False]], # 48 (P5/32-large)
100 |
101 | [[42, 45, 48], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
102 | ]
103 |
--------------------------------------------------------------------------------
/models/yolov5l.yaml:
--------------------------------------------------------------------------------
1 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.0 # model depth multiple
4 | width_multiple: 1.0 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.67 # model depth multiple
4 | width_multiple: 0.75 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 0.33 # model depth multiple
4 | width_multiple: 0.50 # layer channel multiple
5 |
6 | # anchors
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 | # parameters
2 | nc: 80 # number of classes
3 | depth_multiple: 1.33 # model depth multiple
4 | width_multiple: 1.25 # layer channel multiple
5 |
6 | # anchors
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 | 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.8.1
25 | # scikit-learn==0.19.2 # for coreml quantization
26 |
27 | # extras --------------------------------------
28 | thop # FLOPS computation
29 | pycocotools>=2.0 # COCO mAP
30 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/utils/__pycache__/__init__.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/__init__.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/autoanchor.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/autoanchor.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/datasets.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/datasets.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/ds_fusion.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/ds_fusion.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/general.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/general.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/google_utils.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/google_utils.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/gradcam.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/gradcam.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/loss.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/loss.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/metrics.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/metrics.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/plots.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/plots.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/__pycache__/torch_utils.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/__pycache__/torch_utils.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/activations.py:
--------------------------------------------------------------------------------
1 | # Activation functions
2 |
3 | import torch
4 | import torch.nn as nn
5 | import torch.nn.functional as F
6 |
7 |
8 | # SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
9 | class SiLU(nn.Module): # export-friendly version of nn.SiLU()
10 | @staticmethod
11 | def forward(x):
12 | return x * torch.sigmoid(x)
13 |
14 |
15 | class Hardswish(nn.Module): # export-friendly version of nn.Hardswish()
16 | @staticmethod
17 | def forward(x):
18 | # return x * F.hardsigmoid(x) # for torchscript and CoreML
19 | return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
20 |
21 |
22 | # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
23 | class Mish(nn.Module):
24 | @staticmethod
25 | def forward(x):
26 | return x * F.softplus(x).tanh()
27 |
28 |
29 | class MemoryEfficientMish(nn.Module):
30 | class F(torch.autograd.Function):
31 | @staticmethod
32 | def forward(ctx, x):
33 | ctx.save_for_backward(x)
34 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
35 |
36 | @staticmethod
37 | def backward(ctx, grad_output):
38 | x = ctx.saved_tensors[0]
39 | sx = torch.sigmoid(x)
40 | fx = F.softplus(x).tanh()
41 | return grad_output * (fx + x * sx * (1 - fx * fx))
42 |
43 | def forward(self, x):
44 | return self.F.apply(x)
45 |
46 |
47 | # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
48 | class FReLU(nn.Module):
49 | def __init__(self, c1, k=3): # ch_in, kernel
50 | super().__init__()
51 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
52 | self.bn = nn.BatchNorm2d(c1)
53 |
54 | def forward(self, x):
55 | return torch.max(x, self.bn(self.conv(x)))
56 |
57 |
58 | # ACON https://arxiv.org/pdf/2009.04759.pdf ----------------------------------------------------------------------------
59 | class AconC(nn.Module):
60 | r""" ACON activation (activate or not).
61 | AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
62 | according to "Activate or Not: Learning Customized Activation" .
63 | """
64 |
65 | def __init__(self, c1):
66 | super().__init__()
67 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
68 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
69 | self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
70 |
71 | def forward(self, x):
72 | dpx = (self.p1 - self.p2) * x
73 | return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
74 |
75 |
76 | class MetaAconC(nn.Module):
77 | r""" ACON activation (activate or not).
78 | MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
79 | according to "Activate or Not: Learning Customized Activation" .
80 | """
81 |
82 | def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
83 | super().__init__()
84 | c2 = max(r, c1 // r)
85 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
86 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
87 | self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
88 | self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
89 | # self.bn1 = nn.BatchNorm2d(c2)
90 | # self.bn2 = nn.BatchNorm2d(c1)
91 |
92 | def forward(self, x):
93 | y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
94 | # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
95 | # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
96 | beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
97 | dpx = (self.p1 - self.p2) * x
98 | return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
99 |
--------------------------------------------------------------------------------
/utils/autoanchor.py:
--------------------------------------------------------------------------------
1 | # Auto-anchor utils
2 |
3 | import numpy as np
4 | import torch
5 | import yaml
6 | from scipy.cluster.vq import kmeans
7 | from tqdm import tqdm
8 |
9 | from utils.general import colorstr
10 |
11 |
12 | def check_anchor_order(m):
13 | # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
14 | a = m.anchor_grid.prod(-1).view(-1) # anchor area
15 | da = a[-1] - a[0] # delta a
16 | ds = m.stride[-1] - m.stride[0] # delta s
17 | if da.sign() != ds.sign(): # same order
18 | print('Reversing anchor order')
19 | m.anchors[:] = m.anchors.flip(0)
20 | m.anchor_grid[:] = m.anchor_grid.flip(0)
21 |
22 |
23 | def check_anchors(dataset, model, thr=4.0, imgsz=640):
24 | # Check anchor fit to data, recompute if necessary
25 | prefix = colorstr('autoanchor: ')
26 | print(f'\n{prefix}Analyzing anchors... ', end='')
27 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
28 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
29 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
30 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
31 |
32 | def metric(k): # compute metric
33 | r = wh[:, None] / k[None]
34 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
35 | best = x.max(1)[0] # best_x
36 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
37 | bpr = (best > 1. / thr).float().mean() # best possible recall
38 | return bpr, aat
39 |
40 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
41 | bpr, aat = metric(anchors)
42 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
43 | if bpr < 0.98: # threshold to recompute
44 | print('. Attempting to improve anchors, please wait...')
45 | na = m.anchor_grid.numel() // 2 # number of anchors
46 | try:
47 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
48 | except Exception as e:
49 | print(f'{prefix}ERROR: {e}')
50 | new_bpr = metric(anchors)[0]
51 | if new_bpr > bpr: # replace anchors
52 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
53 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
54 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
55 | check_anchor_order(m)
56 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
57 | else:
58 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
59 | print('') # newline
60 |
61 |
62 | def check_anchors_rgb_ir(dataset, model, thr=4.0, imgsz=640):
63 | # Check anchor fit to data, recompute if necessary
64 | prefix = colorstr('autoanchor: ')
65 | print(f'\n{prefix}Analyzing anchors... ', end='')
66 | # m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
67 | m = list(model.model.children())[-1]
68 | print(m)
69 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
70 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
71 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
72 |
73 | def metric(k): # compute metric
74 | r = wh[:, None] / k[None]
75 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
76 | best = x.max(1)[0] # best_x
77 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
78 | bpr = (best > 1. / thr).float().mean() # best possible recall
79 | return bpr, aat
80 |
81 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
82 | bpr, aat = metric(anchors)
83 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
84 | if bpr < 0.98: # threshold to recompute
85 | print('. Attempting to improve anchors, please wait...')
86 | na = m.anchor_grid.numel() // 2 # number of anchors
87 | try:
88 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
89 | except Exception as e:
90 | print(f'{prefix}ERROR: {e}')
91 | new_bpr = metric(anchors)[0]
92 | if new_bpr > bpr: # replace anchors
93 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
94 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
95 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
96 | check_anchor_order(m)
97 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
98 | else:
99 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
100 | print('') # newline
101 |
102 |
103 | def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
104 | """ Creates kmeans-evolved anchors from training dataset
105 |
106 | Arguments:
107 | path: path to dataset *.yaml, or a loaded dataset
108 | n: number of anchors
109 | img_size: image size used for training
110 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
111 | gen: generations to evolve anchors using genetic algorithm
112 | verbose: print all results
113 |
114 | Return:
115 | k: kmeans evolved anchors
116 |
117 | Usage:
118 | from utils.autoanchor import *; _ = kmean_anchors()
119 | """
120 | thr = 1. / thr
121 | prefix = colorstr('autoanchor: ')
122 |
123 | def metric(k, wh): # compute metrics
124 | r = wh[:, None] / k[None]
125 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric
126 | # x = wh_iou(wh, torch.tensor(k)) # iou metric
127 | return x, x.max(1)[0] # x, best_x
128 |
129 | def anchor_fitness(k): # mutation fitness
130 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
131 | return (best * (best > thr).float()).mean() # fitness
132 |
133 | def print_results(k):
134 | k = k[np.argsort(k.prod(1))] # sort small to large
135 | x, best = metric(k, wh0)
136 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
137 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
138 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
139 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')
140 | for i, x in enumerate(k):
141 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
142 | return k
143 |
144 | if isinstance(path, str): # *.yaml file
145 | with open(path) as f:
146 | data_dict = yaml.safe_load(f) # model dict
147 | from utils.datasets import LoadImagesAndLabels
148 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
149 | else:
150 | dataset = path # dataset
151 |
152 | # Get label wh
153 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
154 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
155 |
156 | # Filter
157 | i = (wh0 < 3.0).any(1).sum()
158 | if i:
159 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
160 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
161 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
162 |
163 | # Kmeans calculation
164 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
165 | s = wh.std(0) # sigmas for whitening
166 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
167 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}')
168 | k *= s
169 | wh = torch.tensor(wh, dtype=torch.float32) # filtered
170 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
171 | k = print_results(k)
172 |
173 | # Plot
174 | # k, d = [None] * 20, [None] * 20
175 | # for i in tqdm(range(1, 21)):
176 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
177 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
178 | # ax = ax.ravel()
179 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
180 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
181 | # ax[0].hist(wh[wh[:, 0]<100, 0],400)
182 | # ax[1].hist(wh[wh[:, 1]<100, 1],400)
183 | # fig.savefig('wh.png', dpi=200)
184 |
185 | # Evolve
186 | npr = np.random
187 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
188 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar
189 | for _ in pbar:
190 | v = np.ones(sh)
191 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
192 | v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
193 | kg = (k.copy() * v).clip(min=2.0)
194 | fg = anchor_fitness(kg)
195 | if fg > f:
196 | f, k = fg, kg.copy()
197 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
198 | if verbose:
199 | print_results(k)
200 |
201 | return print_results(k)
202 |
--------------------------------------------------------------------------------
/utils/aws/__init__.py:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/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.launch --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 && sudo chmod -R 777 yolov5
11 | cd yolov5
12 | bash data/scripts/get_coco.sh && echo "Data 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/ds_fusion.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import pandas as pd
3 | import os
4 | import full_arrange
5 |
6 |
7 | def IIM_of_Li(data):
8 |
9 | [evidence_number, data_frame_number] = data.shape
10 | for i in range(evidence_number):
11 | print(str(i) + 'th evidence is ' + str(data[i, :]))
12 |
13 | # 对于识别框架内每一个命题
14 | new_data = np.zeros((evidence_number, data_frame_number + 1))
15 | for k in range(data_frame_number):
16 | # 计算相容矩阵
17 | R = np.zeros((evidence_number, evidence_number))
18 | for i in range(evidence_number):
19 | for j in range(evidence_number):
20 | R[i,j] = (data[i,k] * data[j,k]) / (np.square(data[i,k]) + np.square(data[j,k])) * 2
21 | if np.isnan(R[i,j]):
22 | R[i,j] = 0
23 | print(R)
24 | # 计算绝对相容度
25 | D = np.zeros((evidence_number,1))
26 | for i in range(evidence_number):
27 | D[i,0] = sum(R[i,:]) - 1
28 | # print("+++++++++")
29 | # print(D)
30 | # 计算可信度
31 | W = np.zeros((evidence_number,1))
32 | for i in range(evidence_number):
33 | W[i,0] = D[i,0] / (evidence_number - 1)
34 | # print("-------------")
35 | # print(W)
36 |
37 | # 根据可行度重新确定该证据对应命题的权重,对基本概率指派函数进行处理,得到新的mass函数
38 | for i in range(evidence_number):
39 | new_data[i, k] = data[i, k] * W[i, 0]
40 |
41 | # 提取不确定事件 \Theta
42 | for i in range(evidence_number):
43 | new_data[i, data_frame_number] = 1 - sum(new_data[i, 0:-1])
44 | print(str(i) + 'th new_evidence is ' + str(new_data[i, :]))
45 |
46 | return new_data
47 |
48 |
49 | def IIM_of_sun(data):
50 | [evidence_number, data_frame_number] = data.shape
51 | for i in range(evidence_number):
52 | print(str(i) + 'th evidence is ' + str(data[i, :]))
53 |
54 | #冲突矩阵k_m
55 | k_m = np.zeros((evidence_number,evidence_number))
56 | for i in range(evidence_number):
57 | for j in range(evidence_number):
58 | sum3 = 0
59 | for k in range(data_frame_number):
60 | sum3 = sum3 + data[i,k] * (sum(data[j,:]) - data[j,k])
61 | k_m[i,j] = sum3
62 |
63 | k_sun = 0
64 | for i in range(evidence_number):
65 | for j in range(evidence_number):
66 | if i < j:
67 | k_sun = k_sun + k_m[i,j]
68 | #全部证据可信度
69 | epsilon = k_sun / (evidence_number * (evidence_number - 1) / 2)
70 | #平均概率
71 | q = np.zeros((1, data_frame_number))
72 | for i in range(data_frame_number):
73 | q[0,i] = sum(data[:,i]) / evidence_number
74 |
75 | # print('epsilon为 ' + str(epsilon))
76 | # print('q为 ' + str(q))
77 | return epsilon, q
78 |
79 |
80 |
81 | def DS_fusion_method(data):
82 | new_data = data
83 | [evidence_number, data_frame_number] = new_data.shape
84 | if evidence_number > 3:
85 | print('can not do')
86 | return
87 |
88 | #算出全部组合
89 | combination = full_arrange.full_arrange(range(data_frame_number), evidence_number)
90 | count = 0
91 | for i in combination:
92 | # print(i)
93 | count = count + 1
94 | print('组合一共 ' + str(count) + ' 个')
95 |
96 | #先算归一化因子K
97 | sum1 = 0
98 | for k in combination:
99 | count = 0
100 | small_set = set(k)
101 | for i in small_set:
102 | if i in set(range(data_frame_number - 1)):
103 | count = count + 1
104 | if count >= 2:
105 | multi = 1
106 | for i in range(evidence_number):
107 | multi = multi * new_data[i,k[i]]
108 | sum1 = sum1 + multi
109 | K = 1 - sum1
110 | print('归一化因子K为 ' + str(K))
111 |
112 | #计算每一个特征融合概率
113 | fusion = np.zeros((1,data_frame_number))
114 | for i in range(data_frame_number - 1):
115 | list1 = [i, data_frame_number - 1]
116 | small_combination = full_arrange.full_arrange(list1, evidence_number)
117 | full_info_list = (np.ones((1,evidence_number)) * (data_frame_number - 1)).tolist()[0]
118 | full_info_list = [int(i) for i in full_info_list]
119 | small_combination.remove(full_info_list)
120 | sum2 = 0
121 | for j in small_combination:
122 | multi = 1
123 | for k in range(evidence_number):
124 | multi = multi * new_data[k,j[k]]
125 | sum2 = sum2 + multi
126 | fusion[0,i] = sum2 / K
127 |
128 | multi = 1
129 | for i in range(evidence_number):
130 | multi = multi * new_data[i,data_frame_number - 1]
131 | fusion[0,data_frame_number - 1] = multi / K
132 |
133 | print('DS Fusion ' + str(fusion))
134 | return fusion, K
135 |
136 | def use_DS_method_of_sun(data):
137 | [epsilon, q] = IIM_of_sun(data)
138 | add_line = np.zeros((data.shape[0]))
139 | data_with_all = np.c_[data, add_line]
140 | [fusion, K] = DS_fusion_method(data_with_all)
141 | num = fusion.shape[1]
142 | for i in range(num - 1):
143 | fusion[0, i] = K * fusion[0, i] + (1 - K) * epsilon * q[0, i]
144 |
145 | fusion[0, num - 1] = (1 - K) * (1 - epsilon)
146 | #
147 | # label.append('ALL')
148 | fusion_all = np.c_['0,2', data_with_all, fusion]
149 | fusion_all = pd.DataFrame(data=fusion_all, index=['ProcessData', 'Alert','c', 'Fusion'])
150 | print(fusion_all)
151 | return fusion_all
152 |
153 |
154 |
155 | if __name__ == '__main__':
156 | #测试data
157 | data = [[0.9, 0.1]]
158 | data.append([0.8, 0.2])
159 |
160 | data = np.array(data)
161 |
162 |
163 | # new_data = [[0.2459, 0.1224, 0.24, 0.3917]]
164 | # new_data.append([0, 0.2894, 0.06, 0.6506])
165 | # # new_data.append([0.2951, 0.056, 0.24, 0.4139])
166 | # new_data = np.array(new_data)
167 |
168 | # data_with_all = [[0.5, 0.2, 0.3, 0]]
169 | # data_with_all.append([0, 0.9, 0.1, 0])
170 | # data_with_all.append([0.6, 0.1, 0.3, 0])
171 | # data_with_all = np.array(data_with_all)
172 |
173 | # 测试Li的方法
174 | new_data = IIM_of_Li(data)
175 | DS_fusion_method(new_data)
176 |
177 | # # 测试sun方法
178 | use_DS_method_of_sun(data)
179 |
--------------------------------------------------------------------------------
/utils/flask_rest_api/README.md:
--------------------------------------------------------------------------------
1 | # Flask REST API
2 | [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API created using Flask to expose the `yolov5s` model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/).
3 |
4 | ## Requirements
5 |
6 | [Flask](https://palletsprojects.com/p/flask/) is required. Install with:
7 | ```shell
8 | $ pip install Flask
9 | ```
10 |
11 | ## Run
12 |
13 | After Flask installation run:
14 |
15 | ```shell
16 | $ python3 restapi.py --port 5000
17 | ```
18 |
19 | Then use [curl](https://curl.se/) to perform a request:
20 |
21 | ```shell
22 | $ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s'`
23 | ```
24 |
25 | The model inference results are returned:
26 |
27 | ```shell
28 | [{'class': 0,
29 | 'confidence': 0.8197850585,
30 | 'name': 'person',
31 | 'xmax': 1159.1403808594,
32 | 'xmin': 750.912902832,
33 | 'ymax': 711.2583007812,
34 | 'ymin': 44.0350036621},
35 | {'class': 0,
36 | 'confidence': 0.5667674541,
37 | 'name': 'person',
38 | 'xmax': 1065.5523681641,
39 | 'xmin': 116.0448303223,
40 | 'ymax': 713.8904418945,
41 | 'ymin': 198.4603881836},
42 | {'class': 27,
43 | 'confidence': 0.5661227107,
44 | 'name': 'tie',
45 | 'xmax': 516.7975463867,
46 | 'xmin': 416.6880187988,
47 | 'ymax': 717.0524902344,
48 | 'ymin': 429.2020568848}]
49 | ```
50 |
51 | An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given in `example_request.py`
52 |
--------------------------------------------------------------------------------
/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==18.1
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/google_utils.py:
--------------------------------------------------------------------------------
1 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries
2 |
3 | import os
4 | import platform
5 | import subprocess
6 | import time
7 | from pathlib import Path
8 |
9 | import requests
10 | import torch
11 |
12 |
13 | def gsutil_getsize(url=''):
14 | # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
15 | s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
16 | return eval(s.split(' ')[0]) if len(s) else 0 # bytes
17 |
18 |
19 | def attempt_download(file, repo='ultralytics/yolov5'):
20 | # Attempt file download if does not exist
21 | file = Path(str(file).strip().replace("'", ''))
22 |
23 | if not file.exists():
24 | try:
25 | response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
26 | assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
27 | tag = response['tag_name'] # i.e. 'v1.0'
28 | except: # fallback plan
29 | assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt',
30 | 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
31 | try:
32 | tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
33 | except:
34 | tag = 'v5.0' # current release
35 |
36 | name = file.name
37 | if name in assets:
38 | msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/'
39 | redundant = False # second download option
40 | try: # GitHub
41 | url = f'https://github.com/{repo}/releases/download/{tag}/{name}'
42 | print(f'Downloading {url} to {file}...')
43 | torch.hub.download_url_to_file(url, file)
44 | assert file.exists() and file.stat().st_size > 1E6 # check
45 | except Exception as e: # GCP
46 | print(f'Download error: {e}')
47 | assert redundant, 'No secondary mirror'
48 | url = f'https://storage.googleapis.com/{repo}/ckpt/{name}'
49 | print(f'Downloading {url} to {file}...')
50 | os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights)
51 | finally:
52 | if not file.exists() or file.stat().st_size < 1E6: # check
53 | file.unlink(missing_ok=True) # remove partial downloads
54 | print(f'ERROR: Download failure: {msg}')
55 | print('')
56 | return
57 |
58 |
59 | def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
60 | # Downloads a file from Google Drive. from yolov5.utils.google_utils import *; gdrive_download()
61 | t = time.time()
62 | file = Path(file)
63 | cookie = Path('cookie') # gdrive cookie
64 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
65 | file.unlink(missing_ok=True) # remove existing file
66 | cookie.unlink(missing_ok=True) # remove existing cookie
67 |
68 | # Attempt file download
69 | out = "NUL" if platform.system() == "Windows" else "/dev/null"
70 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
71 | if os.path.exists('cookie'): # large file
72 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
73 | else: # small file
74 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
75 | r = os.system(s) # execute, capture return
76 | cookie.unlink(missing_ok=True) # remove existing cookie
77 |
78 | # Error check
79 | if r != 0:
80 | file.unlink(missing_ok=True) # remove partial
81 | print('Download error ') # raise Exception('Download error')
82 | return r
83 |
84 | # Unzip if archive
85 | if file.suffix == '.zip':
86 | print('unzipping... ', end='')
87 | os.system(f'unzip -q {file}') # unzip
88 | file.unlink() # remove zip to free space
89 |
90 | print(f'Done ({time.time() - t:.1f}s)')
91 | return r
92 |
93 |
94 | def get_token(cookie="./cookie"):
95 | with open(cookie) as f:
96 | for line in f:
97 | if "download" in line:
98 | return line.split()[-1]
99 | return ""
100 |
101 | # def upload_blob(bucket_name, source_file_name, destination_blob_name):
102 | # # Uploads a file to a bucket
103 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
104 | #
105 | # storage_client = storage.Client()
106 | # bucket = storage_client.get_bucket(bucket_name)
107 | # blob = bucket.blob(destination_blob_name)
108 | #
109 | # blob.upload_from_filename(source_file_name)
110 | #
111 | # print('File {} uploaded to {}.'.format(
112 | # source_file_name,
113 | # destination_blob_name))
114 | #
115 | #
116 | # def download_blob(bucket_name, source_blob_name, destination_file_name):
117 | # # Uploads a blob from a bucket
118 | # storage_client = storage.Client()
119 | # bucket = storage_client.get_bucket(bucket_name)
120 | # blob = bucket.blob(source_blob_name)
121 | #
122 | # blob.download_to_filename(destination_file_name)
123 | #
124 | # print('Blob {} downloaded to {}.'.format(
125 | # source_blob_name,
126 | # destination_file_name))
127 |
--------------------------------------------------------------------------------
/utils/gradcam.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding:utf-8 -*-
3 | # Author: Richard Fang
4 | import torch
5 | from torch.autograd import Variable
6 | from torch.autograd import Function
7 | from torchvision import models
8 | from torchvision import utils
9 | import cv2
10 | import sys
11 | import numpy as np
12 | import argparse
13 |
14 | import warnings
15 | warnings.filterwarnings("ignore")
16 |
17 |
18 | def preprocess_image(img):
19 | means=[0.485, 0.456, 0.406]
20 | stds=[0.229, 0.224, 0.225]
21 |
22 | preprocessed_img = img.copy()[:, :, ::-1]
23 | for i in range(3):
24 | preprocessed_img[:, :, i] = preprocessed_img[:, :, i] - means[i]
25 | preprocessed_img[:, :, i] = preprocessed_img[:, :, i] / stds[i]
26 | preprocessed_img = \
27 | np.ascontiguousarray(np.transpose(preprocessed_img, (2, 0, 1)))
28 | preprocessed_img = torch.from_numpy(preprocessed_img)
29 | preprocessed_img.unsqueeze_(0)
30 | input = Variable(preprocessed_img, requires_grad = True)
31 | return input
32 |
33 |
34 | def show_cam_on_image(img, mask, epoch, layer):
35 | heatmap = cv2.applyColorMap(np.uint8(255*mask), cv2.COLORMAP_JET)
36 | heatmap = np.float32(heatmap) / 255
37 | # img = cv2.flip(img, 1)
38 | cam = heatmap + np.float32(img)
39 | cam = cam / np.max(cam)
40 | print(type(cam))
41 | cv2.imwrite("./cam%d_%d.jpg" %(epoch, layer), np.uint8(255 * cam))
42 |
43 |
44 | def calcGradCam(imgpath, feature, epoch, layer):
45 | """
46 |
47 | :param feature: 特征图
48 | :param grad_val: 对应的特征图的梯度
49 | :return
50 | """
51 | # ------------ Image Preprocess ---------------
52 | image_path = imgpath
53 | img = cv2.imread(image_path, 1)
54 | # print(np.shape(img))
55 | img = np.float32(cv2.resize(img, (640, 640))) / 255
56 | input = preprocess_image(img)
57 |
58 | # ------------ GradCam -------------------------
59 | feature = feature.cpu().data.numpy()
60 | print("feature shape", feature.shape)
61 | cam = np.zeros(feature.shape[1:], dtype=np.float32)
62 |
63 | for i in range(feature.shape[0]):
64 | cam += feature[i, :, :]
65 |
66 | cam = np.maximum(cam, 0) # 比较cam的元素与0的大小,<0的都置0
67 | # min = np.min(cam)
68 | # cam -= min
69 | cam = cv2.resize(cam, (640, 640))
70 |
71 | # 归一化 cam
72 | cam = cam - np.min(cam)
73 | cam = cam / np.max(cam)
74 |
75 | print(cam.shape)
76 | # ---------- Show -------------
77 | show_cam_on_image(img, cam, epoch, layer)
78 |
79 | return cam
80 |
81 |
--------------------------------------------------------------------------------
/utils/loss.py:
--------------------------------------------------------------------------------
1 | # Loss functions
2 |
3 | import torch
4 | import torch.nn as nn
5 |
6 | from utils.general import bbox_iou
7 | from utils.torch_utils import is_parallel
8 |
9 |
10 | def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
11 | # return positive, negative label smoothing BCE targets
12 | return 1.0 - 0.5 * eps, 0.5 * eps
13 |
14 |
15 | class BCEBlurWithLogitsLoss(nn.Module):
16 | # BCEwithLogitLoss() with reduced missing label effects.
17 | def __init__(self, alpha=0.05):
18 | super(BCEBlurWithLogitsLoss, self).__init__()
19 | self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
20 | self.alpha = alpha
21 |
22 | def forward(self, pred, true):
23 | loss = self.loss_fcn(pred, true)
24 | pred = torch.sigmoid(pred) # prob from logits
25 | dx = pred - true # reduce only missing label effects
26 | # dx = (pred - true).abs() # reduce missing label and false label effects
27 | alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
28 | loss *= alpha_factor
29 | return loss.mean()
30 |
31 |
32 | class FocalLoss(nn.Module):
33 | # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
34 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
35 | super(FocalLoss, self).__init__()
36 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
37 | self.gamma = gamma
38 | self.alpha = alpha
39 | self.reduction = loss_fcn.reduction
40 | self.loss_fcn.reduction = 'none' # required to apply FL to each element
41 |
42 | def forward(self, pred, true):
43 | loss = self.loss_fcn(pred, true)
44 | # p_t = torch.exp(-loss)
45 | # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
46 |
47 | # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
48 | pred_prob = torch.sigmoid(pred) # prob from logits
49 | p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
50 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
51 | modulating_factor = (1.0 - p_t) ** self.gamma
52 | loss *= alpha_factor * modulating_factor
53 |
54 | if self.reduction == 'mean':
55 | return loss.mean()
56 | elif self.reduction == 'sum':
57 | return loss.sum()
58 | else: # 'none'
59 | return loss
60 |
61 |
62 | class QFocalLoss(nn.Module):
63 | # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
64 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
65 | super(QFocalLoss, self).__init__()
66 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
67 | self.gamma = gamma
68 | self.alpha = alpha
69 | self.reduction = loss_fcn.reduction
70 | self.loss_fcn.reduction = 'none' # required to apply FL to each element
71 |
72 | def forward(self, pred, true):
73 | loss = self.loss_fcn(pred, true)
74 |
75 | pred_prob = torch.sigmoid(pred) # prob from logits
76 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
77 | modulating_factor = torch.abs(true - pred_prob) ** self.gamma
78 | loss *= alpha_factor * modulating_factor
79 |
80 | if self.reduction == 'mean':
81 | return loss.mean()
82 | elif self.reduction == 'sum':
83 | return loss.sum()
84 | else: # 'none'
85 | return loss
86 |
87 |
88 | class ComputeLoss:
89 | # Compute losses
90 | def __init__(self, model, autobalance=False):
91 | super(ComputeLoss, self).__init__()
92 | device = next(model.parameters()).device # get model device
93 | h = model.hyp # hyperparameters
94 |
95 | # Define criteria
96 | BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
97 | BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
98 |
99 | # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
100 | self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
101 |
102 | # Focal loss
103 | g = h['fl_gamma'] # focal loss gamma
104 | if g > 0:
105 | BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
106 |
107 | det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
108 | self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
109 | self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
110 | self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance
111 | for k in 'na', 'nc', 'nl', 'anchors':
112 | setattr(self, k, getattr(det, k))
113 |
114 | def __call__(self, p, targets): # predictions, targets, model
115 | device = targets.device
116 | lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device)
117 | tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
118 |
119 | # Losses
120 | for i, pi in enumerate(p): # layer index, layer predictions
121 | b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
122 | tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
123 |
124 | n = b.shape[0] # number of targets
125 | if n:
126 | ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
127 |
128 | # Regression
129 | pxy = ps[:, :2].sigmoid() * 2. - 0.5
130 | pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i]
131 | pbox = torch.cat((pxy, pwh), 1) # predicted box
132 | iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
133 | lbox += (1.0 - iou).mean() # iou loss
134 |
135 | # Objectness
136 | tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio
137 |
138 | # Classification
139 | if self.nc > 1: # cls loss (only if multiple classes)
140 | t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets
141 | t[range(n), tcls[i]] = self.cp
142 | lcls += self.BCEcls(ps[:, 5:], t) # BCE
143 |
144 | # Append targets to text file
145 | # with open('targets.txt', 'a') as file:
146 | # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
147 |
148 | obji = self.BCEobj(pi[..., 4], tobj)
149 | lobj += obji * self.balance[i] # obj loss
150 | if self.autobalance:
151 | self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
152 |
153 | if self.autobalance:
154 | self.balance = [x / self.balance[self.ssi] for x in self.balance]
155 | lbox *= self.hyp['box']
156 | lobj *= self.hyp['obj']
157 | lcls *= self.hyp['cls']
158 | bs = tobj.shape[0] # batch size
159 |
160 | loss = lbox + lobj + lcls
161 | return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach()
162 |
163 | def build_targets(self, p, targets):
164 | # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
165 | na, nt = self.na, targets.shape[0] # number of anchors, targets
166 | tcls, tbox, indices, anch = [], [], [], []
167 | gain = torch.ones(7, device=targets.device) # normalized to gridspace gain
168 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
169 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
170 |
171 | g = 0.5 # bias
172 | off = torch.tensor([[0, 0],
173 | [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
174 | # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
175 | ], device=targets.device).float() * g # offsets
176 |
177 | for i in range(self.nl):
178 | anchors = self.anchors[i]
179 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain
180 |
181 | # Match targets to anchors
182 | t = targets * gain
183 | if nt:
184 | # Matches
185 | r = t[:, :, 4:6] / anchors[:, None] # wh ratio
186 | j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
187 | # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
188 | t = t[j] # filter
189 |
190 | # Offsets
191 | gxy = t[:, 2:4] # grid xy
192 | gxi = gain[[2, 3]] - gxy # inverse
193 | j, k = ((gxy % 1. < g) & (gxy > 1.)).T
194 | l, m = ((gxi % 1. < g) & (gxi > 1.)).T
195 | j = torch.stack((torch.ones_like(j), j, k, l, m))
196 | t = t.repeat((5, 1, 1))[j]
197 | offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
198 | else:
199 | t = targets[0]
200 | offsets = 0
201 |
202 | # Define
203 | b, c = t[:, :2].long().T # image, class
204 | gxy = t[:, 2:4] # grid xy
205 | gwh = t[:, 4:6] # grid wh
206 | gij = (gxy - offsets).long()
207 | gi, gj = gij.T # grid xy indices
208 |
209 | # Append
210 | a = t[:, 6].long() # anchor indices
211 | indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
212 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
213 | anch.append(anchors[a]) # anchors
214 | tcls.append(c) # class
215 |
216 | return tcls, tbox, indices, anch
217 |
--------------------------------------------------------------------------------
/utils/metrics.py:
--------------------------------------------------------------------------------
1 | # Model validation metrics
2 |
3 | from pathlib import Path
4 |
5 | import matplotlib.pyplot as plt
6 | import numpy as np
7 | import torch
8 |
9 | from . import general
10 |
11 |
12 | def fitness(x):
13 | # Model fitness as a weighted combination of metrics
14 | w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
15 | return (x[:, :4] * w).sum(1)
16 |
17 |
18 | def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()):
19 | """ Compute the average precision, given the recall and precision curves.
20 | Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
21 | # Arguments
22 | tp: True positives (nparray, nx1 or nx10).
23 | conf: Objectness value from 0-1 (nparray).
24 | pred_cls: Predicted object classes (nparray).
25 | target_cls: True object classes (nparray).
26 | plot: Plot precision-recall curve at mAP@0.5
27 | save_dir: Plot save directory
28 | # Returns
29 | The average precision as computed in py-faster-rcnn.
30 | """
31 |
32 | # Sort by objectness
33 | i = np.argsort(-conf)
34 | tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
35 |
36 | # Find unique classes
37 | unique_classes = np.unique(target_cls)
38 | nc = unique_classes.shape[0] # number of classes, number of detections
39 |
40 | # Create Precision-Recall curve and compute AP for each class
41 | px, py = np.linspace(0, 1, 1000), [] # for plotting
42 | ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
43 | for ci, c in enumerate(unique_classes):
44 | i = pred_cls == c
45 | n_l = (target_cls == c).sum() # number of labels
46 | n_p = i.sum() # number of predictions
47 |
48 | if n_p == 0 or n_l == 0:
49 | continue
50 | else:
51 | # Accumulate FPs and TPs
52 | fpc = (1 - tp[i]).cumsum(0)
53 | tpc = tp[i].cumsum(0)
54 |
55 | # Recall
56 | recall = tpc / (n_l + 1e-16) # recall curve
57 | r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
58 |
59 | # Precision
60 | precision = tpc / (tpc + fpc) # precision curve
61 | p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
62 |
63 | # AP from recall-precision curve
64 | for j in range(tp.shape[1]):
65 | ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
66 | if plot and j == 0:
67 | py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
68 |
69 | # Compute F1 (harmonic mean of precision and recall)
70 | f1 = 2 * p * r / (p + r + 1e-16)
71 | if plot:
72 | plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
73 | plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
74 | plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
75 | plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
76 |
77 | i = f1.mean(0).argmax() # max F1 index
78 | # print("p[:, i]", p[:, i])
79 | # print("p[:, i]", p[:, i].shape())
80 | return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32')
81 |
82 |
83 | def compute_ap(recall, precision):
84 | """ Compute the average precision, given the recall and precision curves
85 | # Arguments
86 | recall: The recall curve (list)
87 | precision: The precision curve (list)
88 | # Returns
89 | Average precision, precision curve, recall curve
90 | """
91 |
92 | # Append sentinel values to beginning and end
93 | mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01]))
94 | mpre = np.concatenate(([1.], precision, [0.]))
95 |
96 | # Compute the precision envelope
97 | mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
98 |
99 | # Integrate area under curve
100 | method = 'interp' # methods: 'continuous', 'interp'
101 | if method == 'interp':
102 | x = np.linspace(0, 1, 101) # 101-point interp (COCO)
103 | ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
104 | else: # 'continuous'
105 | i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
106 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
107 |
108 | return ap, mpre, mrec
109 |
110 |
111 | class ConfusionMatrix:
112 | # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
113 | def __init__(self, nc, conf=0.25, iou_thres=0.45):
114 | self.matrix = np.zeros((nc + 1, nc + 1))
115 | self.nc = nc # number of classes
116 | self.conf = conf
117 | self.iou_thres = iou_thres
118 |
119 | def process_batch(self, detections, labels):
120 | """
121 | Return intersection-over-union (Jaccard index) of boxes.
122 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
123 | Arguments:
124 | detections (Array[N, 6]), x1, y1, x2, y2, conf, class
125 | labels (Array[M, 5]), class, x1, y1, x2, y2
126 | Returns:
127 | None, updates confusion matrix accordingly
128 | """
129 | detections = detections[detections[:, 4] > self.conf]
130 | gt_classes = labels[:, 0].int()
131 | detection_classes = detections[:, 5].int()
132 | iou = general.box_iou(labels[:, 1:], detections[:, :4])
133 |
134 | x = torch.where(iou > self.iou_thres)
135 | if x[0].shape[0]:
136 | matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
137 | if x[0].shape[0] > 1:
138 | matches = matches[matches[:, 2].argsort()[::-1]]
139 | matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
140 | matches = matches[matches[:, 2].argsort()[::-1]]
141 | matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
142 | else:
143 | matches = np.zeros((0, 3))
144 |
145 | n = matches.shape[0] > 0
146 | m0, m1, _ = matches.transpose().astype(np.int16)
147 | for i, gc in enumerate(gt_classes):
148 | j = m0 == i
149 | if n and sum(j) == 1:
150 | self.matrix[detection_classes[m1[j]], gc] += 1 # correct
151 | else:
152 | self.matrix[self.nc, gc] += 1 # background FP
153 |
154 | if n:
155 | for i, dc in enumerate(detection_classes):
156 | if not any(m1 == i):
157 | self.matrix[dc, self.nc] += 1 # background FN
158 |
159 | def matrix(self):
160 | return self.matrix
161 |
162 | def plot(self, save_dir='', names=()):
163 | try:
164 | import seaborn as sn
165 |
166 | array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize
167 | array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
168 |
169 | fig = plt.figure(figsize=(12, 9), tight_layout=True)
170 | sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
171 | labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
172 | sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
173 | xticklabels=names + ['background FP'] if labels else "auto",
174 | yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
175 | fig.axes[0].set_xlabel('True')
176 | fig.axes[0].set_ylabel('Predicted')
177 | fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
178 | except Exception as e:
179 | pass
180 |
181 | def print(self):
182 | for i in range(self.nc + 1):
183 | print(' '.join(map(str, self.matrix[i])))
184 |
185 |
186 | # Plots ----------------------------------------------------------------------------------------------------------------
187 |
188 | def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
189 | # Precision-recall curve
190 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
191 | py = np.stack(py, axis=1)
192 |
193 | if 0 < len(names) < 21: # display per-class legend if < 21 classes
194 | for i, y in enumerate(py.T):
195 | ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
196 | else:
197 | ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
198 |
199 | ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
200 | ax.set_xlabel('Recall')
201 | ax.set_ylabel('Precision')
202 | ax.set_xlim(0, 1)
203 | ax.set_ylim(0, 1)
204 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
205 | fig.savefig(Path(save_dir), dpi=250)
206 |
207 |
208 | def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
209 | # Metric-confidence curve
210 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
211 |
212 | if 0 < len(names) < 21: # display per-class legend if < 21 classes
213 | for i, y in enumerate(py):
214 | ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
215 | else:
216 | ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
217 |
218 | y = py.mean(0)
219 | ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
220 | ax.set_xlabel(xlabel)
221 | ax.set_ylabel(ylabel)
222 | ax.set_xlim(0, 1)
223 | ax.set_ylim(0, 1)
224 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
225 | fig.savefig(Path(save_dir), dpi=250)
226 |
--------------------------------------------------------------------------------
/utils/torch_utils.py:
--------------------------------------------------------------------------------
1 | # YOLOv5 PyTorch utils
2 |
3 | import datetime
4 | import logging
5 | import math
6 | import os
7 | import platform
8 | import subprocess
9 | import time
10 | from contextlib import contextmanager
11 | from copy import deepcopy
12 | from pathlib import Path
13 |
14 | import torch
15 | import torch.backends.cudnn as cudnn
16 | import torch.nn as nn
17 | import torch.nn.functional as F
18 | import torchvision
19 |
20 | try:
21 | import thop # for FLOPS computation
22 | except ImportError:
23 | thop = None
24 | logger = logging.getLogger(__name__)
25 |
26 |
27 | @contextmanager
28 | def torch_distributed_zero_first(local_rank: int):
29 | """
30 | Decorator to make all processes in distributed training wait for each local_master to do something.
31 | """
32 | if local_rank not in [-1, 0]:
33 | torch.distributed.barrier()
34 | yield
35 | if local_rank == 0:
36 | torch.distributed.barrier()
37 |
38 |
39 | def init_torch_seeds(seed=0):
40 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
41 | torch.manual_seed(seed)
42 | if seed == 0: # slower, more reproducible
43 | cudnn.benchmark, cudnn.deterministic = False, True
44 | else: # faster, less reproducible
45 | cudnn.benchmark, cudnn.deterministic = True, False
46 |
47 |
48 | def date_modified(path=__file__):
49 | # return human-readable file modification date, i.e. '2021-3-26'
50 | t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
51 | return f'{t.year}-{t.month}-{t.day}'
52 |
53 |
54 | def git_describe(path=Path(__file__).parent): # path must be a directory
55 | # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
56 | s = f'git -C {path} describe --tags --long --always'
57 | try:
58 | return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
59 | except subprocess.CalledProcessError as e:
60 | return '' # not a git repository
61 |
62 |
63 | def select_device(device='', batch_size=None):
64 | # device = 'cpu' or '0' or '0,1,2,3'
65 | s = f'YOLOv5 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
66 | cpu = device.lower() == 'cpu'
67 | if cpu:
68 | os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
69 | elif device: # non-cpu device requested
70 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
71 | assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
72 |
73 | cuda = not cpu and torch.cuda.is_available()
74 | if cuda:
75 | n = torch.cuda.device_count()
76 | if n > 1 and batch_size: # check that batch_size is compatible with device_count
77 | assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
78 | space = ' ' * len(s)
79 | for i, d in enumerate(device.split(',') if device else range(n)):
80 | p = torch.cuda.get_device_properties(i)
81 | s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
82 | else:
83 | s += 'CPU\n'
84 |
85 | logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
86 | return torch.device('cuda:0' if cuda else 'cpu')
87 |
88 |
89 | def time_synchronized():
90 | # pytorch-accurate time
91 | if torch.cuda.is_available():
92 | torch.cuda.synchronize()
93 | return time.time()
94 |
95 |
96 | def profile(x, ops, n=100, device=None):
97 | # profile a pytorch module or list of modules. Example usage:
98 | # x = torch.randn(16, 3, 640, 640) # input
99 | # m1 = lambda x: x * torch.sigmoid(x)
100 | # m2 = nn.SiLU()
101 | # profile(x, [m1, m2], n=100) # profile speed over 100 iterations
102 |
103 | device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
104 | x = x.to(device)
105 | x.requires_grad = True
106 | print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '')
107 | print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}")
108 | for m in ops if isinstance(ops, list) else [ops]:
109 | m = m.to(device) if hasattr(m, 'to') else m # device
110 | m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type
111 | dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward
112 | try:
113 | flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS
114 | except:
115 | flops = 0
116 |
117 | for _ in range(n):
118 | t[0] = time_synchronized()
119 | y = m(x)
120 | t[1] = time_synchronized()
121 | try:
122 | _ = y.sum().backward()
123 | t[2] = time_synchronized()
124 | except: # no backward method
125 | t[2] = float('nan')
126 | dtf += (t[1] - t[0]) * 1000 / n # ms per op forward
127 | dtb += (t[2] - t[1]) * 1000 / n # ms per op backward
128 |
129 | s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'
130 | s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'
131 | p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters
132 | print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}')
133 |
134 |
135 | def is_parallel(model):
136 | return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
137 |
138 |
139 | def intersect_dicts(da, db, exclude=()):
140 | # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
141 | return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
142 |
143 |
144 | def initialize_weights(model):
145 | for m in model.modules():
146 | t = type(m)
147 | if t is nn.Conv2d:
148 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
149 | elif t is nn.BatchNorm2d:
150 | m.eps = 1e-3
151 | m.momentum = 0.03
152 | elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
153 | m.inplace = True
154 |
155 |
156 | def find_modules(model, mclass=nn.Conv2d):
157 | # Finds layer indices matching module class 'mclass'
158 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
159 |
160 |
161 | def sparsity(model):
162 | # Return global model sparsity
163 | a, b = 0., 0.
164 | for p in model.parameters():
165 | a += p.numel()
166 | b += (p == 0).sum()
167 | return b / a
168 |
169 |
170 | def prune(model, amount=0.3):
171 | # Prune model to requested global sparsity
172 | import torch.nn.utils.prune as prune
173 | print('Pruning model... ', end='')
174 | for name, m in model.named_modules():
175 | if isinstance(m, nn.Conv2d):
176 | prune.l1_unstructured(m, name='weight', amount=amount) # prune
177 | prune.remove(m, 'weight') # make permanent
178 | print(' %.3g global sparsity' % sparsity(model))
179 |
180 |
181 | def fuse_conv_and_bn(conv, bn):
182 | # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
183 | fusedconv = nn.Conv2d(conv.in_channels,
184 | conv.out_channels,
185 | kernel_size=conv.kernel_size,
186 | stride=conv.stride,
187 | padding=conv.padding,
188 | groups=conv.groups,
189 | bias=True).requires_grad_(False).to(conv.weight.device)
190 |
191 | # prepare filters
192 | w_conv = conv.weight.clone().view(conv.out_channels, -1)
193 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
194 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
195 |
196 | # prepare spatial bias
197 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
198 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
199 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
200 |
201 | return fusedconv
202 |
203 |
204 | def model_info(model, verbose=False, img_size=640):
205 | # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
206 | n_p = sum(x.numel() for x in model.parameters()) # number parameters
207 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
208 | if verbose:
209 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
210 | for i, (name, p) in enumerate(model.named_parameters()):
211 | name = name.replace('module_list.', '')
212 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
213 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
214 |
215 | try: # FLOPS
216 | from thop import profile
217 | stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32
218 | img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input
219 | flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS
220 | img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
221 | fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS
222 | except (ImportError, Exception):
223 | fs = ''
224 |
225 | logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
226 |
227 |
228 | def load_classifier(name='resnet101', n=2):
229 | # Loads a pretrained model reshaped to n-class output
230 | model = torchvision.models.__dict__[name](pretrained=True)
231 |
232 | # ResNet model properties
233 | # input_size = [3, 224, 224]
234 | # input_space = 'RGB'
235 | # input_range = [0, 1]
236 | # mean = [0.485, 0.456, 0.406]
237 | # std = [0.229, 0.224, 0.225]
238 |
239 | # Reshape output to n classes
240 | filters = model.fc.weight.shape[1]
241 | model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
242 | model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
243 | model.fc.out_features = n
244 | return model
245 |
246 |
247 | def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
248 | # scales img(bs,3,y,x) by ratio constrained to gs-multiple
249 | if ratio == 1.0:
250 | return img
251 | else:
252 | h, w = img.shape[2:]
253 | s = (int(h * ratio), int(w * ratio)) # new size
254 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
255 | if not same_shape: # pad/crop img
256 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
257 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
258 |
259 |
260 | def copy_attr(a, b, include=(), exclude=()):
261 | # Copy attributes from b to a, options to only include [...] and to exclude [...]
262 | for k, v in b.__dict__.items():
263 | if (len(include) and k not in include) or k.startswith('_') or k in exclude:
264 | continue
265 | else:
266 | setattr(a, k, v)
267 |
268 |
269 | class ModelEMA:
270 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
271 | Keep a moving average of everything in the model state_dict (parameters and buffers).
272 | This is intended to allow functionality like
273 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
274 | A smoothed version of the weights is necessary for some training schemes to perform well.
275 | This class is sensitive where it is initialized in the sequence of model init,
276 | GPU assignment and distributed training wrappers.
277 | """
278 |
279 | def __init__(self, model, decay=0.9999, updates=0):
280 | # Create EMA
281 | self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
282 | # if next(model.parameters()).device.type != 'cpu':
283 | # self.ema.half() # FP16 EMA
284 | self.updates = updates # number of EMA updates
285 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
286 | for p in self.ema.parameters():
287 | p.requires_grad_(False)
288 |
289 | def update(self, model):
290 | # Update EMA parameters
291 | with torch.no_grad():
292 | self.updates += 1
293 | d = self.decay(self.updates)
294 |
295 | msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
296 | for k, v in self.ema.state_dict().items():
297 | if v.dtype.is_floating_point:
298 | v *= d
299 | v += (1. - d) * msd[k].detach()
300 |
301 | def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
302 | # Update EMA attributes
303 | copy_attr(self.ema, model, include, exclude)
304 |
--------------------------------------------------------------------------------
/utils/wandb_logging/__init__.py:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/utils/wandb_logging/__pycache__/__init__.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/wandb_logging/__pycache__/__init__.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/wandb_logging/__pycache__/wandb_utils.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/utils/wandb_logging/__pycache__/wandb_utils.cpython-37.pyc
--------------------------------------------------------------------------------
/utils/wandb_logging/log_dataset.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 | import yaml
4 |
5 | from wandb_utils import WandbLogger
6 |
7 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
8 |
9 |
10 | def create_dataset_artifact(opt):
11 | with open(opt.data) as f:
12 | data = yaml.safe_load(f) # data dict
13 | logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation')
14 |
15 |
16 | if __name__ == '__main__':
17 | parser = argparse.ArgumentParser()
18 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
19 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
20 | parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project')
21 | opt = parser.parse_args()
22 | opt.resume = False # Explicitly disallow resume check for dataset upload job
23 |
24 | create_dataset_artifact(opt)
25 |
--------------------------------------------------------------------------------
/video/demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/video/demo.gif
--------------------------------------------------------------------------------
/video/demo1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DocF/multispectral-object-detection/fb591c9b163177c0e950db08e213e24ddc912d41/video/demo1.gif
--------------------------------------------------------------------------------