├── .gitattributes ├── .gitignore ├── .vscode └── sftp.json ├── Dockerfile ├── LICENSE ├── README.md ├── convertTrainLabel.py ├── data ├── coco.yaml ├── coco128.yaml ├── get_coco2017.sh ├── get_voc.sh └── voc.yaml ├── detect.py ├── hubconf.py ├── models ├── __init__.py ├── __pycache__ │ ├── common.cpython-36.pyc │ ├── common.cpython-38.pyc │ ├── experimental.cpython-36.pyc │ ├── experimental.cpython-38.pyc │ ├── yolo.cpython-36.pyc │ └── yolo.cpython-38.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 │ ├── yolov5s6.yaml │ └── yolov5x6.yaml ├── yolo.py ├── yolov5-mobilenet.yaml ├── yolov5l.yaml ├── yolov5m.yaml ├── yolov5s.yaml ├── yolov5s1.yaml ├── yolov5x.yaml └── yolov5x_se.yaml ├── process_data_yolo.py ├── requirements.txt ├── run.sh ├── submit.py ├── test.py ├── train.py ├── train.sh ├── tutorial.ipynb ├── utils ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-36.pyc │ ├── __init__.cpython-38.pyc │ ├── datasets.cpython-36.pyc │ ├── datasets.cpython-38.pyc │ ├── google_utils.cpython-36.pyc │ ├── google_utils.cpython-38.pyc │ ├── torch_utils.cpython-36.pyc │ ├── torch_utils.cpython-38.pyc │ ├── utils.cpython-36.pyc │ └── utils.cpython-38.pyc ├── activations.py ├── autoanchor.py ├── datasets.py ├── general.py ├── google_app_engine │ ├── Dockerfile │ ├── additional_requirements.txt │ └── app.yaml ├── google_utils.py ├── loss.py ├── metrics.py ├── plots.py ├── torch_utils.py ├── utils.py └── wandb_logging │ ├── __init__.py │ ├── log_dataset.py │ └── wandb_utils.py └── weights └── download_weights.sh /.gitattributes: -------------------------------------------------------------------------------- 1 | # this drop notebooks from GitHub language stats 2 | *.ipynb linguist-vendored 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Repo-specific GitIgnore ---------------------------------------------------------------------------------------------- 2 | *.jpg 3 | *.jpeg 4 | *.png 5 | *.bmp 6 | *.tif 7 | *.tiff 8 | *.heic 9 | *.JPG 10 | *.JPEG 11 | *.PNG 12 | *.BMP 13 | *.TIF 14 | *.TIFF 15 | *.HEIC 16 | *.mp4 17 | *.mov 18 | *.MOV 19 | *.avi 20 | *.data 21 | *.json 22 | 23 | *.cfg 24 | !cfg/yolov3*.cfg 25 | 26 | storage.googleapis.com 27 | runs/* 28 | data/* 29 | !data/images/zidane.jpg 30 | !data/images/bus.jpg 31 | !data/coco.names 32 | !data/coco_paper.names 33 | !data/coco.data 34 | !data/coco_*.data 35 | !data/coco_*.txt 36 | !data/trainvalno5k.shapes 37 | !data/*.sh 38 | 39 | pycocotools/* 40 | results*.txt 41 | gcp_test*.sh 42 | 43 | # Datasets ------------------------------------------------------------------------------------------------------------- 44 | coco/ 45 | coco128/ 46 | VOC/ 47 | 48 | # MATLAB GitIgnore ----------------------------------------------------------------------------------------------------- 49 | *.m~ 50 | *.mat 51 | !targets*.mat 52 | 53 | # Neural Network weights ----------------------------------------------------------------------------------------------- 54 | *.weights 55 | *.pt 56 | *.onnx 57 | *.mlmodel 58 | *.torchscript 59 | darknet53.conv.74 60 | yolov3-tiny.conv.15 61 | 62 | # GitHub Python GitIgnore ---------------------------------------------------------------------------------------------- 63 | # Byte-compiled / optimized / DLL files 64 | __pycache__/ 65 | *.py[cod] 66 | *$py.class 67 | 68 | # C extensions 69 | *.so 70 | 71 | # Distribution / packaging 72 | .Python 73 | env/ 74 | build/ 75 | develop-eggs/ 76 | dist/ 77 | downloads/ 78 | eggs/ 79 | .eggs/ 80 | lib/ 81 | lib64/ 82 | parts/ 83 | sdist/ 84 | var/ 85 | wheels/ 86 | *.egg-info/ 87 | wandb/ 88 | .installed.cfg 89 | *.egg 90 | 91 | 92 | # PyInstaller 93 | # Usually these files are written by a python script from a template 94 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 95 | *.manifest 96 | *.spec 97 | 98 | # Installer logs 99 | pip-log.txt 100 | pip-delete-this-directory.txt 101 | 102 | # Unit test / coverage reports 103 | htmlcov/ 104 | .tox/ 105 | .coverage 106 | .coverage.* 107 | .cache 108 | nosetests.xml 109 | coverage.xml 110 | *.cover 111 | .hypothesis/ 112 | 113 | # Translations 114 | *.mo 115 | *.pot 116 | 117 | # Django stuff: 118 | *.log 119 | local_settings.py 120 | 121 | # Flask stuff: 122 | instance/ 123 | .webassets-cache 124 | 125 | # Scrapy stuff: 126 | .scrapy 127 | 128 | # Sphinx documentation 129 | docs/_build/ 130 | 131 | # PyBuilder 132 | target/ 133 | 134 | # Jupyter Notebook 135 | .ipynb_checkpoints 136 | 137 | # pyenv 138 | .python-version 139 | 140 | # celery beat schedule file 141 | celerybeat-schedule 142 | 143 | # SageMath parsed files 144 | *.sage.py 145 | 146 | # dotenv 147 | .env 148 | 149 | # virtualenv 150 | .venv* 151 | venv*/ 152 | ENV*/ 153 | 154 | # Spyder project settings 155 | .spyderproject 156 | .spyproject 157 | 158 | # Rope project settings 159 | .ropeproject 160 | 161 | # mkdocs documentation 162 | /site 163 | 164 | # mypy 165 | .mypy_cache/ 166 | 167 | 168 | # https://github.com/github/gitignore/blob/master/Global/macOS.gitignore ----------------------------------------------- 169 | 170 | # General 171 | .DS_Store 172 | .AppleDouble 173 | .LSOverride 174 | 175 | # Icon must end with two \r 176 | Icon 177 | Icon? 178 | 179 | # Thumbnails 180 | ._* 181 | 182 | # Files that might appear in the root of a volume 183 | .DocumentRevisions-V100 184 | .fseventsd 185 | .Spotlight-V100 186 | .TemporaryItems 187 | .Trashes 188 | .VolumeIcon.icns 189 | .com.apple.timemachine.donotpresent 190 | 191 | # Directories potentially created on remote AFP share 192 | .AppleDB 193 | .AppleDesktop 194 | Network Trash Folder 195 | Temporary Items 196 | .apdisk 197 | 198 | 199 | # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore 200 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 201 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 202 | 203 | # User-specific stuff: 204 | .idea/* 205 | .idea/**/workspace.xml 206 | .idea/**/tasks.xml 207 | .idea/dictionaries 208 | .html # Bokeh Plots 209 | .pg # TensorFlow Frozen Graphs 210 | .avi # videos 211 | 212 | # Sensitive or high-churn files: 213 | .idea/**/dataSources/ 214 | .idea/**/dataSources.ids 215 | .idea/**/dataSources.local.xml 216 | .idea/**/sqlDataSources.xml 217 | .idea/**/dynamic.xml 218 | .idea/**/uiDesigner.xml 219 | 220 | # Gradle: 221 | .idea/**/gradle.xml 222 | .idea/**/libraries 223 | 224 | # CMake 225 | cmake-build-debug/ 226 | cmake-build-release/ 227 | 228 | # Mongo Explorer plugin: 229 | .idea/**/mongoSettings.xml 230 | 231 | ## File-based project format: 232 | *.iws 233 | 234 | ## Plugin-specific files: 235 | 236 | # IntelliJ 237 | out/ 238 | 239 | # mpeltonen/sbt-idea plugin 240 | .idea_modules/ 241 | 242 | # JIRA plugin 243 | atlassian-ide-plugin.xml 244 | 245 | # Cursive Clojure plugin 246 | .idea/replstate.xml 247 | 248 | # Crashlytics plugin (for Android Studio and IntelliJ) 249 | com_crashlytics_export_strings.xml 250 | crashlytics.properties 251 | crashlytics-build.properties 252 | fabric.properties 253 | *.json 254 | -------------------------------------------------------------------------------- /.vscode/sftp.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "server", 3 | "host": "192.168.121.220", 4 | "port": 22, 5 | "username": "pdluser", 6 | "password": "pdluser$666", 7 | "protocol": "sftp", 8 | "agent": null, 9 | "privateKeyPath": null, 10 | "passphrase": null, 11 | "passive": false, 12 | "interactiveAuth": true, 13 | "remotePath": "/home/pdluser/project/tianchi_demo", 14 | "context": "D:\\GitHub\\datawhale_cv_competition", 15 | "uploadOnSave": true, 16 | "syncMode": "update", 17 | "ignore": [ 18 | "**/.vscode/**", 19 | "**/.git/**", 20 | "**/.DS_Store", 21 | "**/dataset/**", 22 | "*.jpg", 23 | "*.weights", 24 | "*.pt", 25 | "*.pyc", 26 | "data_batch*" 27 | ], 28 | "watcher": { 29 | "files": false, 30 | "autoUpload": true, 31 | "autoDelete": false 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | #pip install torch==1.7.1+cu101 torchvision==0.8.2+cu101 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html 2 | 3 | # Base Images 4 | FROM registry.cn-shanghai.aliyuncs.com/tcc-public/pytorch:1.4-cuda10.1-py3 5 | #registry.cn-shanghai.aliyuncs.com/pai-dlc/pytorch-training:1.6.0PAI-gpu-py37-cu100-ubuntu16.04 6 | 7 | #registry.cn-shanghai.aliyuncs.com/tcc-public/pytorch:1.4-cuda10.1-py3 8 | ADD . / 9 | 10 | WORKDIR / 11 | 12 | RUN pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple 13 | 14 | RUN DEBIAN_FRONTEND=noninteractive apt update -y 15 | RUN DEBIAN_FRONTEND=noninteractive apt install libgl1-mesa-glx -y 16 | RUN DEBIAN_FRONTEND=noninteractive apt-get install -y libglib2.0-0 -y 17 | 18 | CMD ["sh", "run.sh"] 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 阿里天池 布匹缺陷热身赛 2 | 3 | 尝试在yolov5x中加入SE模块 4 | -------------------------------------------------------------------------------- /convertTrainLabel.py: -------------------------------------------------------------------------------- 1 | import numpy as np # linear algebra 2 | import os 3 | import json 4 | from tqdm import tqdm 5 | import shutil as sh 6 | import cv2 7 | 8 | josn_path = "/media/niu/niu_d/data/competition/guangdong1_round2_train2_20191004_Annotations/guangdong1_round2_train2_20191004_Annotations/Annotations/anno_train.json" 9 | image_path = "/media/niu/niu_d/data/competition/guangdong1_round2_train2_20191004_images/guangdong1_round2_train2_20191004_images/defect/" 10 | 11 | # josn_path = "/home/pdluser/data/guangdong1_round2_train_part1_20190924/Annotations/anno_train.json" 12 | # image_path = "/home/pdluser/data/guangdong1_round2_train_part1_20190924/defect" 13 | 14 | # josn_path = "/home/pdluser/data/guangdong1_round2_train_part1_20190924/Annotations/anno_train.json" 15 | # image_path = "/home/pdluser/data/guangdong1_round2_train_part3_20190924/defect" 16 | 17 | 18 | name_list = [] 19 | image_h_list = [] 20 | image_w_list = [] 21 | c_list = [] 22 | w_list = [] 23 | h_list = [] 24 | x_center_list = [] 25 | y_center_list = [] 26 | 27 | with open(josn_path, 'r') as f: 28 | temps = tqdm(json.loads(f.read())) 29 | for temp in temps: 30 | # image_w = temp["image_width"] 31 | # image_h = temp["image_height"] 32 | name = temp["name"].split('.')[0] 33 | path = os.path.join(image_path, name, temp["name"]) 34 | # print('path: ',path) 35 | im = cv2.imread(path) 36 | if im is None: 37 | print(path) 38 | continue 39 | else: 40 | sp = im.shape 41 | image_h, image_w = sp[0], sp[1] 42 | # print("image_h, image_w: ", image_h, image_w) 43 | # print("defect_name: ",temp["defect_name"]) 44 | #bboxs 45 | x_l, y_l, x_r, y_r = temp["bbox"] 46 | # print(temp["name"], temp["bbox"]) 47 | if temp["defect_name"]=="沾污": 48 | defect_name = '0' 49 | elif temp["defect_name"]=="错花": 50 | defect_name = '1' 51 | elif temp["defect_name"] == "水印": 52 | defect_name = '2' 53 | elif temp["defect_name"] == "花毛": 54 | defect_name = '3' 55 | elif temp["defect_name"] == "缝头": 56 | defect_name = '4' 57 | elif temp["defect_name"] == "缝头印": 58 | defect_name = '5' 59 | elif temp["defect_name"] == "虫粘": 60 | defect_name = '6' 61 | elif temp["defect_name"] == "破洞": 62 | defect_name = '7' 63 | elif temp["defect_name"] == "褶子": 64 | defect_name = '8' 65 | elif temp["defect_name"] == "织疵": 66 | defect_name = '9' 67 | elif temp["defect_name"] == "漏印": 68 | defect_name = '10' 69 | elif temp["defect_name"] == "蜡斑": 70 | defect_name = '11' 71 | elif temp["defect_name"] == "色差": 72 | defect_name = '12' 73 | elif temp["defect_name"] == "网折": 74 | defect_name = '13' 75 | elif temp["defect_name"] == "其他": 76 | defect_name = '14' 77 | else: 78 | defect_name = '15' 79 | print("----------------------------------error---------------------------") 80 | raise("erro") 81 | # print(image_w, image_h) 82 | # print(defect_name) 83 | x_center = (x_l + x_r)/(2*image_w) 84 | y_center = (y_l + y_r)/(2*image_h) 85 | w = (x_r - x_l)/(image_w) 86 | h = (y_r - y_l)/(image_h) 87 | # print(x_center, y_center, w, h) 88 | name_list.append(temp["name"]) 89 | c_list.append(defect_name) 90 | image_h_list.append(image_w) 91 | image_w_list.append(image_h) 92 | x_center_list.append(x_center) 93 | y_center_list.append(y_center) 94 | w_list.append(w) 95 | h_list.append(h) 96 | 97 | index = list(set(name_list)) 98 | print(len(index)) 99 | for fold in [0]: 100 | val_index = index[len(index) * fold // 5:len(index) * (fold + 1) // 5] 101 | print(len(val_index)) 102 | for num, name in enumerate(name_list): 103 | print(c_list[num], x_center_list[num], y_center_list[num], w_list[num], h_list[num]) 104 | row = [c_list[num], x_center_list[num], y_center_list[num], w_list[num], h_list[num]] 105 | if name in val_index: 106 | path2save = 'val/' 107 | else: 108 | path2save = 'train/' 109 | 110 | if not os.path.exists('convertor/fold{}/labels/'.format(fold) + path2save): 111 | os.makedirs('convertor/fold{}/labels/'.format(fold) + path2save) 112 | with open('convertor/fold{}/labels/'.format(fold) + path2save + name.split('.')[0] + ".txt", 'a+') as f: 113 | for data in row: 114 | f.write('{} '.format(data)) 115 | f.write('\n') 116 | if not os.path.exists('convertor/fold{}/images/{}'.format(fold, path2save)): 117 | os.makedirs('convertor/fold{}/images/{}'.format(fold, path2save)) 118 | sh.copy(os.path.join(image_path, name.split('.')[0], name), 119 | 'convertor/fold{}/images/{}/{}'.format(fold, path2save, name)) 120 | 121 | 122 | -------------------------------------------------------------------------------- /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.load(f, Loader=yaml.FullLoader) # 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: ./process_data/images/train # 128 images 14 | val: ./process_data/images/val # 128 images 15 | 16 | # number of classes 17 | nc: 15 18 | 19 | # class names 20 | names: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15'] 21 | -------------------------------------------------------------------------------- /data/get_coco2017.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # COCO 2017 dataset http://cocodataset.org 3 | # Download command: bash yolov5/data/get_coco2017.sh 4 | # Train command: python train.py --data ./data/coco.yaml 5 | # Dataset should be placed next to yolov5 folder: 6 | # /parent_folder 7 | # /coco 8 | # /yolov5 9 | 10 | # Download labels from Google Drive, accepting presented query 11 | filename="coco2017labels.zip" 12 | fileid="1cXZR_ckHki6nddOmcysCuuJFM--T-Q6L" 13 | curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${fileid}" > /dev/null 14 | curl -Lb ./cookie "https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=${fileid}" -o ${filename} 15 | rm ./cookie 16 | 17 | # Unzip labels 18 | unzip -q ${filename} # for coco.zip 19 | # tar -xzf ${filename} # for coco.tar.gz 20 | rm ${filename} 21 | 22 | # Download and unzip images 23 | cd coco/images 24 | f="train2017.zip" && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f && rm $f # 19G, 118k images 25 | f="val2017.zip" && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f && rm $f # 1G, 5k images 26 | # f="test2017.zip" && curl http://images.cocodataset.org/zips/$f -o $f && unzip -q $f && rm $f # 7G, 41k images 27 | 28 | # cd out 29 | cd ../.. 30 | -------------------------------------------------------------------------------- /data/get_voc.sh: -------------------------------------------------------------------------------- 1 | # PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC/ 2 | # Download command: bash ./data/get_voc.sh 3 | # Train command: python train.py --data voc.yaml 4 | # Dataset should be placed next to yolov5 folder: 5 | # /parent_folder 6 | # /VOC 7 | # /yolov5 8 | 9 | start=`date +%s` 10 | 11 | # handle optional download dir 12 | if [ -z "$1" ] 13 | then 14 | # navigate to ~/tmp 15 | echo "navigating to ../tmp/ ..." 16 | mkdir -p ../tmp 17 | cd ../tmp/ 18 | else 19 | # check if is valid directory 20 | if [ ! -d $1 ]; then 21 | echo $1 "is not a valid directory" 22 | exit 0 23 | fi 24 | echo "navigating to" $1 "..." 25 | cd $1 26 | fi 27 | 28 | echo "Downloading VOC2007 trainval ..." 29 | # Download the data. 30 | curl -LO http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtrainval_06-Nov-2007.tar 31 | echo "Downloading VOC2007 test data ..." 32 | curl -LO http://host.robots.ox.ac.uk/pascal/VOC/voc2007/VOCtest_06-Nov-2007.tar 33 | echo "Done downloading." 34 | 35 | # Extract data 36 | echo "Extracting trainval ..." 37 | tar -xf VOCtrainval_06-Nov-2007.tar 38 | echo "Extracting test ..." 39 | tar -xf VOCtest_06-Nov-2007.tar 40 | echo "removing tars ..." 41 | rm VOCtrainval_06-Nov-2007.tar 42 | rm VOCtest_06-Nov-2007.tar 43 | 44 | end=`date +%s` 45 | runtime=$((end-start)) 46 | 47 | echo "Completed in" $runtime "seconds" 48 | 49 | start=`date +%s` 50 | 51 | # handle optional download dir 52 | if [ -z "$1" ] 53 | then 54 | # navigate to ~/tmp 55 | echo "navigating to ../tmp/ ..." 56 | mkdir -p ../tmp 57 | cd ../tmp/ 58 | else 59 | # check if is valid directory 60 | if [ ! -d $1 ]; then 61 | echo $1 "is not a valid directory" 62 | exit 0 63 | fi 64 | echo "navigating to" $1 "..." 65 | cd $1 66 | fi 67 | 68 | echo "Downloading VOC2012 trainval ..." 69 | # Download the data. 70 | curl -LO http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar 71 | echo "Done downloading." 72 | 73 | 74 | # Extract data 75 | echo "Extracting trainval ..." 76 | tar -xf VOCtrainval_11-May-2012.tar 77 | echo "removing tar ..." 78 | rm VOCtrainval_11-May-2012.tar 79 | 80 | end=`date +%s` 81 | runtime=$((end-start)) 82 | 83 | echo "Completed in" $runtime "seconds" 84 | 85 | cd ../tmp 86 | echo "Spliting dataset..." 87 | python3 - "$@" < train.txt 147 | cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt > train.all.txt 148 | 149 | python3 - "$@" <= 1 85 | p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count 86 | else: 87 | p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0) 88 | 89 | p = Path(p) # to Path 90 | save_path = str(save_dir / p.name) # img.jpg 91 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt 92 | s += '%gx%g ' % img.shape[2:] # print string 93 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh 94 | if len(det): 95 | # Rescale boxes from img_size to im0 size 96 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 97 | 98 | # Print results 99 | for c in det[:, -1].unique(): 100 | n = (det[:, -1] == c).sum() # detections per class 101 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string 102 | 103 | # Write results 104 | for *xyxy, conf, cls in reversed(det): 105 | if save_txt: # Write to file 106 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 107 | line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format 108 | with open(txt_path + '.txt', 'a') as f: 109 | f.write(('%g ' * len(line)).rstrip() % line + '\n') 110 | 111 | if save_img or view_img: # Add bbox to image 112 | label = f'{names[int(cls)]} {conf:.2f}' 113 | plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3) 114 | 115 | # Print time (inference + NMS) 116 | print(f'{s}Done. ({t2 - t1:.3f}s)') 117 | 118 | # Stream results 119 | if view_img: 120 | cv2.imshow(str(p), im0) 121 | cv2.waitKey(1) # 1 millisecond 122 | 123 | # Save results (image with detections) 124 | if save_img: 125 | if dataset.mode == 'image': 126 | cv2.imwrite(save_path, im0) 127 | else: # 'video' 128 | if vid_path != save_path: # new video 129 | vid_path = save_path 130 | if isinstance(vid_writer, cv2.VideoWriter): 131 | vid_writer.release() # release previous video writer 132 | 133 | fourcc = 'mp4v' # output video codec 134 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 135 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 136 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 137 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h)) 138 | vid_writer.write(im0) 139 | 140 | if save_txt or save_img: 141 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' 142 | print(f"Results saved to {save_dir}{s}") 143 | 144 | print(f'Done. ({time.time() - t0:.3f}s)') 145 | 146 | 147 | if __name__ == '__main__': 148 | parser = argparse.ArgumentParser() 149 | parser.add_argument('--weights', nargs='+', type=str, default='./weights/best.pt', help='model.pt path(s)') 150 | parser.add_argument('--source', type=str, default='data/images', help='source') # file/folder, 0 for webcam 151 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 152 | parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold') 153 | parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS') 154 | parser.add_argument('--device', default='0', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 155 | parser.add_argument('--view-img', action='store_true', help='display results') 156 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 157 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') 158 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') 159 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 160 | parser.add_argument('--augment', action='store_true', help='augmented inference') 161 | parser.add_argument('--update', action='store_true', help='update all models') 162 | parser.add_argument('--project', default='runs/detect', help='save results to project/name') 163 | parser.add_argument('--name', default='exp', help='save results to project/name') 164 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') 165 | opt = parser.parse_args() 166 | print(opt) 167 | check_requirements() 168 | 169 | with torch.no_grad(): 170 | if opt.update: # update all models (to fix SourceChangeWarning) 171 | for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']: 172 | detect() 173 | strip_optimizer(opt.weights) 174 | else: 175 | detect() 176 | -------------------------------------------------------------------------------- /hubconf.py: -------------------------------------------------------------------------------- 1 | """File for accessing YOLOv5 via PyTorch Hub https://pytorch.org/hub/ 2 | 3 | Usage: 4 | import torch 5 | model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True, channels=3, classes=80) 6 | """ 7 | 8 | from pathlib import Path 9 | 10 | import torch 11 | 12 | from models.yolo import Model 13 | from utils.general import set_logging 14 | from utils.google_utils import attempt_download 15 | 16 | dependencies = ['torch', 'yaml'] 17 | set_logging() 18 | 19 | 20 | def create(name, pretrained, channels, classes, autoshape): 21 | """Creates a specified YOLOv5 model 22 | 23 | Arguments: 24 | name (str): name of model, i.e. 'yolov5s' 25 | pretrained (bool): load pretrained weights into the model 26 | channels (int): number of input channels 27 | classes (int): number of model classes 28 | 29 | Returns: 30 | pytorch model 31 | """ 32 | config = Path(__file__).parent / 'models' / f'{name}.yaml' # model.yaml path 33 | try: 34 | model = Model(config, channels, classes) 35 | if pretrained: 36 | fname = f'{name}.pt' # checkpoint filename 37 | attempt_download(fname) # download if not found locally 38 | ckpt = torch.load(fname, map_location=torch.device('cpu')) # load 39 | state_dict = ckpt['model'].float().state_dict() # to FP32 40 | state_dict = {k: v for k, v in state_dict.items() if model.state_dict()[k].shape == v.shape} # filter 41 | model.load_state_dict(state_dict, strict=False) # load 42 | if len(ckpt['model'].names) == classes: 43 | model.names = ckpt['model'].names # set class names attribute 44 | if autoshape: 45 | model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS 46 | return model 47 | 48 | except Exception as e: 49 | help_url = 'https://github.com/ultralytics/yolov5/issues/36' 50 | s = 'Cache maybe be out of date, try force_reload=True. See %s for help.' % help_url 51 | raise Exception(s) from e 52 | 53 | 54 | def yolov5s(pretrained=False, channels=3, classes=80, autoshape=True): 55 | """YOLOv5-small model from https://github.com/ultralytics/yolov5 56 | 57 | Arguments: 58 | pretrained (bool): load pretrained weights into the model, default=False 59 | channels (int): number of input channels, default=3 60 | classes (int): number of model classes, default=80 61 | 62 | Returns: 63 | pytorch model 64 | """ 65 | return create('yolov5s', pretrained, channels, classes, autoshape) 66 | 67 | 68 | def yolov5m(pretrained=False, channels=3, classes=80, autoshape=True): 69 | """YOLOv5-medium model from https://github.com/ultralytics/yolov5 70 | 71 | Arguments: 72 | pretrained (bool): load pretrained weights into the model, default=False 73 | channels (int): number of input channels, default=3 74 | classes (int): number of model classes, default=80 75 | 76 | Returns: 77 | pytorch model 78 | """ 79 | return create('yolov5m', pretrained, channels, classes, autoshape) 80 | 81 | 82 | def yolov5l(pretrained=False, channels=3, classes=80, autoshape=True): 83 | """YOLOv5-large model from https://github.com/ultralytics/yolov5 84 | 85 | Arguments: 86 | pretrained (bool): load pretrained weights into the model, default=False 87 | channels (int): number of input channels, default=3 88 | classes (int): number of model classes, default=80 89 | 90 | Returns: 91 | pytorch model 92 | """ 93 | return create('yolov5l', pretrained, channels, classes, autoshape) 94 | 95 | 96 | def yolov5x(pretrained=False, channels=3, classes=80, autoshape=True): 97 | """YOLOv5-xlarge model from https://github.com/ultralytics/yolov5 98 | 99 | Arguments: 100 | pretrained (bool): load pretrained weights into the model, default=False 101 | channels (int): number of input channels, default=3 102 | classes (int): number of model classes, default=80 103 | 104 | Returns: 105 | pytorch model 106 | """ 107 | return create('yolov5x', pretrained, channels, classes, autoshape) 108 | 109 | 110 | def custom(path_or_model='path/to/model.pt', autoshape=True): 111 | """YOLOv5-custom model from https://github.com/ultralytics/yolov5 112 | 113 | Arguments (3 options): 114 | path_or_model (str): 'path/to/model.pt' 115 | path_or_model (dict): torch.load('path/to/model.pt') 116 | path_or_model (nn.Module): torch.load('path/to/model.pt')['model'] 117 | 118 | Returns: 119 | pytorch model 120 | """ 121 | model = torch.load(path_or_model) if isinstance(path_or_model, str) else path_or_model # load checkpoint 122 | if isinstance(model, dict): 123 | model = model['model'] # load model 124 | 125 | hub_model = Model(model.yaml).to(next(model.parameters()).device) # create 126 | hub_model.load_state_dict(model.float().state_dict()) # load state_dict 127 | hub_model.names = model.names # class names 128 | return hub_model.autoshape() if autoshape else hub_model 129 | 130 | 131 | if __name__ == '__main__': 132 | model = create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True) # pretrained example 133 | # model = custom(path_or_model='path/to/model.pt') # custom example 134 | 135 | # Verify inference 136 | import numpy as np 137 | from PIL import Image 138 | 139 | imgs = [Image.open('data/images/bus.jpg'), # PIL 140 | 'data/images/zidane.jpg', # filename 141 | 'https://github.com/ultralytics/yolov5/raw/master/data/images/bus.jpg', # URI 142 | np.zeros((640, 480, 3))] # numpy 143 | 144 | results = model(imgs) # batched inference 145 | results.print() 146 | results.save() 147 | -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/models/__init__.py -------------------------------------------------------------------------------- /models/__pycache__/common.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/models/__pycache__/common.cpython-36.pyc -------------------------------------------------------------------------------- /models/__pycache__/common.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/models/__pycache__/common.cpython-38.pyc -------------------------------------------------------------------------------- /models/__pycache__/experimental.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/models/__pycache__/experimental.cpython-36.pyc -------------------------------------------------------------------------------- /models/__pycache__/experimental.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/models/__pycache__/experimental.cpython-38.pyc -------------------------------------------------------------------------------- /models/__pycache__/yolo.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/models/__pycache__/yolo.cpython-36.pyc -------------------------------------------------------------------------------- /models/__pycache__/yolo.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/models/__pycache__/yolo.cpython-38.pyc -------------------------------------------------------------------------------- /models/common.py: -------------------------------------------------------------------------------- 1 | # This file contains modules common to various models 2 | 3 | import math 4 | from pathlib import Path 5 | 6 | import numpy as np 7 | import requests 8 | import torch 9 | import torch.nn as nn 10 | from PIL import Image 11 | 12 | from utils.datasets import letterbox 13 | from utils.general import non_max_suppression, make_divisible, scale_coords, xyxy2xywh 14 | from utils.plots import color_list, plot_one_box 15 | 16 | 17 | def autopad(k, p=None): # kernel, padding 18 | # Pad to 'same' 19 | if p is None: 20 | p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad 21 | return p 22 | 23 | 24 | def DWConv(c1, c2, k=1, s=1, act=True): 25 | # Depthwise convolution 26 | return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act) 27 | 28 | 29 | class Conv(nn.Module): 30 | # Standard convolution 31 | # ch_in, ch_out, kernel, stride, padding, groups 32 | def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): 33 | super(Conv, self).__init__() 34 | self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), 35 | groups=g, bias=False) 36 | self.bn = nn.BatchNorm2d(c2) 37 | self.act = nn.SiLU() if act is True else ( 38 | act if isinstance(act, nn.Module) else nn.Identity()) 39 | 40 | def forward(self, x): 41 | return self.act(self.bn(self.conv(x))) 42 | 43 | def fuseforward(self, x): 44 | return self.act(self.conv(x)) 45 | 46 | 47 | class Bottleneck(nn.Module): 48 | # Standard bottleneck 49 | # ch_in, ch_out, shortcut, groups, expansion 50 | def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): 51 | super(Bottleneck, self).__init__() 52 | c_ = int(c2 * e) # hidden channels 53 | self.cv1 = Conv(c1, c_, 1, 1) 54 | self.cv2 = Conv(c_, c2, 3, 1, g=g) 55 | self.add = shortcut and c1 == c2 56 | 57 | def forward(self, x): 58 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) 59 | 60 | 61 | class BottleneckCSP(nn.Module): 62 | # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks 63 | # ch_in, ch_out, number, shortcut, groups, expansion 64 | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): 65 | super(BottleneckCSP, self).__init__() 66 | c_ = int(c2 * e) # hidden channels 67 | self.cv1 = Conv(c1, c_, 1, 1) 68 | self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False) 69 | self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False) 70 | self.cv4 = Conv(2 * c_, c2, 1, 1) 71 | self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3) 72 | self.act = nn.LeakyReLU(0.1, inplace=True) 73 | self.m = nn.Sequential( 74 | *[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) 75 | 76 | def forward(self, x): 77 | y1 = self.cv3(self.m(self.cv1(x))) 78 | y2 = self.cv2(x) 79 | return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1)))) 80 | 81 | 82 | class C3(nn.Module): 83 | # CSP Bottleneck with 3 convolutions 84 | # ch_in, ch_out, number, shortcut, groups, expansion 85 | def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): 86 | super(C3, self).__init__() 87 | c_ = int(c2 * e) # hidden channels 88 | self.cv1 = Conv(c1, c_, 1, 1) 89 | self.cv2 = Conv(c1, c_, 1, 1) 90 | self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2) 91 | self.m = nn.Sequential( 92 | *[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) 93 | # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)]) 94 | 95 | def forward(self, x): 96 | return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1)) 97 | 98 | 99 | class SPP(nn.Module): 100 | # Spatial pyramid pooling layer used in YOLOv3-SPP 101 | # [-1, 1, SPP, [1024, [5, 9, 13]]], 102 | def __init__(self, c1, c2, k=(5, 9, 13)): 103 | super(SPP, self).__init__() 104 | c_ = c1 // 2 # hidden channels 105 | self.cv1 = Conv(c1, c_, 1, 1) 106 | self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) 107 | self.m = nn.ModuleList( 108 | [nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) 109 | 110 | def forward(self, x): 111 | x = self.cv1(x) 112 | return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) 113 | 114 | 115 | class SELayer(nn.Module): 116 | def __init__(self, c1, r=16): 117 | super(SELayer, self).__init__() 118 | self.avgpool = nn.AdaptiveAvgPool2d(1) 119 | self.l1 = nn.Linear(c1, c1//r, bias=False) 120 | self.relu = nn.ReLU(inplace=True) 121 | self.l2 = nn.Linear(c1//r, c1, bias=False) 122 | self.sig = nn.Sigmoid() 123 | 124 | 125 | def forward(self, x): 126 | b, c, _, _ = x.size() 127 | y = self.avgpool(x).view(b, c) 128 | y = self.l1(y) 129 | y = self.relu(y) 130 | y = self.l2(y) 131 | y = self.sig(y) 132 | y = y.view(b, c, 1, 1) 133 | return x * y.expand_as(x) 134 | 135 | 136 | class Focus(nn.Module): 137 | # Focus wh information into c-space 138 | # ch_in, ch_out, kernel, stride, padding, groups 139 | def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): 140 | super(Focus, self).__init__() 141 | self.conv = Conv(c1 * 4, c2, k, s, p, g, act) 142 | # self.contract = Contract(gain=2) 143 | 144 | def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) 145 | return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)) 146 | # return self.conv(self.contract(x)) 147 | 148 | 149 | class Contract(nn.Module): 150 | # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40) 151 | def __init__(self, gain=2): 152 | super().__init__() 153 | self.gain = gain 154 | 155 | def forward(self, x): 156 | N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain' 157 | s = self.gain 158 | x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2) 159 | x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40) 160 | return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40) 161 | 162 | 163 | class Expand(nn.Module): 164 | # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160) 165 | def __init__(self, gain=2): 166 | super().__init__() 167 | self.gain = gain 168 | 169 | def forward(self, x): 170 | N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' 171 | s = self.gain 172 | x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80) 173 | x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2) 174 | return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160) 175 | 176 | 177 | class Concat(nn.Module): 178 | # Concatenate a list of tensors along dimension 179 | def __init__(self, dimension=1): 180 | super(Concat, self).__init__() 181 | self.d = dimension 182 | 183 | def forward(self, x): 184 | return torch.cat(x, self.d) 185 | 186 | 187 | class NMS(nn.Module): 188 | # Non-Maximum Suppression (NMS) module 189 | conf = 0.25 # confidence threshold 190 | iou = 0.45 # IoU threshold 191 | classes = None # (optional list) filter by class 192 | 193 | def __init__(self): 194 | super(NMS, self).__init__() 195 | 196 | def forward(self, x): 197 | return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) 198 | 199 | 200 | class autoShape(nn.Module): 201 | # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS 202 | img_size = 640 # inference size (pixels) 203 | conf = 0.25 # NMS confidence threshold 204 | iou = 0.45 # NMS IoU threshold 205 | classes = None # (optional list) filter by class 206 | 207 | def __init__(self, model): 208 | super(autoShape, self).__init__() 209 | self.model = model.eval() 210 | 211 | def autoshape(self): 212 | # model already converted to model.autoshape() 213 | print('autoShape already enabled, skipping... ') 214 | return self 215 | 216 | def forward(self, imgs, size=640, augment=False, profile=False): 217 | # Inference from various sources. For height=720, width=1280, RGB images example inputs are: 218 | # filename: imgs = 'data/samples/zidane.jpg' 219 | # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg' 220 | # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(720,1280,3) 221 | # PIL: = Image.open('image.jpg') # HWC x(720,1280,3) 222 | # numpy: = np.zeros((720,1280,3)) # HWC 223 | # torch: = torch.zeros(16,3,720,1280) # BCHW 224 | # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images 225 | 226 | p = next(self.model.parameters()) # for device and type 227 | if isinstance(imgs, torch.Tensor): # torch 228 | # inference 229 | return self.model(imgs.to(p.device).type_as(p), augment, profile) 230 | 231 | # Pre-process 232 | n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else ( 233 | 1, [imgs]) # number of images, list of images 234 | shape0, shape1, files = [], [], [] # image and inference shapes, filenames 235 | for i, im in enumerate(imgs): 236 | if isinstance(im, str): # filename or uri 237 | im, f = Image.open(requests.get( 238 | im, stream=True).raw if im.startswith('http') else im), im # open 239 | im.filename = f # for uri 240 | files.append(Path(im.filename).with_suffix( 241 | '.jpg').name if isinstance(im, Image.Image) else f'image{i}.jpg') 242 | im = np.array(im) # to numpy 243 | if im.shape[0] < 5: # image in CHW 244 | # reverse dataloader .transpose(2, 0, 1) 245 | im = im.transpose((1, 2, 0)) 246 | im = im[:, :, :3] if im.ndim == 3 else np.tile( 247 | im[:, :, None], 3) # enforce 3ch input 248 | s = im.shape[:2] # HWC 249 | shape0.append(s) # image shape 250 | g = (size / max(s)) # gain 251 | shape1.append([y * g for y in s]) 252 | imgs[i] = im # update 253 | shape1 = [make_divisible(x, int(self.stride.max())) 254 | for x in np.stack(shape1, 0).max(0)] # inference shape 255 | x = [letterbox(im, new_shape=shape1, auto=False)[0] 256 | for im in imgs] # pad 257 | x = np.stack(x, 0) if n > 1 else x[0][None] # stack 258 | x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW 259 | x = torch.from_numpy(x).to(p.device).type_as(p) / \ 260 | 255. # uint8 to fp16/32 261 | 262 | # Inference 263 | with torch.no_grad(): 264 | y = self.model(x, augment, profile)[0] # forward 265 | y = non_max_suppression(y, conf_thres=self.conf, 266 | iou_thres=self.iou, classes=self.classes) # NMS 267 | 268 | # Post-process 269 | for i in range(n): 270 | scale_coords(shape1, y[i][:, :4], shape0[i]) 271 | 272 | return Detections(imgs, y, files, self.names) 273 | 274 | 275 | class Detections: 276 | # detections class for YOLOv5 inference results 277 | def __init__(self, imgs, pred, files, names=None): 278 | super(Detections, self).__init__() 279 | d = pred[0].device # device 280 | gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) 281 | for im in imgs] # normalizations 282 | self.imgs = imgs # list of images as numpy arrays 283 | self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls) 284 | self.names = names # class names 285 | self.files = files # image filenames 286 | self.xyxy = pred # xyxy pixels 287 | self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels 288 | self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized 289 | self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized 290 | self.n = len(self.pred) 291 | 292 | def display(self, pprint=False, show=False, save=False, render=False, save_dir=''): 293 | colors = color_list() 294 | for i, (img, pred) in enumerate(zip(self.imgs, self.pred)): 295 | str = f'image {i + 1}/{len(self.pred)}: {img.shape[0]}x{img.shape[1]} ' 296 | if pred is not None: 297 | for c in pred[:, -1].unique(): 298 | n = (pred[:, -1] == c).sum() # detections per class 299 | # add to string 300 | str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " 301 | if show or save or render: 302 | for *box, conf, cls in pred: # xyxy, confidence, class 303 | label = f'{self.names[int(cls)]} {conf:.2f}' 304 | plot_one_box(box, img, label=label, 305 | color=colors[int(cls) % 10]) 306 | img = Image.fromarray(img.astype(np.uint8)) if isinstance( 307 | img, np.ndarray) else img # from np 308 | if pprint: 309 | print(str.rstrip(', ')) 310 | if show: 311 | img.show(self.files[i]) # show 312 | if save: 313 | f = Path(save_dir) / self.files[i] 314 | img.save(f) # save 315 | print(f"{'Saving' * (i == 0)} {f},", 316 | end='' if i < self.n - 1 else ' done.\n') 317 | if render: 318 | self.imgs[i] = np.asarray(img) 319 | 320 | def print(self): 321 | self.display(pprint=True) # print results 322 | 323 | def show(self): 324 | self.display(show=True) # show results 325 | 326 | def save(self, save_dir='results/'): 327 | Path(save_dir).mkdir(exist_ok=True) 328 | self.display(save=True, save_dir=save_dir) # save results 329 | 330 | def render(self): 331 | self.display(render=True) # render results 332 | return self.imgs 333 | 334 | def __len__(self): 335 | return self.n 336 | 337 | def tolist(self): 338 | # return a list of Detections objects, i.e. 'for result in results.tolist():' 339 | x = [Detections([self.imgs[i]], [self.pred[i]], self.names) 340 | for i in range(self.n)] 341 | for d in x: 342 | for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']: 343 | setattr(d, k, getattr(d, k)[0]) # pop out of list 344 | return x 345 | 346 | 347 | class Classify(nn.Module): 348 | # Classification head, i.e. x(b,c1,20,20) to x(b,c2) 349 | # ch_in, ch_out, kernel, stride, padding, groups 350 | def __init__(self, c1, c2, k=1, s=1, p=None, g=1): 351 | super(Classify, self).__init__() 352 | self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1) 353 | self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), 354 | groups=g) # to x(b,c2,1,1) 355 | self.flat = nn.Flatten() 356 | 357 | def forward(self, x): 358 | z = torch.cat([self.aap(y) for y in ( 359 | x if isinstance(x, list) else [x])], 1) # cat if list 360 | return self.flat(self.conv(z)) # flatten to x(b,c2) 361 | -------------------------------------------------------------------------------- /models/experimental.py: -------------------------------------------------------------------------------- 1 | # This file contains 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 | model.append(torch.load(w, map_location=map_location)['model'].float().fuse().eval()) # load FP32 model 119 | 120 | # Compatibility updates 121 | for m in model.modules(): 122 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: 123 | m.inplace = True # pytorch 1.7.0 compatibility 124 | elif type(m) is Conv: 125 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 126 | 127 | if len(model) == 1: 128 | return model[-1] # return model 129 | else: 130 | print('Ensemble created with %s\n' % weights) 131 | for k in ['names', 'stride']: 132 | setattr(model, k, getattr(model[-1], k)) 133 | return model # return ensemble 134 | -------------------------------------------------------------------------------- /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 ./weights/yolov5s.pt --img 640 --batch 1 5 | """ 6 | 7 | import argparse 8 | import sys 9 | import time 10 | 11 | sys.path.append('./') # to run '$ python *.py' files in subdirectories 12 | 13 | import torch 14 | import torch.nn as nn 15 | 16 | import models 17 | from models.experimental import attempt_load 18 | from utils.activations import Hardswish, SiLU 19 | from utils.general import set_logging, check_img_size 20 | 21 | if __name__ == '__main__': 22 | parser = argparse.ArgumentParser() 23 | parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path') # from yolov5/models/ 24 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width 25 | parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes') 26 | parser.add_argument('--batch-size', type=int, default=1, help='batch size') 27 | opt = parser.parse_args() 28 | opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand 29 | print(opt) 30 | set_logging() 31 | t = time.time() 32 | 33 | # Load PyTorch model 34 | model = attempt_load(opt.weights, map_location=torch.device('cpu')) # load FP32 model 35 | labels = model.names 36 | 37 | # Checks 38 | gs = int(max(model.stride)) # grid size (max stride) 39 | opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples 40 | 41 | # Input 42 | img = torch.zeros(opt.batch_size, 3, *opt.img_size) # image size(1,3,320,192) iDetection 43 | 44 | # Update model 45 | for k, m in model.named_modules(): 46 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 47 | if isinstance(m, models.common.Conv): # assign export-friendly activations 48 | if isinstance(m.act, nn.Hardswish): 49 | m.act = Hardswish() 50 | elif isinstance(m.act, nn.SiLU): 51 | m.act = SiLU() 52 | # elif isinstance(m, models.yolo.Detect): 53 | # m.forward = m.forward_export # assign forward (optional) 54 | model.model[-1].export = True # set Detect() layer export=True 55 | y = model(img) # dry run 56 | 57 | # TorchScript export 58 | try: 59 | print('\nStarting TorchScript export with torch %s...' % torch.__version__) 60 | f = opt.weights.replace('.pt', '.torchscript.pt') # filename 61 | ts = torch.jit.trace(model, img) 62 | ts.save(f) 63 | print('TorchScript export success, saved as %s' % f) 64 | except Exception as e: 65 | print('TorchScript export failure: %s' % e) 66 | 67 | # ONNX export 68 | try: 69 | import onnx 70 | 71 | print('\nStarting ONNX export with onnx %s...' % onnx.__version__) 72 | f = opt.weights.replace('.pt', '.onnx') # filename 73 | torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'], 74 | output_names=['classes', 'boxes'] if y is None else ['output'], 75 | dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640) 76 | 'output': {0: 'batch', 2: 'y', 3: 'x'}} if opt.dynamic else None) 77 | 78 | # Checks 79 | onnx_model = onnx.load(f) # load onnx model 80 | onnx.checker.check_model(onnx_model) # check onnx model 81 | # print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model 82 | print('ONNX export success, saved as %s' % f) 83 | except Exception as e: 84 | print('ONNX export failure: %s' % e) 85 | 86 | # CoreML export 87 | try: 88 | import coremltools as ct 89 | 90 | print('\nStarting CoreML export with coremltools %s...' % ct.__version__) 91 | # convert model from torchscript and apply pixel scaling as per detect.py 92 | model = ct.convert(ts, inputs=[ct.ImageType(name='image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])]) 93 | f = opt.weights.replace('.pt', '.mlmodel') # filename 94 | model.save(f) 95 | print('CoreML export success, saved as %s' % f) 96 | except Exception as e: 97 | print('CoreML export failure: %s' % e) 98 | 99 | # Finish 100 | print('\nExport complete (%.2fs). Visualize with https://github.com/lutzroeder/netron.' % (time.time() - t)) 101 | -------------------------------------------------------------------------------- /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/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/yolo.py: -------------------------------------------------------------------------------- 1 | from utils.torch_utils import time_synchronized, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \ 2 | select_device, copy_attr 3 | from utils.general import make_divisible, check_file, set_logging 4 | from utils.autoanchor import check_anchor_order 5 | from models.experimental import * 6 | from models.common import * 7 | import argparse 8 | import logging 9 | import sys 10 | from copy import deepcopy 11 | 12 | sys.path.append('./') # to run '$ python *.py' files in subdirectories 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | try: 17 | import thop # for FLOPS computation 18 | except ImportError: 19 | thop = None 20 | 21 | 22 | class Detect(nn.Module): 23 | stride = None # strides computed during build 24 | export = False # onnx export 25 | 26 | def __init__(self, nc=15, anchors=(), ch=()): # detection layer 27 | super(Detect, self).__init__() 28 | self.nc = nc # number of classes 29 | self.no = nc + 5 # number of outputs per anchor 30 | self.nl = len(anchors) # number of detection layers 31 | self.na = len(anchors[0]) // 2 # number of anchors 32 | self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) 33 | for x in ch) # output conv 34 | 35 | self.grid = [torch.zeros(1)] * self.nl # init grid 36 | a = torch.tensor(anchors).float().view(self.nl, -1, 2) 37 | self.register_buffer('anchors', a) # shape(nl,na,2) 38 | self.register_buffer('anchor_grid', a.clone().view( 39 | self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) 40 | 41 | def forward(self, x): 42 | # x = x.copy() # for profiling 43 | z = [] # inference output 44 | self.training |= self.export 45 | for i in range(self.nl): 46 | x[i] = self.m[i](x[i]) # conv 47 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) 48 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute( 49 | 0, 1, 3, 4, 2).contiguous() 50 | 51 | if not self.training: # inference 52 | if self.grid[i].shape[2:4] != x[i].shape[2:4]: 53 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device) 54 | 55 | y = x[i].sigmoid() 56 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + 57 | self.grid[i].to(x[i].device)) * self.stride[i] # xy 58 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * \ 59 | self.anchor_grid[i] # wh 60 | z.append(y.view(bs, -1, self.no)) 61 | 62 | return x if self.training else (torch.cat(z, 1), x) 63 | 64 | @staticmethod 65 | def _make_grid(nx=20, ny=20): 66 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) 67 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() 68 | 69 | 70 | class Model(nn.Module): 71 | # model, input channels, number of classes 72 | def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None): 73 | super(Model, self).__init__() 74 | if isinstance(cfg, dict): 75 | self.yaml = cfg # model dict 76 | else: # is *.yaml 77 | import yaml # for torch hub 78 | self.yaml_file = Path(cfg).name 79 | with open(cfg) as f: 80 | self.yaml = yaml.load(f, Loader=yaml.SafeLoader) # model dict 81 | 82 | # Define model 83 | ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels 84 | if nc and nc != self.yaml['nc']: 85 | logger.info('Overriding model.yaml nc=%g with nc=%g' % 86 | (self.yaml['nc'], nc)) 87 | self.yaml['nc'] = nc # override yaml value 88 | self.model, self.save = parse_model( 89 | deepcopy(self.yaml), ch=[ch]) # model, savelist 90 | self.names = [str(i) for i in range(self.yaml['nc'])] # default names 91 | # print([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))]) 92 | 93 | # Build strides, anchors 94 | m = self.model[-1] # Detect() 95 | if isinstance(m, Detect): 96 | s = 256 # 2x min stride 97 | m.stride = torch.tensor( 98 | [s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward 99 | m.anchors /= m.stride.view(-1, 1, 1) 100 | check_anchor_order(m) 101 | self.stride = m.stride 102 | self._initialize_biases() # only run once 103 | # print('Strides: %s' % m.stride.tolist()) 104 | 105 | # Init weights, biases 106 | initialize_weights(self) 107 | self.info() 108 | logger.info('') 109 | 110 | def forward(self, x, augment=False, profile=False): 111 | if augment: 112 | img_size = x.shape[-2:] # height, width 113 | s = [1, 0.83, 0.67] # scales 114 | f = [None, 3, None] # flips (2-ud, 3-lr) 115 | y = [] # outputs 116 | for si, fi in zip(s, f): 117 | xi = scale_img(x.flip(fi) if fi else x, si, 118 | gs=int(self.stride.max())) 119 | yi = self.forward_once(xi)[0] # forward 120 | # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save 121 | yi[..., :4] /= si # de-scale 122 | if fi == 2: 123 | yi[..., 1] = img_size[0] - 1 - yi[..., 1] # de-flip ud 124 | elif fi == 3: 125 | yi[..., 0] = img_size[1] - 1 - yi[..., 0] # de-flip lr 126 | y.append(yi) 127 | return torch.cat(y, 1), None # augmented inference, train 128 | else: 129 | # single-scale inference, train 130 | return self.forward_once(x, profile) 131 | 132 | def forward_once(self, x, profile=False): 133 | y, dt = [], [] # outputs 134 | for id, m in enumerate(self.model): 135 | if m.f != -1: # if not from previous layer 136 | x = y[m.f] if isinstance(m.f, int) else [ 137 | x if j == -1 else y[j] for j in m.f] # from earlier layers 138 | 139 | if profile: 140 | o = thop.profile(m, inputs=(x,), verbose=False)[ 141 | 0] / 1E9 * 2 if thop else 0 # FLOPS 142 | t = time_synchronized() 143 | for _ in range(10): 144 | _ = m(x) 145 | dt.append((time_synchronized() - t) * 100) 146 | print('%10.1f%10.0f%10.1fms %-40s' % (o, m.np, dt[-1], m.type)) 147 | 148 | x = m(x) # run 149 | y.append(x if m.i in self.save else None) # save output 150 | 151 | if profile: 152 | print('%.1fms total' % sum(dt)) 153 | return x 154 | 155 | # initialize biases into Detect(), cf is class frequency 156 | def _initialize_biases(self, cf=None): 157 | # https://arxiv.org/abs/1708.02002 section 3.3 158 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. 159 | m = self.model[-1] # Detect() module 160 | for mi, s in zip(m.m, m.stride): # from 161 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) 162 | # obj (8 objects per 640 image) 163 | b.data[:, 4] += math.log(8 / (640 / s) ** 2) 164 | b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99) 165 | ) if cf is None else torch.log(cf / cf.sum()) # cls 166 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) 167 | 168 | def _print_biases(self): 169 | m = self.model[-1] # Detect() module 170 | for mi in m.m: # from 171 | b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) 172 | print(('%6g Conv2d.bias:' + '%10.3g' * 6) % 173 | (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) 174 | 175 | # def _print_weights(self): 176 | # for m in self.model.modules(): 177 | # if type(m) is Bottleneck: 178 | # print('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights 179 | 180 | def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers 181 | print('Fusing layers... ') 182 | for m in self.model.modules(): 183 | if type(m) is Conv and hasattr(m, 'bn'): 184 | m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv 185 | delattr(m, 'bn') # remove batchnorm 186 | m.forward = m.fuseforward # update forward 187 | self.info() 188 | return self 189 | 190 | def nms(self, mode=True): # add or remove NMS module 191 | present = type(self.model[-1]) is NMS # last layer is NMS 192 | if mode and not present: 193 | print('Adding NMS... ') 194 | m = NMS() # module 195 | m.f = -1 # from 196 | m.i = self.model[-1].i + 1 # index 197 | self.model.add_module(name='%s' % m.i, module=m) # add 198 | self.eval() 199 | elif not mode and present: 200 | print('Removing NMS... ') 201 | self.model = self.model[:-1] # remove 202 | return self 203 | 204 | def autoshape(self): # add autoShape module 205 | print('Adding autoShape... ') 206 | m = autoShape(self) # wrap model 207 | copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 208 | 'stride'), exclude=()) # copy attributes 209 | return m 210 | 211 | def info(self, verbose=False, img_size=640): # print model information 212 | model_info(self, verbose, img_size) 213 | 214 | 215 | def parse_model(d, ch): # model_dict, input_channels(3) 216 | logger.info('\n%3s%18s%3s%10s %-40s%-30s' % 217 | ('', 'from', 'n', 'params', 'module', 'arguments')) 218 | anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] 219 | na = (len(anchors[0]) // 2) if isinstance(anchors, 220 | list) else anchors # number of anchors 221 | no = na * (nc + 5) # number of outputs = anchors * (classes + 5) 222 | 223 | layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out 224 | # from, number, module, args 225 | for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): 226 | m = eval(m) if isinstance(m, str) else m # eval strings 227 | for j, a in enumerate(args): 228 | try: 229 | args[j] = eval(a) if isinstance(a, str) else a # eval strings 230 | except: 231 | pass 232 | 233 | n = max(round(n * gd), 1) if n > 1 else n # depth gain 234 | if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, 235 | DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, 236 | C3]: 237 | c1, c2 = ch[f], args[0] 238 | if c2 != no: # if not output 239 | c2 = make_divisible(c2 * gw, 8) 240 | 241 | args = [c1, c2, *args[1:]] 242 | if m in [BottleneckCSP, C3]: 243 | args.insert(2, n) # number of repeats 244 | n = 1 245 | elif m is nn.BatchNorm2d: 246 | args = [ch[f]] 247 | elif m is Concat: 248 | c2 = sum([ch[x] for x in f]) 249 | elif m is Detect: 250 | args.append([ch[x] for x in f]) 251 | if isinstance(args[1], int): # number of anchors 252 | args[1] = [list(range(args[1] * 2))] * len(f) 253 | elif m is Contract: 254 | c2 = ch[f] * args[0] ** 2 255 | elif m is Expand: 256 | c2 = ch[f] // args[0] ** 2 257 | elif m is SELayer: 258 | channel, re = args[0], args[1] 259 | channel = make_divisible( 260 | channel * gw, 8) if channel != no else channel 261 | args = [channel, re] 262 | else: 263 | c2 = ch[f] 264 | 265 | m_ = nn.Sequential(*[m(*args) for _ in range(n)] 266 | ) if n > 1 else m(*args) # module 267 | t = str(m)[8:-2].replace('__main__.', '') # module type 268 | np = sum([x.numel() for x in m_.parameters()]) # number params 269 | # attach index, 'from' index, type, number params 270 | m_.i, m_.f, m_.type, m_.np = i, f, t, np 271 | logger.info('%3s%18s%3s%10.0f %-40s%-30s' % 272 | (i, f, n, np, t, args)) # print 273 | save.extend(x % i for x in ([f] if isinstance( 274 | f, int) else f) if x != -1) # append to savelist 275 | layers.append(m_) 276 | if i == 0: 277 | ch = [] 278 | ch.append(c2) 279 | return nn.Sequential(*layers), sorted(save) 280 | 281 | 282 | if __name__ == '__main__': 283 | parser = argparse.ArgumentParser() 284 | parser.add_argument('--cfg', type=str, 285 | default='yolov5s.yaml', help='model.yaml') 286 | parser.add_argument('--device', default='', 287 | help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 288 | opt = parser.parse_args() 289 | opt.cfg = check_file(opt.cfg) # check file 290 | set_logging() 291 | device = select_device(opt.device) 292 | 293 | # Create model 294 | model = Model(opt.cfg).to(device) 295 | model.train() 296 | 297 | # Profile 298 | # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device) 299 | # y = model(img, profile=True) 300 | 301 | # Tensorboard 302 | # from torch.utils.tensorboard import SummaryWriter 303 | # tb_writer = SummaryWriter() 304 | # print("Run 'tensorboard --logdir=models/runs' to view tensorboard at http://localhost:6006/") 305 | # tb_writer.add_graph(model.model, img) # add model to tensorboard 306 | # tb_writer.add_image('test', img[0], dataformats='CWH') # add model to tensorboard 307 | -------------------------------------------------------------------------------- /models/yolov5-mobilenet.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # 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 | - [116,90, 156,198, 373,326] # P5/32 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [10,13, 16,30, 33,23] # P3/8 11 | 12 | # YOLOv5 backbone: mobilenet v2 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, nn.Conv2d, [32, 3, 2]], # 0-P1/2 oup, k, s 640 16 | [-1, 1, BottleneckMOB, [16, 1, 1]], # 1-P2/4 oup, s, t 320 17 | [-1, 2, BottleneckMOB, [24, 2, 6]], # 320 18 | [-1, 1, PW_Conv, [256]], #4 output p3 160 19 | [-1, 3, BottleneckMOB, [32, 2, 6]], # 3-P3/8 160 20 | [-1, 4, BottleneckMOB, [64, 1, 6]], # 5 80 21 | [-1, 1, PW_Conv, [512]], #7 output p4 6 40 22 | [-1, 3, BottleneckMOB, [96, 2, 6]], # 7 80 23 | [-1, 3, BottleneckMOB, [160, 1, 6,]], # 40 24 | [-1, 1, BottleneckMOB, [320, 1, 6,]], # 40 25 | [-1, 1, nn.Conv2d, [1280, 1, 1]], # 40 26 | [-1, 1, SPP, [1024, [5, 9, 13]]], #11 # 40 27 | ] 28 | 29 | # YOLOv5 head 30 | head: 31 | [[-1, 3, BottleneckCSP, [1024, False]], # 12 40 32 | 33 | [-1, 1, Conv, [512, 1, 1]], # 40 34 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 40 35 | [[-1, 6], 1, Concat, [1]], # cat backbone P4-7 # 80 36 | [-1, 3, BottleneckCSP, [512, False]], # 16 # 80 37 | 38 | [-1, 1, Conv, [256, 1, 1]], # 80 39 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 160 40 | [[-1, 3], 1, Concat, [1]], # cat backbone P3-4 160 41 | [-1, 3, BottleneckCSP, [256, False]], # 160 42 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 21 (P3/8-small) # 160 43 | 44 | [-2, 1, Conv, [256, 3, 2]], # 160 45 | [[-1, 17], 1, Concat, [1]], # cat head P4 # 160 46 | [-1, 3, BottleneckCSP, [512, False]], # 160 47 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 25 (P4/16-medium) # 160 48 | 49 | [-2, 1, Conv, [512, 3, 2]], # 160 50 | [[-1, 13], 1, Concat, [1]], # cat head P5-13 # 160 51 | [-1, 3, BottleneckCSP, [1024, False]], # 160 52 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 29 (P5/32-large) 160 53 | 54 | [[21, 25, 29], 1, Detect, [nc, anchors]], # Detect(P5, P4, P3) nc:number class, na:number of anchors 55 | ] 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /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/yolov5s1.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # 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 | - [116,90, 156,198, 373,326] # P5/32 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [10,13, 16,30, 33,23] # P3/8 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 640 16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 320 17 | [-1, 3, BottleneckMOB, [128, 1, 1]], # 320 18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 320 19 | [-1, 9, BottleneckCSP, [256]], # 160 20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 #160 21 | [-1, 9, BottleneckCSP, [512]], # 80 22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 #80 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], #40 24 | ] 25 | 26 | # YOLOv5 head 27 | head: 28 | [[-1, 3, BottleneckCSP, [1024, False]], # 9 40 29 | 30 | [-1, 1, Conv, [512, 1, 1]], #40 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], #80 32 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 80 33 | [-1, 3, BottleneckCSP, [512, False]], # 13 80 34 | 35 | [-1, 1, Conv, [256, 1, 1]], # 80 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 160 37 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 160 38 | [-1, 3, BottleneckCSP, [256, False]], # 160 39 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 18 (P3/8-small) 160 40 | 41 | [-2, 1, Conv, [256, 3, 2]], 42 | [[-1, 14], 1, Concat, [1]], # cat head P4 43 | [-1, 3, BottleneckCSP, [512, False]], 44 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 22 (P4/16-medium) 45 | 46 | [-2, 1, Conv, [512, 3, 2]], 47 | [[-1, 10], 1, Concat, [1]], # cat head P5 48 | [-1, 3, BottleneckCSP, [1024, False]], 49 | [-1, 1, nn.Conv2d, [na * (nc + 5), 1, 1]], # 26 (P5/32-large) 50 | 51 | [[], 1, Detect, [nc, anchors]], # Detect(P5, P4, P3) nc:number class, na:number of anchors 52 | ] 53 | -------------------------------------------------------------------------------- /models/yolov5x.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 15 # 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 #1 16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 #2 17 | [-1, 3, C3, [128]], #3 18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 #4 19 | [-1, 9, C3, [256]], #5 20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 #6 21 | [-1, 9, C3, [512]], #7 22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 #8 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], #9 24 | [-1, 3, C3, [1024, False]], # 9 #10 25 | ] 26 | 27 | # YOLOv5 head 28 | head: 29 | [[-1, 1, Conv, [512, 1, 1]], #11 30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], #12 31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 #13 32 | [-1, 3, C3, [512, False]], # 13 #14 33 | 34 | [-1, 1, Conv, [256, 1, 1]], #15 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], #16 36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 #17 37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) #18 38 | 39 | [-1, 1, Conv, [256, 3, 2]], #19 40 | [[-1, 14], 1, Concat, [1]], # cat head P4 #20 41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) #21 42 | 43 | [-1, 1, Conv, [512, 3, 2]], #22 44 | [[-1, 11], 1, Concat, [1]], # cat head P5 #23 45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) #24 46 | 47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 48 | ] 49 | -------------------------------------------------------------------------------- /models/yolov5x_se.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 15 # number of classes 3 | depth_multiple: 1 # model depth multiple 4 | width_multiple: 1 # 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 | [ 16 | [-1, 1, Focus, [64, 3]], # 0-P1/2 #1 17 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 #2 18 | [-1, 3, C3, [128]], #3 19 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 #4 20 | [-1, 9, C3, [256]], #5 21 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 #6 22 | [-1, 9, C3, [512]], #7 23 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 #8 24 | [-1, 1, SPP, [1024, [5, 9, 13]]], #9 25 | [-1, 3, C3, [1024, False]], # 9 #10 26 | [-1, 1, SELayer, [1024, 4]], #10 27 | ] 28 | 29 | 30 | 31 | # YOLOv5 head 32 | head: [ 33 | [-1, 1, Conv, [512, 1, 1]], #11 /32 34 | [-1, 1, nn.Upsample, [None, 2, "nearest"]], #12 /16 35 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 /16 #13 36 | [-1, 3, C3, [512, False]], # 13 / 16 #14 37 | 38 | [-1, 1, Conv, [256, 1, 1]], #15 /16 39 | [-1, 1, nn.Upsample, [None, 2, "nearest"]], #16 /8 40 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 /8 #17 41 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) /8 #18 42 | 43 | [-1, 1, Conv, [256, 3, 2]], #19 /16 44 | [[-1, 6], 1, Concat, [1]], # cat head P4 #20 45 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) #21 46 | 47 | [-1, 1, Conv, [512, 3, 2]], #22 /32 48 | [[-1, 8], 1, Concat, [1]], # cat head P5 #23 49 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) #24 50 | 51 | [[18, 21, 24], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 52 | ] 53 | -------------------------------------------------------------------------------- /process_data_yolo.py: -------------------------------------------------------------------------------- 1 | #-*- coding: utf-8 -*- 2 | ''' 3 | @use:将图片和对应的xml生成为裁剪后两张的图片及数据集 4 | ''' 5 | 6 | from __future__ import division 7 | import os.path 8 | from PIL import Image 9 | import numpy as np 10 | import shutil 11 | import cv2 12 | from tqdm import tqdm 13 | 14 | ImgPath = '/home/pdluser/project/tmp_dir_for_tianchi_data/convertor/fold0/images/train/' #原始图片 15 | path = '/home/pdluser/project/tmp_dir_for_tianchi_data/convertor/fold0/labels/train/' #原始标注 16 | 17 | ProcessedPath = './process_data/' #生成后数据 18 | 19 | txtfiles = os.listdir(path) 20 | print(txtfiles) 21 | #patch img_size 22 | patch_size = 1024 23 | #slide window stride 24 | stride = 600 25 | 26 | txtfiles = tqdm(txtfiles) 27 | for file in txtfiles: #遍历txt进行操作 28 | image_pre, ext = os.path.splitext(file) 29 | imgfile = ImgPath + image_pre + '.jpg' 30 | txtfile = path + image_pre + '.txt' 31 | # if not os.path.isdir(file): # 判断是否是文件夹,不是文件夹才打开 32 | # print(file) 33 | 34 | img = cv2.imread(imgfile) 35 | sp = img.shape 36 | img_h, img_w = sp[0], sp[1] 37 | 38 | f = open(os.path.join(path, file), "r") 39 | lines = f.readlines() 40 | savepath_img = ProcessedPath + 'images' + '/train' #处理完的图片保存路径 41 | savepath_txt = ProcessedPath + 'labels' + '/train' #处理完的图片标签路径 42 | if not os.path.exists(savepath_img): 43 | os.makedirs(savepath_img) 44 | if not os.path.exists(savepath_txt): 45 | os.makedirs(savepath_txt) 46 | 47 | bndbox = [] 48 | boxname = [] 49 | for line in lines: 50 | c, x_c, y_c, w, h, _ = line.split(' ') 51 | c, x_c, y_c, w, h = float(c), float(x_c), float(y_c), float(w), float(h) 52 | bndbox.append([x_c, y_c, w, h]) 53 | boxname.append([c]) 54 | # print("boxname: ", boxname) 55 | # b = bndbox[1] 56 | # print(b.nodeName) 57 | #a: x起点, b: y起点, w: 宽, h: 高 58 | 59 | a = [] 60 | b = [] 61 | for a_ in range(0, img_w, stride): 62 | a.append(a_) 63 | for b_ in range(0, img_h, stride): 64 | b.append(b_) 65 | 66 | 67 | cropboxes = [] 68 | for i in a: 69 | for j in b: 70 | cropboxes.append([i, j, i + patch_size, j + patch_size]) 71 | i = 1 72 | top_size, bottom_size, left_size, right_size = (150, 0, 0, 0) 73 | 74 | def select(m, n, w, h): 75 | # m: x起点, n: y起点, w: 宽, h: 高 76 | bbox = [] 77 | # 查找图片中所有的 box 框 78 | for index in range(0, len(bndbox)): 79 | boxcls = boxname[index]#获取回归框的类别 80 | # print(bndbox[index]) 81 | # x min 82 | x1 = float(bndbox[index][0] * img_w - bndbox[index][2] * img_w/2) 83 | # y min 84 | y1 = float(bndbox[index][1] * img_h - bndbox[index][3] * img_h/2) 85 | # x max 86 | x2 = float(bndbox[index][0] * img_w + bndbox[index][2] * img_w/2) 87 | # y max 88 | y2 = float(bndbox[index][1] * img_h + bndbox[index][3] * img_h/2) 89 | # print("the index of the box is", index) 90 | # print("the box cls is",boxcls[0]) 91 | # print("the xy", x1, y1, x2, y2) 92 | #如果标记框在第一个范围内则存入bbox[] 并转换成新的格式 93 | if x1 >= m and x2 <= m + w and y1 >= n and y2 <= n + h: 94 | a1 = x1 - m 95 | b1 = y1 - n 96 | a2 = x2 - m 97 | b2 = y2 - n 98 | box_w = a2 - a1 99 | box_h = b2 - b1 100 | x_c = (a1 + box_w/2)/w 101 | y_c = (b1 + box_h/2)/h 102 | box_w = box_w / w 103 | box_h = box_h / h 104 | bbox.append([boxcls[0], x_c, y_c, box_w, box_h]) # 更新后的标记框 105 | if bbox is not None: 106 | return bbox 107 | else: 108 | return 0 109 | 110 | img = Image.open(imgfile) 111 | for j in range(0, len(cropboxes)): 112 | # print("the img number is :", j) 113 | # 获取在 patch 的 box 114 | Bboxes = select(cropboxes[j][0], cropboxes[j][1], patch_size, patch_size) 115 | if len(Bboxes): 116 | with open(savepath_txt + '/' + image_pre + '_' + '{}'.format(j) + '.txt', 'w') as f: 117 | for Bbox in Bboxes: 118 | for data in Bbox: 119 | f.write('{} '.format(data)) 120 | f.write('\n') 121 | 122 | #图片裁剪 123 | try: 124 | cropedimg = img.crop(cropboxes[j]) 125 | # print(np.array(cropedimg).shape) 126 | cropedimg.save(savepath_img + '/' + image_pre + '_' + str(j) + '.jpg') 127 | # print("done!") 128 | except: 129 | continue 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # pip install -r requirements.txt 2 | 3 | # base ---------------------------------------- 4 | Cython 5 | matplotlib>=3.2.2 6 | numpy>=1.18.5 7 | opencv-python>=4.1.2 8 | Pillow 9 | PyYAML 10 | scipy>=1.4.1 11 | tensorboard>=2.2 12 | torch>=1.7.0 13 | torchvision>=0.8.1 14 | tqdm>=4.41.0 15 | 16 | # logging ------------------------------------- 17 | # wandb 18 | 19 | # plotting ------------------------------------ 20 | seaborn>=0.11.0 21 | pandas 22 | 23 | # export -------------------------------------- 24 | # coremltools>=4.1 25 | # onnx>=1.8.1 26 | # scikit-learn==0.19.2 # for coreml quantization 27 | 28 | # extras -------------------------------------- 29 | thop # FLOPS computation 30 | pycocotools>=2.0 # COCO mAP 31 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | # python detect.py --source 2 | python submit.py --source /tcdata/guangdong1_round2_testB_20191024 --augment -------------------------------------------------------------------------------- /submit.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import torch.backends.cudnn as cudnn 4 | import json 5 | import cv2 6 | import os 7 | import torch 8 | from utils import google_utils 9 | from utils.datasets import * 10 | from utils.utils import * 11 | 12 | 13 | def detect(save_img=False): 14 | out, source, weights, view_img, save_txt, imgsz = \ 15 | opt.output, opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size 16 | webcam = source == '0' or source.startswith('rtsp') or source.startswith('http') or source.endswith('.txt') 17 | save_dir = opt.save_dir 18 | # Initialize 19 | device = torch_utils.select_device(opt.device) 20 | if os.path.exists(out): 21 | shutil.rmtree(out) # delete output folder 22 | os.makedirs(out) # make new output folder 23 | half = device.type != 'cpu' # half precision only supported on CUDA 24 | 25 | # Load model 26 | # google_utils.attempt_download(weights) 27 | model = torch.load(weights, map_location=device)['model'].float().eval() # load FP32 model 28 | imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size 29 | if half: 30 | model.half() # to FP16 31 | 32 | # Second-stage classifier 33 | classify = False 34 | if classify: 35 | modelc = torch_utils.load_classifier(name='resnet101', n=2) # initialize 36 | modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights 37 | modelc.to(device).eval() 38 | 39 | # Set Dataloader 40 | vid_path, vid_writer = None, None 41 | if webcam: 42 | view_img = True 43 | cudnn.benchmark = True # set True to speed up constant image size inference 44 | dataset = LoadStreams(source, img_size=imgsz) 45 | else: 46 | save_img = True 47 | dataset = LoadImagesTest(source, img_size=imgsz) 48 | 49 | # Get names and colors 50 | names = model.module.names if hasattr(model, 'module') else model.names 51 | colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))] 52 | 53 | # Run inference 54 | t0 = time.time() 55 | img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img 56 | _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once 57 | 58 | save_json = True 59 | result = [] 60 | for path, img, im0s, vid_cap in dataset: 61 | img = torch.from_numpy(img).to(device) 62 | img = img.half() if half else img.float() # uint8 to fp16/32 63 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 64 | if img.ndimension() == 3: 65 | img = img.unsqueeze(0) 66 | 67 | # Inference 68 | t1 = torch_utils.time_synchronized() 69 | pred = model(img, augment=opt.augment)[0] 70 | 71 | # Apply NMS 72 | pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms) 73 | t2 = torch_utils.time_synchronized() 74 | 75 | # Apply Classifier 76 | if classify: 77 | pred = apply_classifier(pred, modelc, img, im0s) 78 | 79 | # Process detections 80 | for i, det in enumerate(pred): # detections per image 81 | if webcam: # batch_size >= 1 82 | p, s, im0 = path[i], '%g: ' % i, im0s[i].copy() 83 | else: 84 | p, s, im0 = path, '', im0s 85 | 86 | save_path = str(Path(out) / Path(p).name) 87 | txt_path = str(Path(out) / Path(p).stem) + ('_%g' % dataset.frame if dataset.mode == 'video' else '') 88 | s += '%gx%g ' % img.shape[2:] # print string 89 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh 90 | if det is not None and len(det): 91 | # Rescale boxes from img_size to im0 size 92 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 93 | 94 | # Print results 95 | for c in det[:, -1].unique(): 96 | n = (det[:, -1] == c).sum() # detections per class 97 | s += '%g %ss, ' % (n, names[int(c)]) # add to string 98 | 99 | # Write results 100 | for *xyxy, conf, cls in det: 101 | if save_txt: # Write to file 102 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 103 | with open(txt_path + '.txt', 'a') as f: 104 | f.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format 105 | 106 | # write jiang ################# 107 | if save_json: 108 | name = os.path.split(txt_path)[-1] 109 | print(name) 110 | 111 | x1, y1, x2, y2 = float(xyxy[0]), float(xyxy[1]), float(xyxy[2]), float(xyxy[3]) 112 | bbox = [x1, y1, x2, y2] 113 | img_name = name 114 | conf = float(conf) 115 | 116 | #add solution remove other 117 | result.append( 118 | {'name': img_name+'.jpg', 'category': int(cls+1), 'bbox': bbox, 119 | 'score': conf}) 120 | print("result: ", {'name': img_name+'.jpg', 'category': int(cls+1), 'bbox': bbox,'score': conf}) 121 | 122 | if save_img or view_img: # Add bbox to image 123 | label = '%s %.2f' % (names[int(cls)], conf) 124 | plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3) 125 | 126 | # Print time (inference + NMS) 127 | print('%sDone. (%.3fs)' % (s, t2 - t1)) 128 | 129 | # Stream results 130 | if view_img: 131 | cv2.imshow(p, im0) 132 | if cv2.waitKey(1) == ord('q'): # q to quit 133 | raise StopIteration 134 | 135 | # Save results (image with detections) 136 | if save_img: 137 | if dataset.mode == 'images': 138 | cv2.imwrite(save_path, im0) 139 | else: 140 | if vid_path != save_path: # new video 141 | vid_path = save_path 142 | if isinstance(vid_writer, cv2.VideoWriter): 143 | vid_writer.release() # release previous video writer 144 | 145 | fourcc = 'mp4v' # output video codec 146 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 147 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 148 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 149 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h)) 150 | vid_writer.write(im0) 151 | 152 | if save_txt or save_img: 153 | print('Results saved to %s' % os.getcwd() + os.sep + out) 154 | if platform == 'darwin': # MacOS 155 | os.system('open ' + save_path) 156 | 157 | if save_json: 158 | if not os.path.exists(save_dir): 159 | os.makedirs(save_dir) 160 | with open(os.path.join(save_dir, "result.json"), 'w') as fp: 161 | json.dump(result, fp, indent=4, ensure_ascii=False) 162 | 163 | 164 | print('Done. (%.3fs)' % (time.time() - t0)) 165 | 166 | 167 | 168 | if __name__ == '__main__': 169 | parser = argparse.ArgumentParser() 170 | parser.add_argument('--weights', type=str, default='./runs/train/exp44/weights/best.pt', help='model.pt path') 171 | parser.add_argument('--save_dir', type=str, default='./', help='result save dir') 172 | # parser.add_argument('--source', type=str, default='convertor/fold0/images/val', help='source') # file/folder, 0 for webcam 173 | parser.add_argument('--source', type=str, default='../../data/guangdong1_round2_train_part1_20190924/defect', 174 | help='source') # file/folder, 0 for webcam 175 | parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder 176 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 177 | parser.add_argument('--conf-thres', type=float, default=0.04, help='object confidence threshold') 178 | parser.add_argument('--iou-thres', type=float, default=0.05, help='IOU threshold for NMS') 179 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 180 | parser.add_argument('--view-img', action='store_true', help='display results') 181 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 182 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class') 183 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 184 | parser.add_argument('--augment', action='store_true', help='augmented inference') 185 | parser.add_argument('--update', action='store_true', help='update all models') 186 | opt = parser.parse_args() 187 | print(opt) 188 | 189 | with torch.no_grad(): 190 | if opt.update: # update all models (to fix SourceChangeWarning) 191 | for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov3-spp.pt']: 192 | detect() 193 | create_pretrained(opt.weights, opt.weights) 194 | else: 195 | detect() -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | import os 4 | from pathlib import Path 5 | from threading import Thread 6 | 7 | import numpy as np 8 | import torch 9 | import yaml 10 | from tqdm import tqdm 11 | 12 | from models.experimental import attempt_load 13 | from utils.datasets import create_dataloader 14 | from utils.general import coco80_to_coco91_class, check_dataset, check_file, check_img_size, check_requirements, \ 15 | box_iou, non_max_suppression, scale_coords, xyxy2xywh, xywh2xyxy, set_logging, increment_path, colorstr 16 | from utils.metrics import ap_per_class, ConfusionMatrix 17 | from utils.plots import plot_images, output_to_target, plot_study_txt 18 | from utils.torch_utils import select_device, time_synchronized 19 | 20 | 21 | def test(data, 22 | weights=None, 23 | batch_size=32, 24 | imgsz=640, 25 | conf_thres=0.001, 26 | iou_thres=0.6, # for NMS 27 | save_json=False, 28 | single_cls=False, 29 | augment=False, 30 | verbose=False, 31 | model=None, 32 | dataloader=None, 33 | save_dir=Path(''), # for saving images 34 | save_txt=False, # for auto-labelling 35 | save_hybrid=False, # for hybrid auto-labelling 36 | save_conf=False, # save auto-label confidences 37 | plots=True, 38 | log_imgs=0, # number of logged images 39 | compute_loss=None): 40 | # Initialize/load model and set device 41 | training = model is not None 42 | if training: # called by train.py 43 | device = next(model.parameters()).device # get model device 44 | 45 | else: # called directly 46 | set_logging() 47 | device = select_device(opt.device, batch_size=batch_size) 48 | 49 | # Directories 50 | save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run 51 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir 52 | 53 | # Load model 54 | model = attempt_load(weights, map_location=device) # load FP32 model 55 | gs = max(int(model.stride.max()), 32) # grid size (max stride) 56 | imgsz = check_img_size(imgsz, s=gs) # check img_size 57 | 58 | # Multi-GPU disabled, incompatible with .half() https://github.com/ultralytics/yolov5/issues/99 59 | # if device.type != 'cpu' and torch.cuda.device_count() > 1: 60 | # model = nn.DataParallel(model) 61 | 62 | # Half 63 | half = device.type != 'cpu' # half precision only supported on CUDA 64 | if half: 65 | model.half() 66 | 67 | # Configure 68 | model.eval() 69 | is_coco = data.endswith('coco.yaml') # is COCO dataset 70 | with open(data) as f: 71 | data = yaml.load(f, Loader=yaml.SafeLoader) # model dict 72 | check_dataset(data) # check 73 | nc = 1 if single_cls else int(data['nc']) # number of classes 74 | iouv = torch.linspace(0.5, 0.95, 10).to(device) # iou vector for mAP@0.5:0.95 75 | niou = iouv.numel() 76 | 77 | # Logging 78 | log_imgs, wandb = min(log_imgs, 100), None # ceil 79 | try: 80 | import wandb # Weights & Biases 81 | except ImportError: 82 | log_imgs = 0 83 | 84 | # Dataloader 85 | if not training: 86 | if device.type != 'cpu': 87 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once 88 | path = data['test'] if opt.task == 'test' else data['val'] # path to val/test images 89 | dataloader = create_dataloader(path, imgsz, batch_size, gs, opt, pad=0.5, rect=True, 90 | prefix=colorstr('test: ' if opt.task == 'test' else 'val: '))[0] 91 | 92 | seen = 0 93 | confusion_matrix = ConfusionMatrix(nc=nc) 94 | names = {k: v for k, v in enumerate(model.names if hasattr(model, 'names') else model.module.names)} 95 | coco91class = coco80_to_coco91_class() 96 | s = ('%20s' + '%12s' * 6) % ('Class', 'Images', 'Targets', 'P', 'R', 'mAP@.5', 'mAP@.5:.95') 97 | p, r, f1, mp, mr, map50, map, t0, t1 = 0., 0., 0., 0., 0., 0., 0., 0., 0. 98 | loss = torch.zeros(3, device=device) 99 | jdict, stats, ap, ap_class, wandb_images = [], [], [], [], [] 100 | for batch_i, (img, targets, paths, shapes) in enumerate(tqdm(dataloader, desc=s)): 101 | img = img.to(device, non_blocking=True) 102 | img = img.half() if half else img.float() # uint8 to fp16/32 103 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 104 | targets = targets.to(device) 105 | nb, _, height, width = img.shape # batch size, channels, height, width 106 | 107 | with torch.no_grad(): 108 | # Run model 109 | t = time_synchronized() 110 | out, train_out = model(img, augment=augment) # inference and training outputs 111 | t0 += time_synchronized() - t 112 | 113 | # Compute loss 114 | if compute_loss: 115 | loss += compute_loss([x.float() for x in train_out], targets)[1][:3] # box, obj, cls 116 | 117 | # Run NMS 118 | targets[:, 2:] *= torch.Tensor([width, height, width, height]).to(device) # to pixels 119 | lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling 120 | t = time_synchronized() 121 | out = non_max_suppression(out, conf_thres=conf_thres, iou_thres=iou_thres, labels=lb, multi_label=True) 122 | t1 += time_synchronized() - t 123 | 124 | # Statistics per image 125 | for si, pred in enumerate(out): 126 | labels = targets[targets[:, 0] == si, 1:] 127 | nl = len(labels) 128 | tcls = labels[:, 0].tolist() if nl else [] # target class 129 | path = Path(paths[si]) 130 | seen += 1 131 | 132 | if len(pred) == 0: 133 | if nl: 134 | stats.append((torch.zeros(0, niou, dtype=torch.bool), torch.Tensor(), torch.Tensor(), tcls)) 135 | continue 136 | 137 | # Predictions 138 | predn = pred.clone() 139 | scale_coords(img[si].shape[1:], predn[:, :4], shapes[si][0], shapes[si][1]) # native-space pred 140 | 141 | # Append to text file 142 | if save_txt: 143 | gn = torch.tensor(shapes[si][0])[[1, 0, 1, 0]] # normalization gain whwh 144 | for *xyxy, conf, cls in predn.tolist(): 145 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 146 | line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format 147 | with open(save_dir / 'labels' / (path.stem + '.txt'), 'a') as f: 148 | f.write(('%g ' * len(line)).rstrip() % line + '\n') 149 | 150 | # W&B logging 151 | if plots and len(wandb_images) < log_imgs: 152 | box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]}, 153 | "class_id": int(cls), 154 | "box_caption": "%s %.3f" % (names[cls], conf), 155 | "scores": {"class_score": conf}, 156 | "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()] 157 | boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space 158 | wandb_images.append(wandb.Image(img[si], boxes=boxes, caption=path.name)) 159 | 160 | # Append to pycocotools JSON dictionary 161 | if save_json: 162 | # [{"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}, ... 163 | image_id = int(path.stem) if path.stem.isnumeric() else path.stem 164 | box = xyxy2xywh(predn[:, :4]) # xywh 165 | box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner 166 | for p, b in zip(pred.tolist(), box.tolist()): 167 | jdict.append({'image_id': image_id, 168 | 'category_id': coco91class[int(p[5])] if is_coco else int(p[5]), 169 | 'bbox': [round(x, 3) for x in b], 170 | 'score': round(p[4], 5)}) 171 | 172 | # Assign all predictions as incorrect 173 | correct = torch.zeros(pred.shape[0], niou, dtype=torch.bool, device=device) 174 | if nl: 175 | detected = [] # target indices 176 | tcls_tensor = labels[:, 0] 177 | 178 | # target boxes 179 | tbox = xywh2xyxy(labels[:, 1:5]) 180 | scale_coords(img[si].shape[1:], tbox, shapes[si][0], shapes[si][1]) # native-space labels 181 | if plots: 182 | confusion_matrix.process_batch(predn, torch.cat((labels[:, 0:1], tbox), 1)) 183 | 184 | # Per target class 185 | for cls in torch.unique(tcls_tensor): 186 | ti = (cls == tcls_tensor).nonzero(as_tuple=False).view(-1) # prediction indices 187 | pi = (cls == pred[:, 5]).nonzero(as_tuple=False).view(-1) # target indices 188 | 189 | # Search for detections 190 | if pi.shape[0]: 191 | # Prediction to target ious 192 | ious, i = box_iou(predn[pi, :4], tbox[ti]).max(1) # best ious, indices 193 | 194 | # Append detections 195 | detected_set = set() 196 | for j in (ious > iouv[0]).nonzero(as_tuple=False): 197 | d = ti[i[j]] # detected target 198 | if d.item() not in detected_set: 199 | detected_set.add(d.item()) 200 | detected.append(d) 201 | correct[pi[j]] = ious[j] > iouv # iou_thres is 1xn 202 | if len(detected) == nl: # all targets already located in image 203 | break 204 | 205 | # Append statistics (correct, conf, pcls, tcls) 206 | stats.append((correct.cpu(), pred[:, 4].cpu(), pred[:, 5].cpu(), tcls)) 207 | 208 | # Plot images 209 | if plots and batch_i < 3: 210 | f = save_dir / f'test_batch{batch_i}_labels.jpg' # labels 211 | Thread(target=plot_images, args=(img, targets, paths, f, names), daemon=True).start() 212 | f = save_dir / f'test_batch{batch_i}_pred.jpg' # predictions 213 | Thread(target=plot_images, args=(img, output_to_target(out), paths, f, names), daemon=True).start() 214 | 215 | # Compute statistics 216 | stats = [np.concatenate(x, 0) for x in zip(*stats)] # to numpy 217 | if len(stats) and stats[0].any(): 218 | p, r, ap, f1, ap_class = ap_per_class(*stats, plot=plots, save_dir=save_dir, names=names) 219 | ap50, ap = ap[:, 0], ap.mean(1) # AP@0.5, AP@0.5:0.95 220 | mp, mr, map50, map = p.mean(), r.mean(), ap50.mean(), ap.mean() 221 | nt = np.bincount(stats[3].astype(np.int64), minlength=nc) # number of targets per class 222 | else: 223 | nt = torch.zeros(1) 224 | 225 | # Print results 226 | pf = '%20s' + '%12.3g' * 6 # print format 227 | print(pf % ('all', seen, nt.sum(), mp, mr, map50, map)) 228 | 229 | # Print results per class 230 | if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats): 231 | for i, c in enumerate(ap_class): 232 | print(pf % (names[c], seen, nt[c], p[i], r[i], ap50[i], ap[i])) 233 | 234 | # Print speeds 235 | t = tuple(x / seen * 1E3 for x in (t0, t1, t0 + t1)) + (imgsz, imgsz, batch_size) # tuple 236 | if not training: 237 | print('Speed: %.1f/%.1f/%.1f ms inference/NMS/total per %gx%g image at batch-size %g' % t) 238 | 239 | # Plots 240 | if plots: 241 | confusion_matrix.plot(save_dir=save_dir, names=list(names.values())) 242 | if wandb and wandb.run: 243 | val_batches = [wandb.Image(str(f), caption=f.name) for f in sorted(save_dir.glob('test*.jpg'))] 244 | wandb.log({"Images": wandb_images, "Validation": val_batches}, commit=False) 245 | 246 | # Save JSON 247 | if save_json and len(jdict): 248 | w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else '' # weights 249 | anno_json = '../coco/annotations/instances_val2017.json' # annotations json 250 | pred_json = str(save_dir / f"{w}_predictions.json") # predictions json 251 | print('\nEvaluating pycocotools mAP... saving %s...' % pred_json) 252 | with open(pred_json, 'w') as f: 253 | json.dump(jdict, f) 254 | 255 | try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb 256 | from pycocotools.coco import COCO 257 | from pycocotools.cocoeval import COCOeval 258 | 259 | anno = COCO(anno_json) # init annotations api 260 | pred = anno.loadRes(pred_json) # init predictions api 261 | eval = COCOeval(anno, pred, 'bbox') 262 | if is_coco: 263 | eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.img_files] # image IDs to evaluate 264 | eval.evaluate() 265 | eval.accumulate() 266 | eval.summarize() 267 | map, map50 = eval.stats[:2] # update results (mAP@0.5:0.95, mAP@0.5) 268 | except Exception as e: 269 | print(f'pycocotools unable to run: {e}') 270 | 271 | # Return results 272 | if not training: 273 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' 274 | print(f"Results saved to {save_dir}{s}") 275 | model.float() # for training 276 | maps = np.zeros(nc) + map 277 | for i, c in enumerate(ap_class): 278 | maps[c] = ap[i] 279 | return (mp, mr, map50, map, *(loss.cpu() / len(dataloader)).tolist()), maps, t 280 | 281 | 282 | if __name__ == '__main__': 283 | parser = argparse.ArgumentParser(prog='test.py') 284 | parser.add_argument('--weights', nargs='+', type=str, default='./weights/best.pt', help='model.pt path(s)') 285 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='*.data path') 286 | parser.add_argument('--batch-size', type=int, default=2, help='size of each image batch') 287 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 288 | parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold') 289 | parser.add_argument('--iou-thres', type=float, default=0.6, help='IOU threshold for NMS') 290 | parser.add_argument('--task', default='val', help="'val', 'test', 'study'") 291 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 292 | parser.add_argument('--single-cls', action='store_true', help='treat as single-class dataset') 293 | parser.add_argument('--augment', action='store_true', help='augmented inference') 294 | parser.add_argument('--verbose', action='store_true', help='report mAP by class') 295 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 296 | parser.add_argument('--save-hybrid', action='store_true', help='save label+prediction hybrid results to *.txt') 297 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') 298 | parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file') 299 | parser.add_argument('--project', default='runs/test', help='save to project/name') 300 | parser.add_argument('--name', default='exp', help='save to project/name') 301 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') 302 | opt = parser.parse_args() 303 | opt.save_json |= opt.data.endswith('coco.yaml') 304 | opt.data = check_file(opt.data) # check file 305 | print(opt) 306 | check_requirements() 307 | 308 | if opt.task in ['val', 'test']: # run normally 309 | test(opt.data, 310 | opt.weights, 311 | opt.batch_size, 312 | opt.img_size, 313 | opt.conf_thres, 314 | opt.iou_thres, 315 | opt.save_json, 316 | opt.single_cls, 317 | opt.augment, 318 | opt.verbose, 319 | save_txt=opt.save_txt | opt.save_hybrid, 320 | save_hybrid=opt.save_hybrid, 321 | save_conf=opt.save_conf, 322 | ) 323 | 324 | elif opt.task == 'speed': # speed benchmarks 325 | for w in opt.weights: 326 | test(opt.data, w, opt.batch_size, opt.img_size, 0.25, 0.45, save_json=False, plots=False) 327 | 328 | elif opt.task == 'study': # run over a range of settings and save/plot 329 | x = list(range(256, 1536 + 128, 128)) # x axis (image sizes) 330 | for w in opt.weights: 331 | f = f'study_{Path(opt.data).stem}_{Path(w).stem}.txt' # filename to save to 332 | y = [] # y axis 333 | for i in x: # img-size 334 | print(f'\nRunning {f} point {i}...') 335 | r, _, t = test(opt.data, w, opt.batch_size, i, opt.conf_thres, opt.iou_thres, opt.save_json, 336 | plots=False) 337 | y.append(r + t) # results and times 338 | np.savetxt(f, y, fmt='%10.4g') # save 339 | os.system('zip -r study.zip study_*.txt') 340 | plot_study_txt(x=x) # plot 341 | -------------------------------------------------------------------------------- /train.sh: -------------------------------------------------------------------------------- 1 | python convertTrainLabel.py 2 | python process_data_yolo.py 3 | rm -rf ./convertor 4 | python train.py -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__init__.py -------------------------------------------------------------------------------- /utils/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /utils/__pycache__/datasets.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__pycache__/datasets.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/datasets.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__pycache__/datasets.cpython-38.pyc -------------------------------------------------------------------------------- /utils/__pycache__/google_utils.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__pycache__/google_utils.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/google_utils.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__pycache__/google_utils.cpython-38.pyc -------------------------------------------------------------------------------- /utils/__pycache__/torch_utils.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__pycache__/torch_utils.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/torch_utils.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__pycache__/torch_utils.cpython-38.pyc -------------------------------------------------------------------------------- /utils/__pycache__/utils.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__pycache__/utils.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/utils.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/__pycache__/utils.cpython-38.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 | class MemoryEfficientSwish(nn.Module): 23 | class F(torch.autograd.Function): 24 | @staticmethod 25 | def forward(ctx, x): 26 | ctx.save_for_backward(x) 27 | return x * torch.sigmoid(x) 28 | 29 | @staticmethod 30 | def backward(ctx, grad_output): 31 | x = ctx.saved_tensors[0] 32 | sx = torch.sigmoid(x) 33 | return grad_output * (sx * (1 + x * (1 - sx))) 34 | 35 | def forward(self, x): 36 | return self.F.apply(x) 37 | 38 | 39 | # Mish https://github.com/digantamisra98/Mish -------------------------------------------------------------------------- 40 | class Mish(nn.Module): 41 | @staticmethod 42 | def forward(x): 43 | return x * F.softplus(x).tanh() 44 | 45 | 46 | class MemoryEfficientMish(nn.Module): 47 | class F(torch.autograd.Function): 48 | @staticmethod 49 | def forward(ctx, x): 50 | ctx.save_for_backward(x) 51 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) 52 | 53 | @staticmethod 54 | def backward(ctx, grad_output): 55 | x = ctx.saved_tensors[0] 56 | sx = torch.sigmoid(x) 57 | fx = F.softplus(x).tanh() 58 | return grad_output * (fx + x * sx * (1 - fx * fx)) 59 | 60 | def forward(self, x): 61 | return self.F.apply(x) 62 | 63 | 64 | # FReLU https://arxiv.org/abs/2007.11824 ------------------------------------------------------------------------------- 65 | class FReLU(nn.Module): 66 | def __init__(self, c1, k=3): # ch_in, kernel 67 | super().__init__() 68 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) 69 | self.bn = nn.BatchNorm2d(c1) 70 | 71 | def forward(self, x): 72 | return torch.max(x, self.bn(self.conv(x))) 73 | -------------------------------------------------------------------------------- /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 | bpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2)) 41 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='') 42 | if bpr < 0.98: # threshold to recompute 43 | print('. Attempting to improve anchors, please wait...') 44 | na = m.anchor_grid.numel() // 2 # number of anchors 45 | new_anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) 46 | new_bpr = metric(new_anchors.reshape(-1, 2))[0] 47 | if new_bpr > bpr: # replace anchors 48 | new_anchors = torch.tensor(new_anchors, device=m.anchors.device).type_as(m.anchors) 49 | m.anchor_grid[:] = new_anchors.clone().view_as(m.anchor_grid) # for inference 50 | m.anchors[:] = new_anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss 51 | check_anchor_order(m) 52 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.') 53 | else: 54 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.') 55 | print('') # newline 56 | 57 | 58 | def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): 59 | """ Creates kmeans-evolved anchors from training dataset 60 | 61 | Arguments: 62 | path: path to dataset *.yaml, or a loaded dataset 63 | n: number of anchors 64 | img_size: image size used for training 65 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 66 | gen: generations to evolve anchors using genetic algorithm 67 | verbose: print all results 68 | 69 | Return: 70 | k: kmeans evolved anchors 71 | 72 | Usage: 73 | from utils.autoanchor import *; _ = kmean_anchors() 74 | """ 75 | thr = 1. / thr 76 | prefix = colorstr('autoanchor: ') 77 | 78 | def metric(k, wh): # compute metrics 79 | r = wh[:, None] / k[None] 80 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric 81 | # x = wh_iou(wh, torch.tensor(k)) # iou metric 82 | return x, x.max(1)[0] # x, best_x 83 | 84 | def anchor_fitness(k): # mutation fitness 85 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh) 86 | return (best * (best > thr).float()).mean() # fitness 87 | 88 | def print_results(k): 89 | k = k[np.argsort(k.prod(1))] # sort small to large 90 | x, best = metric(k, wh0) 91 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr 92 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr') 93 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' 94 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='') 95 | for i, x in enumerate(k): 96 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg 97 | return k 98 | 99 | if isinstance(path, str): # *.yaml file 100 | with open(path) as f: 101 | data_dict = yaml.load(f, Loader=yaml.SafeLoader) # model dict 102 | from utils.datasets import LoadImagesAndLabels 103 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) 104 | else: 105 | dataset = path # dataset 106 | 107 | # Get label wh 108 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) 109 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh 110 | 111 | # Filter 112 | i = (wh0 < 3.0).any(1).sum() 113 | if i: 114 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.') 115 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels 116 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 117 | 118 | # Kmeans calculation 119 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...') 120 | s = wh.std(0) # sigmas for whitening 121 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance 122 | k *= s 123 | wh = torch.tensor(wh, dtype=torch.float32) # filtered 124 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered 125 | k = print_results(k) 126 | 127 | # Plot 128 | # k, d = [None] * 20, [None] * 20 129 | # for i in tqdm(range(1, 21)): 130 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance 131 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) 132 | # ax = ax.ravel() 133 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') 134 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh 135 | # ax[0].hist(wh[wh[:, 0]<100, 0],400) 136 | # ax[1].hist(wh[wh[:, 1]<100, 1],400) 137 | # fig.savefig('wh.png', dpi=200) 138 | 139 | # Evolve 140 | npr = np.random 141 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma 142 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar 143 | for _ in pbar: 144 | v = np.ones(sh) 145 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates) 146 | v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) 147 | kg = (k.copy() * v).clip(min=2.0) 148 | fg = anchor_fitness(kg) 149 | if fg > f: 150 | f, k = fg, kg.copy() 151 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' 152 | if verbose: 153 | print_results(k) 154 | 155 | return print_results(k) 156 | -------------------------------------------------------------------------------- /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("'", '').lower()) 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 | tag = subprocess.check_output('git tag', shell=True).decode().split()[-1] 31 | 32 | name = file.name 33 | if name in assets: 34 | msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/' 35 | redundant = False # second download option 36 | try: # GitHub 37 | url = f'https://github.com/{repo}/releases/download/{tag}/{name}' 38 | print(f'Downloading {url} to {file}...') 39 | torch.hub.download_url_to_file(url, file) 40 | assert file.exists() and file.stat().st_size > 1E6 # check 41 | except Exception as e: # GCP 42 | print(f'Download error: {e}') 43 | assert redundant, 'No secondary mirror' 44 | url = f'https://storage.googleapis.com/{repo}/ckpt/{name}' 45 | print(f'Downloading {url} to {file}...') 46 | os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights) 47 | finally: 48 | if not file.exists() or file.stat().st_size < 1E6: # check 49 | file.unlink(missing_ok=True) # remove partial downloads 50 | print(f'ERROR: Download failure: {msg}') 51 | print('') 52 | return 53 | 54 | 55 | def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'): 56 | # Downloads a file from Google Drive. from yolov5.utils.google_utils import *; gdrive_download() 57 | t = time.time() 58 | file = Path(file) 59 | cookie = Path('cookie') # gdrive cookie 60 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='') 61 | file.unlink(missing_ok=True) # remove existing file 62 | cookie.unlink(missing_ok=True) # remove existing cookie 63 | 64 | # Attempt file download 65 | out = "NUL" if platform.system() == "Windows" else "/dev/null" 66 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}') 67 | if os.path.exists('cookie'): # large file 68 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}' 69 | else: # small file 70 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"' 71 | r = os.system(s) # execute, capture return 72 | cookie.unlink(missing_ok=True) # remove existing cookie 73 | 74 | # Error check 75 | if r != 0: 76 | file.unlink(missing_ok=True) # remove partial 77 | print('Download error ') # raise Exception('Download error') 78 | return r 79 | 80 | # Unzip if archive 81 | if file.suffix == '.zip': 82 | print('unzipping... ', end='') 83 | os.system(f'unzip -q {file}') # unzip 84 | file.unlink() # remove zip to free space 85 | 86 | print(f'Done ({time.time() - t:.1f}s)') 87 | return r 88 | 89 | 90 | def get_token(cookie="./cookie"): 91 | with open(cookie) as f: 92 | for line in f: 93 | if "download" in line: 94 | return line.split()[-1] 95 | return "" 96 | 97 | # def upload_blob(bucket_name, source_file_name, destination_blob_name): 98 | # # Uploads a file to a bucket 99 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python 100 | # 101 | # storage_client = storage.Client() 102 | # bucket = storage_client.get_bucket(bucket_name) 103 | # blob = bucket.blob(destination_blob_name) 104 | # 105 | # blob.upload_from_filename(source_file_name) 106 | # 107 | # print('File {} uploaded to {}.'.format( 108 | # source_file_name, 109 | # destination_blob_name)) 110 | # 111 | # 112 | # def download_blob(bucket_name, source_blob_name, destination_file_name): 113 | # # Uploads a blob from a bucket 114 | # storage_client = storage.Client() 115 | # bucket = storage_client.get_bucket(bucket_name) 116 | # blob = bucket.blob(source_blob_name) 117 | # 118 | # blob.download_to_filename(destination_file_name) 119 | # 120 | # print('Blob {} downloaded to {}.'.format( 121 | # source_blob_name, 122 | # destination_file_name)) 123 | -------------------------------------------------------------------------------- /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=0.0) 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 | return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32') 79 | 80 | 81 | def compute_ap(recall, precision): 82 | """ Compute the average precision, given the recall and precision curves 83 | # Arguments 84 | recall: The recall curve (list) 85 | precision: The precision curve (list) 86 | # Returns 87 | Average precision, precision curve, recall curve 88 | """ 89 | 90 | # Append sentinel values to beginning and end 91 | mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01])) 92 | mpre = np.concatenate(([1.], precision, [0.])) 93 | 94 | # Compute the precision envelope 95 | mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) 96 | 97 | # Integrate area under curve 98 | method = 'interp' # methods: 'continuous', 'interp' 99 | if method == 'interp': 100 | x = np.linspace(0, 1, 101) # 101-point interp (COCO) 101 | ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate 102 | else: # 'continuous' 103 | i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes 104 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve 105 | 106 | return ap, mpre, mrec 107 | 108 | 109 | class ConfusionMatrix: 110 | # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix 111 | def __init__(self, nc, conf=0.25, iou_thres=0.45): 112 | self.matrix = np.zeros((nc + 1, nc + 1)) 113 | self.nc = nc # number of classes 114 | self.conf = conf 115 | self.iou_thres = iou_thres 116 | 117 | def process_batch(self, detections, labels): 118 | """ 119 | Return intersection-over-union (Jaccard index) of boxes. 120 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format. 121 | Arguments: 122 | detections (Array[N, 6]), x1, y1, x2, y2, conf, class 123 | labels (Array[M, 5]), class, x1, y1, x2, y2 124 | Returns: 125 | None, updates confusion matrix accordingly 126 | """ 127 | detections = detections[detections[:, 4] > self.conf] 128 | gt_classes = labels[:, 0].int() 129 | detection_classes = detections[:, 5].int() 130 | iou = general.box_iou(labels[:, 1:], detections[:, :4]) 131 | 132 | x = torch.where(iou > self.iou_thres) 133 | if x[0].shape[0]: 134 | matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() 135 | if x[0].shape[0] > 1: 136 | matches = matches[matches[:, 2].argsort()[::-1]] 137 | matches = matches[np.unique(matches[:, 1], return_index=True)[1]] 138 | matches = matches[matches[:, 2].argsort()[::-1]] 139 | matches = matches[np.unique(matches[:, 0], return_index=True)[1]] 140 | else: 141 | matches = np.zeros((0, 3)) 142 | 143 | n = matches.shape[0] > 0 144 | m0, m1, _ = matches.transpose().astype(np.int16) 145 | for i, gc in enumerate(gt_classes): 146 | j = m0 == i 147 | if n and sum(j) == 1: 148 | self.matrix[gc, detection_classes[m1[j]]] += 1 # correct 149 | else: 150 | self.matrix[gc, self.nc] += 1 # background FP 151 | 152 | if n: 153 | for i, dc in enumerate(detection_classes): 154 | if not any(m1 == i): 155 | self.matrix[self.nc, dc] += 1 # background FN 156 | 157 | def matrix(self): 158 | return self.matrix 159 | 160 | def plot(self, save_dir='', names=()): 161 | try: 162 | import seaborn as sn 163 | 164 | array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize 165 | array[array < 0.005] = np.nan # don't annotate (would appear as 0.00) 166 | 167 | fig = plt.figure(figsize=(12, 9), tight_layout=True) 168 | sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size 169 | labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels 170 | sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True, 171 | xticklabels=names + ['background FN'] if labels else "auto", 172 | yticklabels=names + ['background FP'] if labels else "auto").set_facecolor((1, 1, 1)) 173 | fig.axes[0].set_xlabel('True') 174 | fig.axes[0].set_ylabel('Predicted') 175 | fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250) 176 | except Exception as e: 177 | pass 178 | 179 | def print(self): 180 | for i in range(self.nc + 1): 181 | print(' '.join(map(str, self.matrix[i]))) 182 | 183 | 184 | # Plots ---------------------------------------------------------------------------------------------------------------- 185 | 186 | def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()): 187 | # Precision-recall curve 188 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) 189 | py = np.stack(py, axis=1) 190 | 191 | if 0 < len(names) < 21: # display per-class legend if < 21 classes 192 | for i, y in enumerate(py.T): 193 | ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision) 194 | else: 195 | ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision) 196 | 197 | ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean()) 198 | ax.set_xlabel('Recall') 199 | ax.set_ylabel('Precision') 200 | ax.set_xlim(0, 1) 201 | ax.set_ylim(0, 1) 202 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") 203 | fig.savefig(Path(save_dir), dpi=250) 204 | 205 | 206 | def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'): 207 | # Metric-confidence curve 208 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) 209 | 210 | if 0 < len(names) < 21: # display per-class legend if < 21 classes 211 | for i, y in enumerate(py): 212 | ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric) 213 | else: 214 | ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric) 215 | 216 | y = py.mean(0) 217 | ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}') 218 | ax.set_xlabel(xlabel) 219 | ax.set_ylabel(ylabel) 220 | ax.set_xlim(0, 1) 221 | ax.set_ylim(0, 1) 222 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") 223 | fig.savefig(Path(save_dir), dpi=250) 224 | -------------------------------------------------------------------------------- /utils/torch_utils.py: -------------------------------------------------------------------------------- 1 | # PyTorch utils 2 | 3 | import logging 4 | import math 5 | import os 6 | import subprocess 7 | import time 8 | from contextlib import contextmanager 9 | from copy import deepcopy 10 | from pathlib import Path 11 | 12 | import torch 13 | import torch.backends.cudnn as cudnn 14 | import torch.nn as nn 15 | import torch.nn.functional as F 16 | import torchvision 17 | 18 | try: 19 | import thop # for FLOPS computation 20 | except ImportError: 21 | thop = None 22 | logger = logging.getLogger(__name__) 23 | 24 | 25 | @contextmanager 26 | def torch_distributed_zero_first(local_rank: int): 27 | """ 28 | Decorator to make all processes in distributed training wait for each local_master to do something. 29 | """ 30 | if local_rank not in [-1, 0]: 31 | torch.distributed.barrier() 32 | yield 33 | if local_rank == 0: 34 | torch.distributed.barrier() 35 | 36 | 37 | def init_torch_seeds(seed=0): 38 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html 39 | torch.manual_seed(seed) 40 | if seed == 0: # slower, more reproducible 41 | cudnn.benchmark, cudnn.deterministic = False, True 42 | else: # faster, less reproducible 43 | cudnn.benchmark, cudnn.deterministic = True, False 44 | 45 | 46 | def git_describe(): 47 | # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe 48 | if Path('.git').exists(): 49 | return subprocess.check_output('git describe --tags --long --always', shell=True).decode('utf-8')[:-1] 50 | else: 51 | return '' 52 | 53 | 54 | def select_device(device='', batch_size=None): 55 | # device = 'cpu' or '0' or '0,1,2,3' 56 | s = f'YOLOv5 torch {torch.__version__} ' # string 57 | cpu = device.lower() == 'cpu' 58 | if cpu: 59 | os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False 60 | elif device: # non-cpu device requested 61 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable 62 | assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability 63 | 64 | cuda = not cpu and torch.cuda.is_available() 65 | if cuda: 66 | n = torch.cuda.device_count() 67 | if n > 1 and batch_size: # check that batch_size is compatible with device_count 68 | assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' 69 | space = ' ' * len(s) 70 | for i, d in enumerate(device.split(',') if device else range(n)): 71 | p = torch.cuda.get_device_properties(i) 72 | s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB 73 | else: 74 | s += 'CPU\n' 75 | 76 | logger.info(s) # skip a line 77 | return torch.device('cuda:0' if cuda else 'cpu') 78 | 79 | 80 | def time_synchronized(): 81 | # pytorch-accurate time 82 | if torch.cuda.is_available(): 83 | torch.cuda.synchronize() 84 | return time.time() 85 | 86 | 87 | def profile(x, ops, n=100, device=None): 88 | # profile a pytorch module or list of modules. Example usage: 89 | # x = torch.randn(16, 3, 640, 640) # input 90 | # m1 = lambda x: x * torch.sigmoid(x) 91 | # m2 = nn.SiLU() 92 | # profile(x, [m1, m2], n=100) # profile speed over 100 iterations 93 | 94 | device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') 95 | x = x.to(device) 96 | x.requires_grad = True 97 | print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '') 98 | print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}") 99 | for m in ops if isinstance(ops, list) else [ops]: 100 | m = m.to(device) if hasattr(m, 'to') else m # device 101 | m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type 102 | dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward 103 | try: 104 | flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS 105 | except: 106 | flops = 0 107 | 108 | for _ in range(n): 109 | t[0] = time_synchronized() 110 | y = m(x) 111 | t[1] = time_synchronized() 112 | try: 113 | _ = y.sum().backward() 114 | t[2] = time_synchronized() 115 | except: # no backward method 116 | t[2] = float('nan') 117 | dtf += (t[1] - t[0]) * 1000 / n # ms per op forward 118 | dtb += (t[2] - t[1]) * 1000 / n # ms per op backward 119 | 120 | s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' 121 | s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list' 122 | p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters 123 | print(f'{p:12.4g}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}') 124 | 125 | 126 | def is_parallel(model): 127 | return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) 128 | 129 | 130 | def intersect_dicts(da, db, exclude=()): 131 | # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values 132 | 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} 133 | 134 | 135 | def initialize_weights(model): 136 | for m in model.modules(): 137 | t = type(m) 138 | if t is nn.Conv2d: 139 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 140 | elif t is nn.BatchNorm2d: 141 | m.eps = 1e-3 142 | m.momentum = 0.03 143 | elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]: 144 | m.inplace = True 145 | 146 | 147 | def find_modules(model, mclass=nn.Conv2d): 148 | # Finds layer indices matching module class 'mclass' 149 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] 150 | 151 | 152 | def sparsity(model): 153 | # Return global model sparsity 154 | a, b = 0., 0. 155 | for p in model.parameters(): 156 | a += p.numel() 157 | b += (p == 0).sum() 158 | return b / a 159 | 160 | 161 | def prune(model, amount=0.3): 162 | # Prune model to requested global sparsity 163 | import torch.nn.utils.prune as prune 164 | print('Pruning model... ', end='') 165 | for name, m in model.named_modules(): 166 | if isinstance(m, nn.Conv2d): 167 | prune.l1_unstructured(m, name='weight', amount=amount) # prune 168 | prune.remove(m, 'weight') # make permanent 169 | print(' %.3g global sparsity' % sparsity(model)) 170 | 171 | 172 | def fuse_conv_and_bn(conv, bn): 173 | # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ 174 | fusedconv = nn.Conv2d(conv.in_channels, 175 | conv.out_channels, 176 | kernel_size=conv.kernel_size, 177 | stride=conv.stride, 178 | padding=conv.padding, 179 | groups=conv.groups, 180 | bias=True).requires_grad_(False).to(conv.weight.device) 181 | 182 | # prepare filters 183 | w_conv = conv.weight.clone().view(conv.out_channels, -1) 184 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) 185 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size())) 186 | 187 | # prepare spatial bias 188 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias 189 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) 190 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) 191 | 192 | return fusedconv 193 | 194 | 195 | def model_info(model, verbose=False, img_size=640): 196 | # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320] 197 | n_p = sum(x.numel() for x in model.parameters()) # number parameters 198 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients 199 | if verbose: 200 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma')) 201 | for i, (name, p) in enumerate(model.named_parameters()): 202 | name = name.replace('module_list.', '') 203 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' % 204 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) 205 | 206 | try: # FLOPS 207 | from thop import profile 208 | stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 209 | img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input 210 | flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS 211 | img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float 212 | fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS 213 | except (ImportError, Exception): 214 | fs = '' 215 | 216 | logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") 217 | 218 | 219 | def load_classifier(name='resnet101', n=2): 220 | # Loads a pretrained model reshaped to n-class output 221 | model = torchvision.models.__dict__[name](pretrained=True) 222 | 223 | # ResNet model properties 224 | # input_size = [3, 224, 224] 225 | # input_space = 'RGB' 226 | # input_range = [0, 1] 227 | # mean = [0.485, 0.456, 0.406] 228 | # std = [0.229, 0.224, 0.225] 229 | 230 | # Reshape output to n classes 231 | filters = model.fc.weight.shape[1] 232 | model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True) 233 | model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True) 234 | model.fc.out_features = n 235 | return model 236 | 237 | 238 | def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) 239 | # scales img(bs,3,y,x) by ratio constrained to gs-multiple 240 | if ratio == 1.0: 241 | return img 242 | else: 243 | h, w = img.shape[2:] 244 | s = (int(h * ratio), int(w * ratio)) # new size 245 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize 246 | if not same_shape: # pad/crop img 247 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)] 248 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean 249 | 250 | 251 | def copy_attr(a, b, include=(), exclude=()): 252 | # Copy attributes from b to a, options to only include [...] and to exclude [...] 253 | for k, v in b.__dict__.items(): 254 | if (len(include) and k not in include) or k.startswith('_') or k in exclude: 255 | continue 256 | else: 257 | setattr(a, k, v) 258 | 259 | 260 | class ModelEMA: 261 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models 262 | Keep a moving average of everything in the model state_dict (parameters and buffers). 263 | This is intended to allow functionality like 264 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage 265 | A smoothed version of the weights is necessary for some training schemes to perform well. 266 | This class is sensitive where it is initialized in the sequence of model init, 267 | GPU assignment and distributed training wrappers. 268 | """ 269 | 270 | def __init__(self, model, decay=0.9999, updates=0): 271 | # Create EMA 272 | self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA 273 | # if next(model.parameters()).device.type != 'cpu': 274 | # self.ema.half() # FP16 EMA 275 | self.updates = updates # number of EMA updates 276 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs) 277 | for p in self.ema.parameters(): 278 | p.requires_grad_(False) 279 | 280 | def update(self, model): 281 | # Update EMA parameters 282 | with torch.no_grad(): 283 | self.updates += 1 284 | d = self.decay(self.updates) 285 | 286 | msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict 287 | for k, v in self.ema.state_dict().items(): 288 | if v.dtype.is_floating_point: 289 | v *= d 290 | v += (1. - d) * msd[k].detach() 291 | 292 | def update_attr(self, model, include=(), exclude=('process_group', 'reducer')): 293 | # Update EMA attributes 294 | copy_attr(self.ema, model, include, exclude) 295 | -------------------------------------------------------------------------------- /utils/wandb_logging/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pprp/datawhale_cv_competition/aa725671572b86ef99204450c92e7e5a9950ca49/utils/wandb_logging/__init__.py -------------------------------------------------------------------------------- /utils/wandb_logging/log_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from pathlib import Path 3 | 4 | import yaml 5 | 6 | from wandb_utils import WandbLogger 7 | from utils.datasets import LoadImagesAndLabels 8 | 9 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' 10 | 11 | 12 | def create_dataset_artifact(opt): 13 | with open(opt.data) as f: 14 | data = yaml.load(f, Loader=yaml.SafeLoader) # data dict 15 | logger = WandbLogger(opt, '', None, data, job_type='create_dataset') 16 | nc, names = (1, ['item']) if opt.single_cls else (int(data['nc']), data['names']) 17 | names = {k: v for k, v in enumerate(names)} # to index dictionary 18 | logger.log_dataset_artifact(LoadImagesAndLabels(data['train']), names, name='train') # trainset 19 | logger.log_dataset_artifact(LoadImagesAndLabels(data['val']), names, name='val') # valset 20 | 21 | # Update data.yaml with artifact links 22 | data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(opt.project) / 'train') 23 | data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(opt.project) / 'val') 24 | path = opt.data if opt.overwrite_config else opt.data.replace('.', '_wandb.') # updated data.yaml path 25 | data.pop('download', None) # download via artifact instead of predefined field 'download:' 26 | with open(path, 'w') as f: 27 | yaml.dump(data, f) 28 | print("New Config file => ", path) 29 | 30 | 31 | if __name__ == '__main__': 32 | parser = argparse.ArgumentParser() 33 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') 34 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') 35 | parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project') 36 | parser.add_argument('--overwrite_config', action='store_true', help='overwrite data.yaml') 37 | opt = parser.parse_args() 38 | 39 | create_dataset_artifact(opt) 40 | -------------------------------------------------------------------------------- /utils/wandb_logging/wandb_utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | import shutil 3 | import sys 4 | from datetime import datetime 5 | from pathlib import Path 6 | 7 | import torch 8 | 9 | sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path 10 | from utils.general import colorstr, xywh2xyxy 11 | 12 | try: 13 | import wandb 14 | except ImportError: 15 | wandb = None 16 | print(f"{colorstr('wandb: ')}Install Weights & Biases for YOLOv5 logging with 'pip install wandb' (recommended)") 17 | 18 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' 19 | 20 | 21 | def remove_prefix(from_string, prefix): 22 | return from_string[len(prefix):] 23 | 24 | 25 | class WandbLogger(): 26 | def __init__(self, opt, name, run_id, data_dict, job_type='Training'): 27 | self.wandb = wandb 28 | self.wandb_run = wandb.init(config=opt, resume="allow", 29 | project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem, 30 | name=name, 31 | job_type=job_type, 32 | id=run_id) if self.wandb else None 33 | 34 | if job_type == 'Training': 35 | self.setup_training(opt, data_dict) 36 | if opt.bbox_interval == -1: 37 | opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else opt.epochs 38 | if opt.save_period == -1: 39 | opt.save_period = (opt.epochs // 10) if opt.epochs > 10 else opt.epochs 40 | 41 | def setup_training(self, opt, data_dict): 42 | self.log_dict = {} 43 | self.train_artifact_path, self.trainset_artifact = \ 44 | self.download_dataset_artifact(data_dict['train'], opt.artifact_alias) 45 | self.test_artifact_path, self.testset_artifact = \ 46 | self.download_dataset_artifact(data_dict['val'], opt.artifact_alias) 47 | self.result_artifact, self.result_table, self.weights = None, None, None 48 | if self.train_artifact_path is not None: 49 | train_path = Path(self.train_artifact_path) / 'data/images/' 50 | data_dict['train'] = str(train_path) 51 | if self.test_artifact_path is not None: 52 | test_path = Path(self.test_artifact_path) / 'data/images/' 53 | data_dict['val'] = str(test_path) 54 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") 55 | self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"]) 56 | if opt.resume_from_artifact: 57 | modeldir, _ = self.download_model_artifact(opt.resume_from_artifact) 58 | if modeldir: 59 | self.weights = Path(modeldir) / "best.pt" 60 | opt.weights = self.weights 61 | 62 | def download_dataset_artifact(self, path, alias): 63 | if path.startswith(WANDB_ARTIFACT_PREFIX): 64 | dataset_artifact = wandb.use_artifact(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias) 65 | assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'" 66 | datadir = dataset_artifact.download() 67 | labels_zip = Path(datadir) / "data/labels.zip" 68 | shutil.unpack_archive(labels_zip, Path(datadir) / 'data/labels', 'zip') 69 | print("Downloaded dataset to : ", datadir) 70 | return datadir, dataset_artifact 71 | return None, None 72 | 73 | def download_model_artifact(self, name): 74 | model_artifact = wandb.use_artifact(name + ":latest") 75 | assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist' 76 | modeldir = model_artifact.download() 77 | print("Downloaded model to : ", modeldir) 78 | return modeldir, model_artifact 79 | 80 | def log_model(self, path, opt, epoch): 81 | datetime_suffix = datetime.today().strftime('%Y-%m-%d-%H-%M-%S') 82 | model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={ 83 | 'original_url': str(path), 84 | 'epoch': epoch + 1, 85 | 'save period': opt.save_period, 86 | 'project': opt.project, 87 | 'datetime': datetime_suffix 88 | }) 89 | model_artifact.add_file(str(path / 'last.pt'), name='last.pt') 90 | model_artifact.add_file(str(path / 'best.pt'), name='best.pt') 91 | wandb.log_artifact(model_artifact) 92 | print("Saving model artifact on epoch ", epoch + 1) 93 | 94 | def log_dataset_artifact(self, dataset, class_to_id, name='dataset'): 95 | artifact = wandb.Artifact(name=name, type="dataset") 96 | image_path = dataset.path 97 | artifact.add_dir(image_path, name='data/images') 98 | table = wandb.Table(columns=["id", "train_image", "Classes"]) 99 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()]) 100 | for si, (img, labels, paths, shapes) in enumerate(dataset): 101 | height, width = shapes[0] 102 | labels[:, 2:] = (xywh2xyxy(labels[:, 2:].view(-1, 4))) 103 | labels[:, 2:] *= torch.Tensor([width, height, width, height]) 104 | box_data = [] 105 | img_classes = {} 106 | for cls, *xyxy in labels[:, 1:].tolist(): 107 | cls = int(cls) 108 | box_data.append({"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]}, 109 | "class_id": cls, 110 | "box_caption": "%s" % (class_to_id[cls]), 111 | "scores": {"acc": 1}, 112 | "domain": "pixel"}) 113 | img_classes[cls] = class_to_id[cls] 114 | boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space 115 | table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes)) 116 | artifact.add(table, name) 117 | labels_path = 'labels'.join(image_path.rsplit('images', 1)) 118 | zip_path = Path(labels_path).parent / (name + '_labels.zip') 119 | if not zip_path.is_file(): # make_archive won't check if file exists 120 | shutil.make_archive(zip_path.with_suffix(''), 'zip', labels_path) 121 | artifact.add_file(str(zip_path), name='data/labels.zip') 122 | wandb.log_artifact(artifact) 123 | print("Saving data to W&B...") 124 | 125 | def log(self, log_dict): 126 | if self.wandb_run: 127 | for key, value in log_dict.items(): 128 | self.log_dict[key] = value 129 | 130 | def end_epoch(self): 131 | if self.wandb_run and self.log_dict: 132 | wandb.log(self.log_dict) 133 | self.log_dict = {} 134 | 135 | def finish_run(self): 136 | if self.wandb_run: 137 | if self.result_artifact: 138 | print("Add Training Progress Artifact") 139 | self.result_artifact.add(self.result_table, 'result') 140 | train_results = wandb.JoinedTable(self.testset_artifact.get("val"), self.result_table, "id") 141 | self.result_artifact.add(train_results, 'joined_result') 142 | wandb.log_artifact(self.result_artifact) 143 | if self.log_dict: 144 | wandb.log(self.log_dict) 145 | wandb.run.finish() 146 | -------------------------------------------------------------------------------- /weights/download_weights.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Download latest models from https://github.com/ultralytics/yolov5/releases 3 | # Usage: 4 | # $ bash weights/download_weights.sh 5 | 6 | python - <