├── models ├── __init__.py ├── __pycache__ │ ├── common.cpython-36.pyc │ ├── yolo.cpython-36.pyc │ ├── __init__.cpython-36.pyc │ └── experimental.cpython-36.pyc ├── hub │ ├── yolov3-tiny.yaml │ ├── yolov5-fpn.yaml │ ├── yolov5-bifpn.yaml │ ├── yolov5s-transformer.yaml │ ├── yolov5-panet.yaml │ ├── yolov3.yaml │ ├── yolov3-spp.yaml │ ├── yolov5-p2.yaml │ ├── yolov5-p6.yaml │ ├── yolov5l6.yaml │ ├── yolov5m6.yaml │ ├── yolov5s6.yaml │ ├── yolov5x6.yaml │ ├── yolov5-p7.yaml │ └── anchors.yaml ├── yolov5l.yaml ├── yolov5m.yaml ├── yolov5x.yaml ├── yolov5s.yaml └── experimental.py ├── run └── LICENCE ├── utils ├── __init__.py ├── aws │ ├── __init__.py │ ├── mime.sh │ ├── resume.py │ └── userdata.sh ├── __pycache__ │ ├── loss.cpython-36.pyc │ ├── general.cpython-36.pyc │ ├── metrics.cpython-36.pyc │ ├── plots.cpython-36.pyc │ ├── __init__.cpython-36.pyc │ ├── callbacks.cpython-36.pyc │ ├── datasets.cpython-36.pyc │ ├── downloads.cpython-36.pyc │ ├── autoanchor.cpython-36.pyc │ ├── torch_utils.cpython-36.pyc │ └── augmentations.cpython-36.pyc ├── google_app_engine │ ├── additional_requirements.txt │ ├── app.yaml │ └── Dockerfile ├── loggers │ ├── wandb │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ └── wandb_utils.cpython-36.pyc │ │ ├── log_dataset.py │ │ ├── sweep.py │ │ ├── sweep.yaml │ │ └── README.md │ └── __init__.py ├── flask_rest_api │ ├── example_request.py │ ├── restapi.py │ └── README.md ├── activations.py ├── callbacks.py ├── downloads.py ├── autoanchor.py └── loss.py ├── .gitattributes ├── __pycache__ └── val.cpython-36.pyc ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── question.md │ ├── feature-request.md │ └── bug-report.md ├── dependabot.yml └── workflows │ ├── rebase.yml │ ├── stale.yml │ ├── codeql-analysis.yml │ ├── ci-testing.yml │ └── greetings.yml ├── labeldir.py ├── data ├── scripts │ ├── download_weights.sh │ ├── get_coco128.sh │ └── get_coco.sh ├── hyps │ ├── hyp.finetune_objects365.yaml │ ├── hyp.finetune.yaml │ ├── hyp.scratch.yaml │ └── hyp.scratch-p6.yaml ├── DOTA_ROTATED.yaml ├── coco128.yaml ├── GlobalWheat2020.yaml ├── coco.yaml ├── SKU-110K.yaml ├── Argoverse.yaml ├── VisDrone.yaml ├── VOC.yaml ├── xView.yaml └── Objects365.yaml ├── requirements.txt ├── README.md ├── .dockerignore ├── .gitignore ├── hubconf.py ├── export.py └── detect.py /models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /run/LICENCE: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /utils/aws/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # this drop notebooks from GitHub language stats 2 | *.ipynb linguist-vendored 3 | -------------------------------------------------------------------------------- /__pycache__/val.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/__pycache__/val.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/loss.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/loss.cpython-36.pyc -------------------------------------------------------------------------------- /models/__pycache__/common.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/models/__pycache__/common.cpython-36.pyc -------------------------------------------------------------------------------- /models/__pycache__/yolo.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/models/__pycache__/yolo.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/general.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/general.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/metrics.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/metrics.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/plots.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/plots.cpython-36.pyc -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: glenn-jocher 4 | patreon: ultralytics 5 | open_collective: ultralytics 6 | -------------------------------------------------------------------------------- /models/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/models/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/callbacks.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/callbacks.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/datasets.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/datasets.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/downloads.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/downloads.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/autoanchor.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/autoanchor.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/torch_utils.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/torch_utils.cpython-36.pyc -------------------------------------------------------------------------------- /models/__pycache__/experimental.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/models/__pycache__/experimental.cpython-36.pyc -------------------------------------------------------------------------------- /utils/__pycache__/augmentations.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/__pycache__/augmentations.cpython-36.pyc -------------------------------------------------------------------------------- /utils/google_app_engine/additional_requirements.txt: -------------------------------------------------------------------------------- 1 | # add these requirements in your app on top of the existing ones 2 | pip==19.2 3 | Flask==1.0.2 4 | gunicorn==19.9.0 5 | -------------------------------------------------------------------------------- /utils/loggers/wandb/__pycache__/__init__.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/loggers/wandb/__pycache__/__init__.cpython-36.pyc -------------------------------------------------------------------------------- /utils/loggers/wandb/__pycache__/wandb_utils.cpython-36.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/root12321/Rotation-Detect-yolov5_poly/HEAD/utils/loggers/wandb/__pycache__/wandb_utils.cpython-36.pyc -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "❓Question" 3 | about: Ask a general question 4 | title: '' 5 | labels: question 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## ❔Question 11 | 12 | ## Additional context 13 | -------------------------------------------------------------------------------- /labeldir.py: -------------------------------------------------------------------------------- 1 | import os 2 | img_dir=os.listdir('./img_640') 3 | traintxt=open("train.txt",'w') 4 | for img_name in img_dir: 5 | path=os.path.join(os.getcwd(),'img_640',img_name)+'\n' 6 | traintxt.write(path) 7 | #print(path) 8 | traintxt.close() -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | time: "04:00" 8 | open-pull-requests-limit: 10 9 | reviewers: 10 | - glenn-jocher 11 | labels: 12 | - dependencies 13 | -------------------------------------------------------------------------------- /utils/flask_rest_api/example_request.py: -------------------------------------------------------------------------------- 1 | """Perform test request""" 2 | import pprint 3 | 4 | import requests 5 | 6 | DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s" 7 | TEST_IMAGE = "zidane.jpg" 8 | 9 | image_data = open(TEST_IMAGE, "rb").read() 10 | 11 | response = requests.post(DETECTION_URL, files={"image": image_data}).json() 12 | 13 | pprint.pprint(response) 14 | -------------------------------------------------------------------------------- /data/scripts/download_weights.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 3 | # Download latest models from https://github.com/ultralytics/yolov5/releases 4 | # Example usage: bash path/to/download_weights.sh 5 | # parent 6 | # └── yolov5 7 | # ├── yolov5s.pt ← downloads here 8 | # ├── yolov5m.pt 9 | # └── ... 10 | 11 | python - <=3.2.2 5 | numpy>=1.18.5 6 | opencv-python==4.1.2.30 7 | Pillow 8 | PyYAML>=5.3.1 9 | scipy>=1.4.1 10 | # torch>=1.7.0 11 | # torchvision>=0.8.1 12 | tqdm>=4.41.0 13 | 14 | # logging ------------------------------------- 15 | tensorboard>=2.4.1 16 | # wandb 17 | 18 | # plotting ------------------------------------ 19 | seaborn>=0.11.0 20 | pandas 21 | 22 | # export -------------------------------------- 23 | # coremltools>=4.1 24 | # onnx>=1.9.0 25 | # scikit-learn==0.19.2 # for coreml quantization 26 | 27 | # extras -------------------------------------- 28 | # Cython # for pycocotools https://github.com/cocodataset/cocoapi/issues/172 29 | # pycocotools>=2.0 # COCO mAP 30 | # albumentations>=1.0.3 31 | thop # FLOPs computation 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "🚀 Feature request" 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | ## 🚀 Feature 11 | 12 | 13 | 14 | ## Motivation 15 | 16 | 18 | 19 | ## Pitch 20 | 21 | 22 | 23 | ## Alternatives 24 | 25 | 26 | 27 | ## Additional context 28 | 29 | 30 | -------------------------------------------------------------------------------- /utils/aws/mime.sh: -------------------------------------------------------------------------------- 1 | # AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/ 2 | # This script will run on every instance restart, not only on first start 3 | # --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA --- 4 | 5 | Content-Type: multipart/mixed; boundary="//" 6 | MIME-Version: 1.0 7 | 8 | --// 9 | Content-Type: text/cloud-config; charset="us-ascii" 10 | MIME-Version: 1.0 11 | Content-Transfer-Encoding: 7bit 12 | Content-Disposition: attachment; filename="cloud-config.txt" 13 | 14 | #cloud-config 15 | cloud_final_modules: 16 | - [scripts-user, always] 17 | 18 | --// 19 | Content-Type: text/x-shellscript; charset="us-ascii" 20 | MIME-Version: 1.0 21 | Content-Transfer-Encoding: 7bit 22 | Content-Disposition: attachment; filename="userdata.txt" 23 | 24 | #!/bin/bash 25 | # --- paste contents of userdata.sh here --- 26 | --// 27 | -------------------------------------------------------------------------------- /utils/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/loggers/wandb/log_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | from wandb_utils import WandbLogger 4 | 5 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' 6 | 7 | 8 | def create_dataset_artifact(opt): 9 | logger = WandbLogger(opt, None, job_type='Dataset Creation') # TODO: return value unused 10 | 11 | 12 | if __name__ == '__main__': 13 | parser = argparse.ArgumentParser() 14 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') 15 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') 16 | parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project') 17 | parser.add_argument('--entity', default=None, help='W&B entity') 18 | parser.add_argument('--name', type=str, default='log dataset', help='name of W&B run') 19 | 20 | opt = parser.parse_args() 21 | opt.resume = False # Explicitly disallow resume check for dataset upload job 22 | 23 | create_dataset_artifact(opt) 24 | -------------------------------------------------------------------------------- /utils/loggers/wandb/sweep.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from pathlib import Path 3 | 4 | import wandb 5 | 6 | FILE = Path(__file__).absolute() 7 | sys.path.append(FILE.parents[3].as_posix()) # add utils/ to path 8 | 9 | from train import train, parse_opt 10 | from utils.general import increment_path 11 | from utils.torch_utils import select_device 12 | 13 | 14 | def sweep(): 15 | wandb.init() 16 | # Get hyp dict from sweep agent 17 | hyp_dict = vars(wandb.config).get("_items") 18 | 19 | # Workaround: get necessary opt args 20 | opt = parse_opt(known=True) 21 | opt.batch_size = hyp_dict.get("batch_size") 22 | opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve)) 23 | opt.epochs = hyp_dict.get("epochs") 24 | opt.nosave = True 25 | opt.data = hyp_dict.get("data") 26 | device = select_device(opt.device, batch_size=opt.batch_size) 27 | 28 | # train 29 | train(hyp_dict, opt, device) 30 | 31 | 32 | if __name__ == "__main__": 33 | sweep() 34 | -------------------------------------------------------------------------------- /data/scripts/get_coco.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 3 | # Download COCO 2017 dataset http://cocodataset.org 4 | # Example usage: bash data/scripts/get_coco.sh 5 | # parent 6 | # ├── yolov5 7 | # └── datasets 8 | # └── coco ← downloads here 9 | 10 | # Download/unzip labels 11 | d='../datasets' # unzip directory 12 | url=https://github.com/ultralytics/yolov5/releases/download/v1.0/ 13 | f='coco2017labels.zip' # or 'coco2017labels-segments.zip', 68 MB 14 | echo 'Downloading' $url$f ' ...' 15 | curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & 16 | 17 | # Download/unzip images 18 | d='../datasets/coco/images' # unzip directory 19 | url=http://images.cocodataset.org/zips/ 20 | f1='train2017.zip' # 19G, 118k images 21 | f2='val2017.zip' # 1G, 5k images 22 | f3='test2017.zip' # 7G, 41k images (optional) 23 | for f in $f1 $f2; do 24 | echo 'Downloading' $url$f '...' 25 | curl -L $url$f -o $f && unzip -q $f -d $d && rm $f & 26 | done 27 | wait # finish background tasks 28 | -------------------------------------------------------------------------------- /data/DOTA_ROTATED.yaml: -------------------------------------------------------------------------------- 1 | # train and val datasets (image directory or *.txt file with image paths) 2 | # train: ../DOTA_YOLO/train_1024_OBB/images/train2020/ 3 | # val: ../DOTA_YOLO/val_1024_OBB/images/train2020/ 4 | 5 | train: /data/dataset/dataset_download/datasets/test/val_poly.txt 6 | val: /data/dataset/dataset_download/datasets/test/val_poly.txt 7 | test: /data/dataset/dataset_download/datasets/test/val_poly.txt 8 | 9 | # number of classes 10 | #nc: 16 11 | nc: 6 12 | 13 | # class names 14 | # names: [ 'plane', 'baseball-diamond', 'bridge', 'ground-track-field', 'small-vehicle', 'large-vehicle', 'ship', 15 | # 'tennis-court', 'basketball-court', 'storage-tank', 'soccer-ball-field', 'roundabout', 'harbor', 16 | # 'swimming-pool', 'helicopter', 'container-crane' ] 17 | # names: ['jueyuanzi',''] 18 | # names: ['seg_jueyuanzi_01','seg_fangzhenchui_sh','seg_daodixian_01','fushusheshi_01','fushusheshi_03','ganta_02','gkxfw','TaDiao','YanHuo','zhongjianjian'] 19 | names: ['falanpan_normal','seg_blz_jsxs','seg_blz_normal','seg_taizhou_caigangwa', 'seg_taizhou_dapeng','seg_taizhou_jsxs'] -------------------------------------------------------------------------------- /data/hyps/hyp.finetune.yaml: -------------------------------------------------------------------------------- 1 | # Hyperparameters for VOC finetuning 2 | # python train.py --batch 64 --weights yolov5m.pt --data VOC.yaml --img 512 --epochs 50 3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials 4 | 5 | 6 | # Hyperparameter Evolution Results 7 | # Generations: 306 8 | # P R mAP.5 mAP.5:.95 box obj cls 9 | # Metrics: 0.6 0.936 0.896 0.684 0.0115 0.00805 0.00146 10 | 11 | lr0: 0.0032 12 | lrf: 0.12 13 | momentum: 0.843 14 | weight_decay: 0.00036 15 | warmup_epochs: 2.0 16 | warmup_momentum: 0.5 17 | warmup_bias_lr: 0.05 18 | box: 0.0296 19 | cls: 0.243 20 | cls_pw: 0.631 21 | obj: 0.301 22 | obj_pw: 0.911 23 | angle: 0.266 24 | angle_pw: 0.333 # angle BCELoss positive_weight 25 | iou_t: 0.2 26 | anchor_t: 2.91 27 | # anchors: 3.63 28 | fl_gamma: 0.0 29 | hsv_h: 0.0138 30 | hsv_s: 0.664 31 | hsv_v: 0.464 32 | degrees: 0.373 33 | translate: 0.245 34 | scale: 0.898 35 | shear: 0.602 36 | perspective: 0.0 37 | flipud: 0.00856 38 | fliplr: 0.5 39 | mosaic: 1.0 40 | mixup: 0.243 41 | copy_paste: 0.0 42 | -------------------------------------------------------------------------------- /utils/aws/resume.py: -------------------------------------------------------------------------------- 1 | # Resume all interrupted trainings in yolov5/ dir including DDP trainings 2 | # Usage: $ python utils/aws/resume.py 3 | 4 | import os 5 | import sys 6 | from pathlib import Path 7 | 8 | import torch 9 | import yaml 10 | 11 | sys.path.append('./') # to run '$ python *.py' files in subdirectories 12 | 13 | port = 0 # --master_port 14 | path = Path('').resolve() 15 | for last in path.rglob('*/**/last.pt'): 16 | ckpt = torch.load(last) 17 | if ckpt['optimizer'] is None: 18 | continue 19 | 20 | # Load opt.yaml 21 | with open(last.parent.parent / 'opt.yaml') as f: 22 | opt = yaml.safe_load(f) 23 | 24 | # Get device count 25 | d = opt['device'].split(',') # devices 26 | nd = len(d) # number of devices 27 | ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel 28 | 29 | if ddp: # multi-GPU 30 | port += 1 31 | cmd = f'python -m torch.distributed.run --nproc_per_node {nd} --master_port {port} train.py --resume {last}' 32 | else: # single-GPU 33 | cmd = f'python train.py --resume {last}' 34 | 35 | cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread 36 | print(cmd) 37 | os.system(cmd) 38 | -------------------------------------------------------------------------------- /utils/flask_rest_api/restapi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Run a rest API exposing the yolov5s object detection model 3 | """ 4 | import argparse 5 | import io 6 | 7 | import torch 8 | from PIL import Image 9 | from flask import Flask, request 10 | 11 | app = Flask(__name__) 12 | 13 | DETECTION_URL = "/v1/object-detection/yolov5s" 14 | 15 | 16 | @app.route(DETECTION_URL, methods=["POST"]) 17 | def predict(): 18 | if not request.method == "POST": 19 | return 20 | 21 | if request.files.get("image"): 22 | image_file = request.files["image"] 23 | image_bytes = image_file.read() 24 | 25 | img = Image.open(io.BytesIO(image_bytes)) 26 | 27 | results = model(img, size=640) # reduce size=320 for faster inference 28 | return results.pandas().xyxy[0].to_json(orient="records") 29 | 30 | 31 | if __name__ == "__main__": 32 | parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model") 33 | parser.add_argument("--port", default=5000, type=int, help="port number") 34 | args = parser.parse_args() 35 | 36 | model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache 37 | app.run(host="0.0.0.0", port=args.port) # debug=True causes Restarting with stat 38 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [10,14, 23,27, 37,58] # P4/16 7 | - [81,82, 135,169, 344,319] # P5/32 8 | 9 | # YOLOv3-tiny backbone 10 | backbone: 11 | # [from, number, module, args] 12 | [[-1, 1, Conv, [16, 3, 1]], # 0 13 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2 14 | [-1, 1, Conv, [32, 3, 1]], 15 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4 16 | [-1, 1, Conv, [64, 3, 1]], 17 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8 18 | [-1, 1, Conv, [128, 3, 1]], 19 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16 20 | [-1, 1, Conv, [256, 3, 1]], 21 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32 22 | [-1, 1, Conv, [512, 3, 1]], 23 | [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11 24 | [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12 25 | ] 26 | 27 | # YOLOv3-tiny head 28 | head: 29 | [[-1, 1, Conv, [1024, 3, 1]], 30 | [-1, 1, Conv, [256, 1, 1]], 31 | [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large) 32 | 33 | [-2, 1, Conv, [128, 1, 1]], 34 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 35 | [[-1, 8], 1, Concat, [1]], # cat backbone P4 36 | [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium) 37 | 38 | [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5) 39 | ] 40 | -------------------------------------------------------------------------------- /utils/aws/userdata.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html 3 | # This script will run only once on first instance start (for a re-start script see mime.sh) 4 | # /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir 5 | # Use >300 GB SSD 6 | 7 | cd home/ubuntu 8 | if [ ! -d yolov5 ]; then 9 | echo "Running first-time script." # install dependencies, download COCO, pull Docker 10 | git clone https://github.com/ultralytics/yolov5 -b master && sudo chmod -R 777 yolov5 11 | cd yolov5 12 | bash data/scripts/get_coco.sh && echo "COCO done." & 13 | sudo docker pull ultralytics/yolov5:latest && echo "Docker done." & 14 | python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." & 15 | wait && echo "All tasks done." # finish background tasks 16 | else 17 | echo "Running re-start script." # resume interrupted runs 18 | i=0 19 | list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour' 20 | while IFS= read -r id; do 21 | ((i++)) 22 | echo "restarting container $i: $id" 23 | sudo docker start $id 24 | # sudo docker exec -it $id python train.py --resume # single-GPU 25 | sudo docker exec -d $id python utils/aws/resume.py # multi-scenario 26 | done <<<"$list" 27 | fi 28 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, Bottleneck, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, BottleneckCSP, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, BottleneckCSP, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 6, BottleneckCSP, [1024]], # 9 23 | ] 24 | 25 | # YOLOv5 FPN head 26 | head: 27 | [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large) 28 | 29 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 30 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 31 | [-1, 1, Conv, [512, 1, 1]], 32 | [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium) 33 | 34 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 35 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 36 | [-1, 1, Conv, [256, 1, 1]], 37 | [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small) 38 | 39 | [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 40 | ] 41 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3, [1024, False]], # 9 23 | ] 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14], 1, Concat, [1]], # cat head P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3, [1024, False]], # 9 23 | ] 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14], 1, Concat, [1]], # cat head P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /models/yolov5x.yaml: -------------------------------------------------------------------------------- 1 | # Parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.33 # model depth multiple 4 | width_multiple: 1.25 # layer channel multiple 5 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3, [1024, False]], # 9 23 | ] 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14], 1, Concat, [1]], # cat head P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /models/hub/yolov5-bifpn.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 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]] 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3, [1024, False]], # 9 23 | ] 24 | 25 | # YOLOv5 BiFPN head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14, 6], 1, Concat, [1]], # cat P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /models/hub/yolov5s-transformer.yaml: -------------------------------------------------------------------------------- 1 | # Parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 0.33 # model depth multiple 4 | width_multiple: 0.50 # layer channel multiple 5 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3TR, [1024, False]], # 9 <-------- C3TR() Transformer module 23 | ] 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14], 1, Concat, [1]], # cat head P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, BottleneckCSP, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, BottleneckCSP, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, BottleneckCSP, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, BottleneckCSP, [1024, False]], # 9 23 | ] 24 | 25 | # YOLOv5 PANet head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, BottleneckCSP, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14], 1, Concat, [1]], # cat head P4 39 | [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # darknet53 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Conv, [32, 3, 1]], # 0 14 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 15 | [-1, 1, Bottleneck, [64]], 16 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 17 | [-1, 2, Bottleneck, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 19 | [-1, 8, Bottleneck, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 21 | [-1, 8, Bottleneck, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 23 | [-1, 4, Bottleneck, [1024]], # 10 24 | ] 25 | 26 | # YOLOv3 head 27 | head: 28 | [[-1, 1, Bottleneck, [1024, False]], 29 | [-1, 1, Conv, [512, [1, 1]]], 30 | [-1, 1, Conv, [1024, 3, 1]], 31 | [-1, 1, Conv, [512, 1, 1]], 32 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) 33 | 34 | [-2, 1, Conv, [256, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 8], 1, Concat, [1]], # cat backbone P4 37 | [-1, 1, Bottleneck, [512, False]], 38 | [-1, 1, Bottleneck, [512, False]], 39 | [-1, 1, Conv, [256, 1, 1]], 40 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) 41 | 42 | [-2, 1, Conv, [128, 1, 1]], 43 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 44 | [[-1, 6], 1, Concat, [1]], # cat backbone P3 45 | [-1, 1, Bottleneck, [256, False]], 46 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) 47 | 48 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 49 | ] 50 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # darknet53 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Conv, [32, 3, 1]], # 0 14 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 15 | [-1, 1, Bottleneck, [64]], 16 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 17 | [-1, 2, Bottleneck, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 19 | [-1, 8, Bottleneck, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 21 | [-1, 8, Bottleneck, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 23 | [-1, 4, Bottleneck, [1024]], # 10 24 | ] 25 | 26 | # YOLOv3-SPP head 27 | head: 28 | [[-1, 1, Bottleneck, [1024, False]], 29 | [-1, 1, SPP, [512, [5, 9, 13]]], 30 | [-1, 1, Conv, [1024, 3, 1]], 31 | [-1, 1, Conv, [512, 1, 1]], 32 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) 33 | 34 | [-2, 1, Conv, [256, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 8], 1, Concat, [1]], # cat backbone P4 37 | [-1, 1, Bottleneck, [512, False]], 38 | [-1, 1, Bottleneck, [512, False]], 39 | [-1, 1, Conv, [256, 1, 1]], 40 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) 41 | 42 | [-2, 1, Conv, [128, 1, 1]], 43 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 44 | [[-1, 6], 1, Concat, [1]], # cat backbone P3 45 | [-1, 1, Bottleneck, [256, False]], 46 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) 47 | 48 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 49 | ] 50 | -------------------------------------------------------------------------------- /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 | anchors: 3 6 | 7 | # YOLOv5 backbone 8 | backbone: 9 | # [from, number, module, args] 10 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 11 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 12 | [-1, 3, C3, [128]], 13 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 14 | [-1, 9, C3, [256]], 15 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 16 | [-1, 9, C3, [512]], 17 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 18 | [-1, 1, SPP, [1024, [5, 9, 13]]], 19 | [-1, 3, C3, [1024, False]], # 9 20 | ] 21 | 22 | # YOLOv5 head 23 | head: 24 | [[-1, 1, Conv, [512, 1, 1]], 25 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 26 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 27 | [-1, 3, C3, [512, False]], # 13 28 | 29 | [-1, 1, Conv, [256, 1, 1]], 30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 31 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 32 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 33 | 34 | [-1, 1, Conv, [128, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 2], 1, Concat, [1]], # cat backbone P2 37 | [-1, 1, C3, [128, False]], # 21 (P2/4-xsmall) 38 | 39 | [-1, 1, Conv, [128, 3, 2]], 40 | [[-1, 18], 1, Concat, [1]], # cat head P3 41 | [-1, 3, C3, [256, False]], # 24 (P3/8-small) 42 | 43 | [-1, 1, Conv, [256, 3, 2]], 44 | [[-1, 14], 1, Concat, [1]], # cat head P4 45 | [-1, 3, C3, [512, False]], # 27 (P4/16-medium) 46 | 47 | [-1, 1, Conv, [512, 3, 2]], 48 | [[-1, 10], 1, Concat, [1]], # cat head P5 49 | [-1, 3, C3, [1024, False]], # 30 (P5/32-large) 50 | 51 | [[24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 52 | ] 53 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: "🐛 Bug report" 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | Before submitting a bug report, please be aware that your issue **must be reproducible** with all of the following, 11 | otherwise it is non-actionable, and we can not help you: 12 | 13 | - **Current repo**: run `git fetch && git status -uno` to check and `git pull` to update repo 14 | - **Common dataset**: coco.yaml or coco128.yaml 15 | - **Common environment**: Colab, Google Cloud, or Docker image. See https://github.com/ultralytics/yolov5#environments 16 | 17 | If this is a custom dataset/training question you **must include** your `train*.jpg`, `val*.jpg` and `results.png` 18 | figures, or we can not help you. You can generate these with `utils.plot_results()`. 19 | 20 | ## 🐛 Bug 21 | 22 | A clear and concise description of what the bug is. 23 | 24 | ## To Reproduce (REQUIRED) 25 | 26 | Input: 27 | 28 | ``` 29 | import torch 30 | 31 | a = torch.tensor([5]) 32 | c = a / 0 33 | ``` 34 | 35 | Output: 36 | 37 | ``` 38 | Traceback (most recent call last): 39 | File "/Users/glennjocher/opt/anaconda3/envs/env1/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3331, in run_code 40 | exec(code_obj, self.user_global_ns, self.user_ns) 41 | File "", line 5, in 42 | c = a / 0 43 | RuntimeError: ZeroDivisionError 44 | ``` 45 | 46 | ## Expected behavior 47 | 48 | A clear and concise description of what you expected to happen. 49 | 50 | ## Environment 51 | 52 | If applicable, add screenshots to help explain your problem. 53 | 54 | - OS: [e.g. Ubuntu] 55 | - GPU [e.g. 2080 Ti] 56 | 57 | ## Additional context 58 | 59 | Add any other context about the problem here. 60 | -------------------------------------------------------------------------------- /data/hyps/hyp.scratch.yaml: -------------------------------------------------------------------------------- 1 | # Hyperparameters for COCO training from scratch 2 | # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300 3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials 4 | 5 | 6 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3) 7 | lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf) 8 | momentum: 0.937 # SGD momentum/Adam beta1 9 | weight_decay: 0.0005 # optimizer weight decay 5e-4 10 | warmup_epochs: 3.0 # warmup epochs (fractions ok) 11 | warmup_momentum: 0.8 # warmup initial momentum 12 | warmup_bias_lr: 0.1 # warmup initial bias lr 13 | box: 0.05 # box loss gain 14 | cls: 0.5 # cls loss gain 15 | cls_pw: 1.0 # cls BCELoss positive_weight 16 | obj: 1.0 # obj loss gain (scale with pixels) 17 | obj_pw: 1.0 # obj BCELoss positive_weight 18 | angle: 0.266 19 | angle_pw: 0.333 # angle BCELoss positive_weight 20 | iou_t: 0.20 # IoU training threshold 21 | anchor_t: 4.0 # anchor-multiple threshold 22 | # anchors: 3 # anchors per output layer (0 to ignore) 23 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) 24 | hsv_h: 0.015 # image HSV-Hue augmentation (fraction) 25 | hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) 26 | hsv_v: 0.4 # image HSV-Value augmentation (fraction) 27 | degrees: 0.0 # image rotation (+/- deg) 28 | translate: 0.1 # image translation (+/- fraction) 29 | scale: 0.5 # image scale (+/- gain) 30 | shear: 0.0 # image shear (+/- deg) 31 | perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 32 | flipud: 0.0 # image flip up-down (probability) 33 | fliplr: 0.5 # image flip left-right (probability) 34 | mosaic: 1.0 # image mosaic (probability) 35 | mixup: 0.0 # image mixup (probability) 36 | copy_paste: 0.0 # segment copy-paste (probability) 37 | -------------------------------------------------------------------------------- /data/hyps/hyp.scratch-p6.yaml: -------------------------------------------------------------------------------- 1 | # Hyperparameters for COCO training from scratch 2 | # python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300 3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials 4 | 5 | 6 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3) 7 | lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf) 8 | momentum: 0.937 # SGD momentum/Adam beta1 9 | weight_decay: 0.0005 # optimizer weight decay 5e-4 10 | warmup_epochs: 3.0 # warmup epochs (fractions ok) 11 | warmup_momentum: 0.8 # warmup initial momentum 12 | warmup_bias_lr: 0.1 # warmup initial bias lr 13 | box: 0.05 # box loss gain 14 | cls: 0.3 # cls loss gain 15 | cls_pw: 1.0 # cls BCELoss positive_weight 16 | obj: 0.7 # obj loss gain (scale with pixels) 17 | obj_pw: 1.0 # obj BCELoss positive_weight 18 | angle: 0.266 19 | angle_pw: 0.333 # angle BCELoss positive_weight 20 | iou_t: 0.20 # IoU training threshold 21 | anchor_t: 4.0 # anchor-multiple threshold 22 | # anchors: 3 # anchors per output layer (0 to ignore) 23 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) 24 | hsv_h: 0.015 # image HSV-Hue augmentation (fraction) 25 | hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) 26 | hsv_v: 0.4 # image HSV-Value augmentation (fraction) 27 | degrees: 0.0 # image rotation (+/- deg) 28 | translate: 0.1 # image translation (+/- fraction) 29 | scale: 0.9 # image scale (+/- gain) 30 | shear: 0.0 # image shear (+/- deg) 31 | perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 32 | flipud: 0.0 # image flip up-down (probability) 33 | fliplr: 0.5 # image flip left-right (probability) 34 | mosaic: 1.0 # image mosaic (probability) 35 | mixup: 0.0 # image mixup (probability) 36 | copy_paste: 0.0 # segment copy-paste (probability) 37 | -------------------------------------------------------------------------------- /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 | anchors: 3 6 | 7 | # YOLOv5 backbone 8 | backbone: 9 | # [from, number, module, args] 10 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 11 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 12 | [-1, 3, C3, [128]], 13 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 14 | [-1, 9, C3, [256]], 15 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 16 | [-1, 9, C3, [512]], 17 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 18 | [-1, 3, C3, [768]], 19 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 20 | [-1, 1, SPP, [1024, [3, 5, 7]]], 21 | [-1, 3, C3, [1024, False]], # 11 22 | ] 23 | 24 | # YOLOv5 head 25 | head: 26 | [[-1, 1, Conv, [768, 1, 1]], 27 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 28 | [[-1, 8], 1, Concat, [1]], # cat backbone P5 29 | [-1, 3, C3, [768, False]], # 15 30 | 31 | [-1, 1, Conv, [512, 1, 1]], 32 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 33 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 34 | [-1, 3, C3, [512, False]], # 19 35 | 36 | [-1, 1, Conv, [256, 1, 1]], 37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 38 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 39 | [-1, 3, C3, [256, False]], # 23 (P3/8-small) 40 | 41 | [-1, 1, Conv, [256, 3, 2]], 42 | [[-1, 20], 1, Concat, [1]], # cat head P4 43 | [-1, 3, C3, [512, False]], # 26 (P4/16-medium) 44 | 45 | [-1, 1, Conv, [512, 3, 2]], 46 | [[-1, 16], 1, Concat, [1]], # cat head P5 47 | [-1, 3, C3, [768, False]], # 29 (P5/32-large) 48 | 49 | [-1, 1, Conv, [768, 3, 2]], 50 | [[-1, 12], 1, Concat, [1]], # cat head P6 51 | [-1, 3, C3, [1024, False]], # 32 (P5/64-xlarge) 52 | 53 | [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) 54 | ] 55 | -------------------------------------------------------------------------------- /data/coco128.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) 3 | # Example usage: python train.py --data coco128.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── coco128 ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/coco128 # dataset root dir 12 | train: images/train2017 # train images (relative to 'path') 128 images 13 | val: images/train2017 # val images (relative to 'path') 128 images 14 | test: # test images (optional) 15 | 16 | # Classes 17 | nc: 80 # number of classes 18 | names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 19 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 20 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 21 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 22 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 23 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 24 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 25 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 26 | 'hair drier', 'toothbrush'] # class names 27 | 28 | 29 | # Download script/URL (optional) 30 | download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Close stale issues 2 | on: 3 | schedule: 4 | - cron: "0 0 * * *" 5 | 6 | jobs: 7 | stale: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/stale@v3 11 | with: 12 | repo-token: ${{ secrets.GITHUB_TOKEN }} 13 | stale-issue-message: | 14 | 👋 Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs. 15 | 16 | Access additional [YOLOv5](https://ultralytics.com/yolov5) 🚀 resources: 17 | - **Wiki** – https://github.com/ultralytics/yolov5/wiki 18 | - **Tutorials** – https://github.com/ultralytics/yolov5#tutorials 19 | - **Docs** – https://docs.ultralytics.com 20 | 21 | Access additional [Ultralytics](https://ultralytics.com) ⚡ resources: 22 | - **Ultralytics HUB** – https://ultralytics.com 23 | - **Vision API** – https://ultralytics.com/yolov5 24 | - **About Us** – https://ultralytics.com/about 25 | - **Join Our Team** – https://ultralytics.com/work 26 | - **Contact Us** – https://ultralytics.com/contact 27 | 28 | Feel free to inform us of any other **issues** you discover or **feature requests** that come to mind in the future. Pull Requests (PRs) are also always welcomed! 29 | 30 | Thank you for your contributions to YOLOv5 🚀 and Vision AI ⭐! 31 | 32 | stale-pr-message: 'This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions YOLOv5 🚀 and Vision AI ⭐.' 33 | days-before-stale: 30 34 | days-before-close: 5 35 | exempt-issue-labels: 'documentation,tutorial' 36 | operations-per-run: 100 # The maximum number of operations per run, used to control rate limiting. 37 | -------------------------------------------------------------------------------- /utils/flask_rest_api/README.md: -------------------------------------------------------------------------------- 1 | # Flask REST API 2 | [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API created using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/). 3 | 4 | ## Requirements 5 | 6 | [Flask](https://palletsprojects.com/p/flask/) is required. Install with: 7 | ```shell 8 | $ pip install Flask 9 | ``` 10 | 11 | ## Run 12 | 13 | After Flask installation run: 14 | 15 | ```shell 16 | $ python3 restapi.py --port 5000 17 | ``` 18 | 19 | Then use [curl](https://curl.se/) to perform a request: 20 | 21 | ```shell 22 | $ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s' 23 | ``` 24 | 25 | The model inference results are returned as a JSON response: 26 | 27 | ```json 28 | [ 29 | { 30 | "class": 0, 31 | "confidence": 0.8900438547, 32 | "height": 0.9318675399, 33 | "name": "person", 34 | "width": 0.3264600933, 35 | "xcenter": 0.7438579798, 36 | "ycenter": 0.5207948685 37 | }, 38 | { 39 | "class": 0, 40 | "confidence": 0.8440024257, 41 | "height": 0.7155083418, 42 | "name": "person", 43 | "width": 0.6546785235, 44 | "xcenter": 0.427829951, 45 | "ycenter": 0.6334488392 46 | }, 47 | { 48 | "class": 27, 49 | "confidence": 0.3771208823, 50 | "height": 0.3902671337, 51 | "name": "tie", 52 | "width": 0.0696444362, 53 | "xcenter": 0.3675483763, 54 | "ycenter": 0.7991207838 55 | }, 56 | { 57 | "class": 27, 58 | "confidence": 0.3527112305, 59 | "height": 0.1540903747, 60 | "name": "tie", 61 | "width": 0.0336618312, 62 | "xcenter": 0.7814827561, 63 | "ycenter": 0.5065554976 64 | } 65 | ] 66 | ``` 67 | 68 | An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given in `example_request.py` 69 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [19,27, 44,40, 38,94] # P3/8 7 | - [96,68, 86,152, 180,137] # P4/16 8 | - [140,301, 303,264, 238,542] # P5/32 9 | - [436,615, 739,380, 925,792] # P6/64 10 | 11 | # YOLOv5 backbone 12 | backbone: 13 | # [from, number, module, args] 14 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 15 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 16 | [-1, 3, C3, [128]], 17 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 18 | [-1, 9, C3, [256]], 19 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 20 | [-1, 9, C3, [512]], 21 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 22 | [-1, 3, C3, [768]], 23 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 24 | [-1, 1, SPP, [1024, [3, 5, 7]]], 25 | [-1, 3, C3, [1024, False]], # 11 26 | ] 27 | 28 | # YOLOv5 head 29 | head: 30 | [[-1, 1, Conv, [768, 1, 1]], 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 32 | [[-1, 8], 1, Concat, [1]], # cat backbone P5 33 | [-1, 3, C3, [768, False]], # 15 34 | 35 | [-1, 1, Conv, [512, 1, 1]], 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 38 | [-1, 3, C3, [512, False]], # 19 39 | 40 | [-1, 1, Conv, [256, 1, 1]], 41 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 42 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 43 | [-1, 3, C3, [256, False]], # 23 (P3/8-small) 44 | 45 | [-1, 1, Conv, [256, 3, 2]], 46 | [[-1, 20], 1, Concat, [1]], # cat head P4 47 | [-1, 3, C3, [512, False]], # 26 (P4/16-medium) 48 | 49 | [-1, 1, Conv, [512, 3, 2]], 50 | [[-1, 16], 1, Concat, [1]], # cat head P5 51 | [-1, 3, C3, [768, False]], # 29 (P5/32-large) 52 | 53 | [-1, 1, Conv, [768, 3, 2]], 54 | [[-1, 12], 1, Concat, [1]], # cat head P6 55 | [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) 56 | 57 | [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) 58 | ] 59 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [19,27, 44,40, 38,94] # P3/8 7 | - [96,68, 86,152, 180,137] # P4/16 8 | - [140,301, 303,264, 238,542] # P5/32 9 | - [436,615, 739,380, 925,792] # P6/64 10 | 11 | # YOLOv5 backbone 12 | backbone: 13 | # [from, number, module, args] 14 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 15 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 16 | [-1, 3, C3, [128]], 17 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 18 | [-1, 9, C3, [256]], 19 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 20 | [-1, 9, C3, [512]], 21 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 22 | [-1, 3, C3, [768]], 23 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 24 | [-1, 1, SPP, [1024, [3, 5, 7]]], 25 | [-1, 3, C3, [1024, False]], # 11 26 | ] 27 | 28 | # YOLOv5 head 29 | head: 30 | [[-1, 1, Conv, [768, 1, 1]], 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 32 | [[-1, 8], 1, Concat, [1]], # cat backbone P5 33 | [-1, 3, C3, [768, False]], # 15 34 | 35 | [-1, 1, Conv, [512, 1, 1]], 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 38 | [-1, 3, C3, [512, False]], # 19 39 | 40 | [-1, 1, Conv, [256, 1, 1]], 41 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 42 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 43 | [-1, 3, C3, [256, False]], # 23 (P3/8-small) 44 | 45 | [-1, 1, Conv, [256, 3, 2]], 46 | [[-1, 20], 1, Concat, [1]], # cat head P4 47 | [-1, 3, C3, [512, False]], # 26 (P4/16-medium) 48 | 49 | [-1, 1, Conv, [512, 3, 2]], 50 | [[-1, 16], 1, Concat, [1]], # cat head P5 51 | [-1, 3, C3, [768, False]], # 29 (P5/32-large) 52 | 53 | [-1, 1, Conv, [768, 3, 2]], 54 | [[-1, 12], 1, Concat, [1]], # cat head P6 55 | [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) 56 | 57 | [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) 58 | ] 59 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [19,27, 44,40, 38,94] # P3/8 7 | - [96,68, 86,152, 180,137] # P4/16 8 | - [140,301, 303,264, 238,542] # P5/32 9 | - [436,615, 739,380, 925,792] # P6/64 10 | 11 | # YOLOv5 backbone 12 | backbone: 13 | # [from, number, module, args] 14 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 15 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 16 | [-1, 3, C3, [128]], 17 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 18 | [-1, 9, C3, [256]], 19 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 20 | [-1, 9, C3, [512]], 21 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 22 | [-1, 3, C3, [768]], 23 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 24 | [-1, 1, SPP, [1024, [3, 5, 7]]], 25 | [-1, 3, C3, [1024, False]], # 11 26 | ] 27 | 28 | # YOLOv5 head 29 | head: 30 | [[-1, 1, Conv, [768, 1, 1]], 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 32 | [[-1, 8], 1, Concat, [1]], # cat backbone P5 33 | [-1, 3, C3, [768, False]], # 15 34 | 35 | [-1, 1, Conv, [512, 1, 1]], 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 38 | [-1, 3, C3, [512, False]], # 19 39 | 40 | [-1, 1, Conv, [256, 1, 1]], 41 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 42 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 43 | [-1, 3, C3, [256, False]], # 23 (P3/8-small) 44 | 45 | [-1, 1, Conv, [256, 3, 2]], 46 | [[-1, 20], 1, Concat, [1]], # cat head P4 47 | [-1, 3, C3, [512, False]], # 26 (P4/16-medium) 48 | 49 | [-1, 1, Conv, [512, 3, 2]], 50 | [[-1, 16], 1, Concat, [1]], # cat head P5 51 | [-1, 3, C3, [768, False]], # 29 (P5/32-large) 52 | 53 | [-1, 1, Conv, [768, 3, 2]], 54 | [[-1, 12], 1, Concat, [1]], # cat head P6 55 | [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) 56 | 57 | [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) 58 | ] 59 | -------------------------------------------------------------------------------- /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 | anchors: 6 | - [19,27, 44,40, 38,94] # P3/8 7 | - [96,68, 86,152, 180,137] # P4/16 8 | - [140,301, 303,264, 238,542] # P5/32 9 | - [436,615, 739,380, 925,792] # P6/64 10 | 11 | # YOLOv5 backbone 12 | backbone: 13 | # [from, number, module, args] 14 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 15 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 16 | [-1, 3, C3, [128]], 17 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 18 | [-1, 9, C3, [256]], 19 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 20 | [-1, 9, C3, [512]], 21 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 22 | [-1, 3, C3, [768]], 23 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 24 | [-1, 1, SPP, [1024, [3, 5, 7]]], 25 | [-1, 3, C3, [1024, False]], # 11 26 | ] 27 | 28 | # YOLOv5 head 29 | head: 30 | [[-1, 1, Conv, [768, 1, 1]], 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 32 | [[-1, 8], 1, Concat, [1]], # cat backbone P5 33 | [-1, 3, C3, [768, False]], # 15 34 | 35 | [-1, 1, Conv, [512, 1, 1]], 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 38 | [-1, 3, C3, [512, False]], # 19 39 | 40 | [-1, 1, Conv, [256, 1, 1]], 41 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 42 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 43 | [-1, 3, C3, [256, False]], # 23 (P3/8-small) 44 | 45 | [-1, 1, Conv, [256, 3, 2]], 46 | [[-1, 20], 1, Concat, [1]], # cat head P4 47 | [-1, 3, C3, [512, False]], # 26 (P4/16-medium) 48 | 49 | [-1, 1, Conv, [512, 3, 2]], 50 | [[-1, 16], 1, Concat, [1]], # cat head P5 51 | [-1, 3, C3, [768, False]], # 29 (P5/32-large) 52 | 53 | [-1, 1, Conv, [768, 3, 2]], 54 | [[-1, 12], 1, Concat, [1]], # cat head P6 55 | [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge) 56 | 57 | [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6) 58 | ] 59 | -------------------------------------------------------------------------------- /data/GlobalWheat2020.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # Global Wheat 2020 dataset http://www.global-wheat.com/ 3 | # Example usage: python train.py --data GlobalWheat2020.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── GlobalWheat2020 ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/GlobalWheat2020 # dataset root dir 12 | train: # train images (relative to 'path') 3422 images 13 | - images/arvalis_1 14 | - images/arvalis_2 15 | - images/arvalis_3 16 | - images/ethz_1 17 | - images/rres_1 18 | - images/inrae_1 19 | - images/usask_1 20 | val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1) 21 | - images/ethz_1 22 | test: # test images (optional) 1276 images 23 | - images/utokyo_1 24 | - images/utokyo_2 25 | - images/nau_1 26 | - images/uq_1 27 | 28 | # Classes 29 | nc: 1 # number of classes 30 | names: ['wheat_head'] # class names 31 | 32 | 33 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 34 | download: | 35 | from utils.general import download, Path 36 | 37 | # Download 38 | dir = Path(yaml['path']) # dataset root dir 39 | urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip', 40 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip'] 41 | download(urls, dir=dir) 42 | 43 | # Make Directories 44 | for p in 'annotations', 'images', 'labels': 45 | (dir / p).mkdir(parents=True, exist_ok=True) 46 | 47 | # Move 48 | for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \ 49 | 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1': 50 | (dir / p).rename(dir / 'images' / p) # move to /images 51 | f = (dir / p).with_suffix('.json') # json file 52 | if f.exists(): 53 | f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rotation-Detect-yolov5_poly 2 | 本项目主要基于yolov5算法的旋转目标检测,主要借鉴项目https://github.com/hukaixuan19970627/YOLOv5_DOTA_OBB 3 | 4 | https://github.com/acai66/yolov5_rotation 5 | 6 | 本项目主要对这两个项目中存在的问题进行改进,主要改进点为针对目标出现在图像边缘位置时,图像预处理会出现label偏移现象,以及对边缘目标没有目标截断操作等预处理方式进行改进。主要改进方式为抛弃原始的yolo形式的预处理方式(centetx,centery,w,h),改成直接对 7 | 旋转矩形框进行预处理,新的label数据类型为(x1,y1,x2,y2,x3,y3,x4,y4) 8 | 9 | ## Installation (Linux Recommend, Windows not Recommend) 10 | ``` 11 | conda create -n rotation_yolo_poly python=3.6 12 | 13 | conda activate rotation_yolo_poly 14 | 15 | conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch 16 | 17 | cd Rotation-Detect-yolov5_poly 18 | 19 | pip install -r requirements 20 | ``` 21 | 22 | 注意我的环境中torch版本是1.9.0,理论上1.7以上版本torch均可运行 23 | 24 | ## Usage Example 25 | ### 1.制作数据集 26 | 通过labelme软件标注的rectangle或者poly均可,标注完成的数据集目录为: 27 | 28 | |_train 29 | 30 | ----|_imgs: 31 | 32 | ----------|1.jpg 33 | 34 | ----------|2.jpg 35 | 36 | ----|_Annotations: 37 | 38 | ----------|1.json 39 | 40 | ----------|2.json 41 | 42 | ----|_min_poly.py 43 | 44 | |_test 45 | 46 | ----|_imgs: 47 | 48 | ----------|1.jpg 49 | 50 | ----------|2.jpg 51 | 52 | ----|_Annotations: 53 | 54 | ----------|1.json 55 | 56 | ----------|2.json 57 | 58 | ----|_min_poly.py 59 | 60 | labelme标注的实例如下图,标注成poly类型或者rec类型均可 61 | ![image](https://user-images.githubusercontent.com/28287748/142178999-246c9059-2507-42cb-8e1c-c17c2567e88a.png) 62 | 63 | ### 2.数据预处理 64 | ``` 65 | python min_poly.py 66 | ``` 67 | 68 | 直接运行min_poly.py文件进行预处理(注意:环境为之前创建的conda虚拟环境),修改min_poly.py中的label_name为自己的类别名称,修改min_poly.py中的115行的name_id为自己的标注文件中标注为多边形poly的类别。(默认已完成训练集和测试集分割) 69 | 70 | ### 3.生成训练集列表 71 | 72 | ``` 73 | python labeldir.py 74 | ``` 75 | 76 | ### 4.开始训练 77 | 78 | #### (1)修改/data路径下的DOTA——ROTATED.yaml文件,将其中的train,val,test,替换成自己的路径,将nc改成自己的类别数,name改成自己的类别名称 79 | 80 | #### (2)修改/utils文件夹中的datasets.py文件中的535行,将在其中的'img'和'labels_poly'改成自己的数据集中的图片文件夹名和label文件夹名称。 81 | 82 | #### (3)运行train.py,对于单卡可直接运行: 83 | 84 | `python train.py --batch-size 4 --device 0` 85 | 86 | 对于多卡训练,运行: 87 | 88 | `python -m torch.distributed.launch --nproc_per_node 4 train.py --device 0,1,2,3` 89 | 90 | #### (4)评估训练效果 91 | 92 | `python val.py` 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /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 | anchors: 3 6 | 7 | # YOLOv5 backbone 8 | backbone: 9 | # [from, number, module, args] 10 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 11 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 12 | [-1, 3, C3, [128]], 13 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 14 | [-1, 9, C3, [256]], 15 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 16 | [-1, 9, C3, [512]], 17 | [-1, 1, Conv, [768, 3, 2]], # 7-P5/32 18 | [-1, 3, C3, [768]], 19 | [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64 20 | [-1, 3, C3, [1024]], 21 | [-1, 1, Conv, [1280, 3, 2]], # 11-P7/128 22 | [-1, 1, SPP, [1280, [3, 5]]], 23 | [-1, 3, C3, [1280, False]], # 13 24 | ] 25 | 26 | # YOLOv5 head 27 | head: 28 | [[-1, 1, Conv, [1024, 1, 1]], 29 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 30 | [[-1, 10], 1, Concat, [1]], # cat backbone P6 31 | [-1, 3, C3, [1024, False]], # 17 32 | 33 | [-1, 1, Conv, [768, 1, 1]], 34 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 35 | [[-1, 8], 1, Concat, [1]], # cat backbone P5 36 | [-1, 3, C3, [768, False]], # 21 37 | 38 | [-1, 1, Conv, [512, 1, 1]], 39 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 40 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 41 | [-1, 3, C3, [512, False]], # 25 42 | 43 | [-1, 1, Conv, [256, 1, 1]], 44 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 45 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 46 | [-1, 3, C3, [256, False]], # 29 (P3/8-small) 47 | 48 | [-1, 1, Conv, [256, 3, 2]], 49 | [[-1, 26], 1, Concat, [1]], # cat head P4 50 | [-1, 3, C3, [512, False]], # 32 (P4/16-medium) 51 | 52 | [-1, 1, Conv, [512, 3, 2]], 53 | [[-1, 22], 1, Concat, [1]], # cat head P5 54 | [-1, 3, C3, [768, False]], # 35 (P5/32-large) 55 | 56 | [-1, 1, Conv, [768, 3, 2]], 57 | [[-1, 18], 1, Concat, [1]], # cat head P6 58 | [-1, 3, C3, [1024, False]], # 38 (P6/64-xlarge) 59 | 60 | [-1, 1, Conv, [1024, 3, 2]], 61 | [[-1, 14], 1, Concat, [1]], # cat head P7 62 | [-1, 3, C3, [1280, False]], # 41 (P7/128-xxlarge) 63 | 64 | [[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6, P7) 65 | ] 66 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # This action runs GitHub's industry-leading static analysis engine, CodeQL, against a repository's source code to find security vulnerabilities. 2 | # https://github.com/github/codeql-action 3 | 4 | name: "CodeQL" 5 | 6 | on: 7 | schedule: 8 | - cron: '0 0 1 * *' # Runs at 00:00 UTC on the 1st of every month 9 | 10 | jobs: 11 | analyze: 12 | name: Analyze 13 | runs-on: ubuntu-latest 14 | 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | language: [ 'python' ] 19 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 20 | # Learn more: 21 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 22 | 23 | steps: 24 | - name: Checkout repository 25 | uses: actions/checkout@v2 26 | 27 | # Initializes the CodeQL tools for scanning. 28 | - name: Initialize CodeQL 29 | uses: github/codeql-action/init@v1 30 | with: 31 | languages: ${{ matrix.language }} 32 | # If you wish to specify custom queries, you can do so here or in a config file. 33 | # By default, queries listed here will override any specified in a config file. 34 | # Prefix the list here with "+" to use these queries and those in the config file. 35 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 36 | 37 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 38 | # If this step fails, then you should remove it and run the build manually (see below) 39 | - name: Autobuild 40 | uses: github/codeql-action/autobuild@v1 41 | 42 | # ℹ️ Command-line programs to run using the OS shell. 43 | # 📚 https://git.io/JvXDl 44 | 45 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 46 | # and modify them (or add more) to build your code if your project 47 | # uses a compiled language 48 | 49 | #- run: | 50 | # make bootstrap 51 | # make release 52 | 53 | - name: Perform CodeQL Analysis 54 | uses: github/codeql-action/analyze@v1 55 | -------------------------------------------------------------------------------- /data/coco.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # COCO 2017 dataset http://cocodataset.org 3 | # Example usage: python train.py --data coco.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── coco ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/coco # dataset root dir 12 | train: train2017.txt # train images (relative to 'path') 118287 images 13 | val: val2017.txt # train images (relative to 'path') 5000 images 14 | test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794 15 | 16 | # Classes 17 | nc: 80 # number of classes 18 | names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 19 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 20 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 21 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 22 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 23 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 24 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 25 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 26 | 'hair drier', 'toothbrush'] # class names 27 | 28 | 29 | # Download script/URL (optional) 30 | download: | 31 | from utils.general import download, Path 32 | 33 | # Download labels 34 | segments = False # segment or box labels 35 | dir = Path(yaml['path']) # dataset root dir 36 | url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' 37 | urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels 38 | download(urls, dir=dir.parent) 39 | 40 | # Download data 41 | urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images 42 | 'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images 43 | 'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional) 44 | download(urls, dir=dir / 'images', threads=3) 45 | -------------------------------------------------------------------------------- /data/SKU-110K.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 3 | # Example usage: python train.py --data SKU-110K.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── SKU-110K ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/SKU-110K # dataset root dir 12 | train: train.txt # train images (relative to 'path') 8219 images 13 | val: val.txt # val images (relative to 'path') 588 images 14 | test: test.txt # test images (optional) 2936 images 15 | 16 | # Classes 17 | nc: 1 # number of classes 18 | names: ['object'] # class names 19 | 20 | 21 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 22 | download: | 23 | import shutil 24 | from tqdm import tqdm 25 | from utils.general import np, pd, Path, download, xyxy2xywh 26 | 27 | # Download 28 | dir = Path(yaml['path']) # dataset root dir 29 | parent = Path(dir.parent) # download dir 30 | urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz'] 31 | download(urls, dir=parent, delete=False) 32 | 33 | # Rename directories 34 | if dir.exists(): 35 | shutil.rmtree(dir) 36 | (parent / 'SKU110K_fixed').rename(dir) # rename dir 37 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir 38 | 39 | # Convert labels 40 | names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names 41 | for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv': 42 | x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations 43 | images, unique_images = x[:, 0], np.unique(x[:, 0]) 44 | with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f: 45 | f.writelines(f'./images/{s}\n' for s in unique_images) 46 | for im in tqdm(unique_images, desc=f'Converting {dir / d}'): 47 | cls = 0 # single-class dataset 48 | with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f: 49 | for r in x[images == im]: 50 | w, h = r[6], r[7] # image width, height 51 | xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance 52 | f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label 53 | -------------------------------------------------------------------------------- /models/yolov5s.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 10 # number of classes 3 | depth_multiple: 0.33 # model depth multiple 4 | width_multiple: 0.50 # layer channel multiple 5 | 6 | # anchors 7 | # 7,7, 15,13, 15,34, 26,20, 30,71, 41,35, 69,58, 98,118, 166,241 8 | 9 | # gkxfw 10 | # anchors: 11 | # - [23,36, 49,56, 54,127] # P3/8 12 | # - [93,66, 101,216, 165,111] # P4/16 13 | # - [177,347, 290,193, 365,408] # P5/32 14 | 15 | # tongdao 16 | # anchors: 17 | # - [14,13, 27,14, 24,33] # P3/8 18 | # - [47,21, 31,77, 53,46] # P4/16 19 | # - [101,32, 89,86, 158,214] # P5/32 20 | 21 | # person 22 | # anchors: 23 | # - [13,36, 25,68, 37,140] # P3/8 24 | # - [64,103, 69,226, 110,400] # P4/16 25 | # - [159,228, 210,478, 413,549] # P5/32 26 | 27 | # Crowd Human 28 | anchors: 29 | - [6,12, 11,22, 16,36] # P3/8 30 | - [26,46, 28,81, 47,103] # P4/16 31 | - [59,174, 88,242, 164,292] # P5/32 32 | 33 | # coco 34 | # anchors: 35 | # - [10,13, 16,30, 33,23] # P3/8 36 | # - [30,61, 62,45, 59,119] # P4/16 37 | # - [116,90, 156,198, 373,326] # P5/32 38 | 39 | # xiaochicun_01 40 | # anchors: 41 | # - [1,2, 2,3, 3,4] # P3/8 42 | # - [3,5, 4,7, 5,7] # P4/16 43 | # - [5,8, 6,11, 9,21] # P5/32 44 | 45 | 46 | # yinyetin 47 | # anchors: 48 | # - [18,32, 25,57, 34,97] # P3/8 49 | # - [52,84, 55,153, 75,112] # P4/16 50 | # - [96,162, 119,248, 175,296] # P5/32 51 | 52 | # just ys xtc 53 | # anchors: 54 | # - [14,48, 20,52, 22,36] # P3/8 55 | # - [25,48, 25,56, 27,52] # P4/16 56 | # - [30,44, 46,70, 76,129] # P5/32 57 | 58 | 59 | backbone: 60 | # 61 | 62 | [[-1, 1, Conv, [32, 3, 1]], 63 | [-1, 1, Conv, [64, 3, 2]], # 0-P1/2 64 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 65 | [-1, 3, C3, [128]], 66 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 67 | [-1, 9, C3, [256]], 68 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 69 | [-1, 9, C3, [512]], 70 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 71 | [-1, 1, SPP, [1024, [5, 9, 13]]], 72 | [-1, 3, C3, [1024, False]], # 9 73 | ] 74 | 75 | # YOLOv5 head 76 | head: 77 | [[-1, 1, Conv, [512, 1, 1]], 78 | [-1, 1, nn.Upsample, [None, 2, 'bilinear',True]], 79 | [[-1, 7], 1, Concat, [1]], # cat backbone P4 80 | [-1, 3, C3, [512, False]], # 13 81 | 82 | [-1, 1, Conv, [256, 1, 1]], 83 | [-1, 1, nn.Upsample, [None, 2, 'bilinear',True]], 84 | [[-1, 5], 1, Concat, [1]], # cat backbone P3 85 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 86 | 87 | [-1, 1, Conv, [256, 3, 2]], 88 | [[-1, 15], 1, Concat, [1]], # cat head P4 89 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 90 | 91 | [-1, 1, Conv, [512, 3, 2]], 92 | [[-1, 11], 1, Concat, [1]], # cat head P5 93 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 94 | 95 | [[18, 21, 24], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 96 | ] 97 | -------------------------------------------------------------------------------- /data/Argoverse.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ 3 | # Example usage: python train.py --data Argoverse.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── Argoverse ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/Argoverse # dataset root dir 12 | train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images 13 | val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images 14 | test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview 15 | 16 | # Classes 17 | nc: 8 # number of classes 18 | names: ['person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign'] # class names 19 | 20 | 21 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 22 | download: | 23 | import json 24 | 25 | from tqdm import tqdm 26 | from utils.general import download, Path 27 | 28 | 29 | def argoverse2yolo(set): 30 | labels = {} 31 | a = json.load(open(set, "rb")) 32 | for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."): 33 | img_id = annot['image_id'] 34 | img_name = a['images'][img_id]['name'] 35 | img_label_name = img_name[:-3] + "txt" 36 | 37 | cls = annot['category_id'] # instance class id 38 | x_center, y_center, width, height = annot['bbox'] 39 | x_center = (x_center + width / 2) / 1920.0 # offset and scale 40 | y_center = (y_center + height / 2) / 1200.0 # offset and scale 41 | width /= 1920.0 # scale 42 | height /= 1200.0 # scale 43 | 44 | img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']] 45 | if not img_dir.exists(): 46 | img_dir.mkdir(parents=True, exist_ok=True) 47 | 48 | k = str(img_dir / img_label_name) 49 | if k not in labels: 50 | labels[k] = [] 51 | labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n") 52 | 53 | for k in labels: 54 | with open(k, "w") as f: 55 | f.writelines(labels[k]) 56 | 57 | 58 | # Download 59 | dir = Path('../datasets/Argoverse') # dataset root dir 60 | urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip'] 61 | download(urls, dir=dir, delete=False) 62 | 63 | # Convert 64 | annotations_dir = 'Argoverse-HD/annotations/' 65 | (dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images' 66 | for d in "train.json", "val.json": 67 | argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels 68 | -------------------------------------------------------------------------------- /data/VisDrone.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset 3 | # Example usage: python train.py --data VisDrone.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── VisDrone ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/VisDrone # dataset root dir 12 | train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images 13 | val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images 14 | test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images 15 | 16 | # Classes 17 | nc: 10 # number of classes 18 | names: ['pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor'] 19 | 20 | 21 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 22 | download: | 23 | from utils.general import download, os, Path 24 | 25 | def visdrone2yolo(dir): 26 | from PIL import Image 27 | from tqdm import tqdm 28 | 29 | def convert_box(size, box): 30 | # Convert VisDrone box to YOLO xywh box 31 | dw = 1. / size[0] 32 | dh = 1. / size[1] 33 | return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh 34 | 35 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory 36 | pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}') 37 | for f in pbar: 38 | img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size 39 | lines = [] 40 | with open(f, 'r') as file: # read annotation.txt 41 | for row in [x.split(',') for x in file.read().strip().splitlines()]: 42 | if row[4] == '0': # VisDrone 'ignored regions' class 0 43 | continue 44 | cls = int(row[5]) - 1 45 | box = convert_box(img_size, tuple(map(int, row[:4]))) 46 | lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n") 47 | with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl: 48 | fl.writelines(lines) # write label.txt 49 | 50 | 51 | # Download 52 | dir = Path(yaml['path']) # dataset root dir 53 | urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip', 54 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip', 55 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip', 56 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip'] 57 | download(urls, dir=dir) 58 | 59 | # Convert 60 | for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev': 61 | visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels 62 | -------------------------------------------------------------------------------- /.github/workflows/ci-testing.yml: -------------------------------------------------------------------------------- 1 | name: CI CPU testing 2 | 3 | on: # https://help.github.com/en/actions/reference/events-that-trigger-workflows 4 | push: 5 | branches: [ master, develop ] 6 | pull_request: 7 | # The branches below must be a subset of the branches above 8 | branches: [ master, develop ] 9 | 10 | jobs: 11 | cpu-tests: 12 | 13 | runs-on: ${{ matrix.os }} 14 | strategy: 15 | fail-fast: false 16 | matrix: 17 | os: [ ubuntu-latest, macos-latest, windows-latest ] 18 | python-version: [ 3.8 ] 19 | model: [ 'yolov5s' ] # models to test 20 | 21 | # Timeout: https://stackoverflow.com/a/59076067/4521646 22 | timeout-minutes: 50 23 | steps: 24 | - uses: actions/checkout@v2 25 | - name: Set up Python ${{ matrix.python-version }} 26 | uses: actions/setup-python@v2 27 | with: 28 | python-version: ${{ matrix.python-version }} 29 | 30 | # Note: This uses an internal pip API and may not always work 31 | # https://github.com/actions/cache/blob/master/examples.md#multiple-oss-in-a-workflow 32 | - name: Get pip cache 33 | id: pip-cache 34 | run: | 35 | python -c "from pip._internal.locations import USER_CACHE_DIR; print('::set-output name=dir::' + USER_CACHE_DIR)" 36 | 37 | - name: Cache pip 38 | uses: actions/cache@v1 39 | with: 40 | path: ${{ steps.pip-cache.outputs.dir }} 41 | key: ${{ runner.os }}-${{ matrix.python-version }}-pip-${{ hashFiles('requirements.txt') }} 42 | restore-keys: | 43 | ${{ runner.os }}-${{ matrix.python-version }}-pip- 44 | 45 | - name: Install dependencies 46 | run: | 47 | python -m pip install --upgrade pip 48 | pip install -qr requirements.txt -f https://download.pytorch.org/whl/cpu/torch_stable.html 49 | pip install -q onnx 50 | python --version 51 | pip --version 52 | pip list 53 | shell: bash 54 | 55 | - name: Download data 56 | run: | 57 | # curl -L -o tmp.zip https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip 58 | # unzip -q tmp.zip -d ../ 59 | # rm tmp.zip 60 | 61 | - name: Tests workflow 62 | run: | 63 | # export PYTHONPATH="$PWD" # to run '$ python *.py' files in subdirectories 64 | di=cpu # inference devices # define device 65 | 66 | # train 67 | python train.py --img 128 --batch 16 --weights ${{ matrix.model }}.pt --cfg ${{ matrix.model }}.yaml --epochs 1 --device $di 68 | # detect 69 | python detect.py --weights ${{ matrix.model }}.pt --device $di 70 | python detect.py --weights runs/train/exp/weights/last.pt --device $di 71 | # val 72 | python val.py --img 128 --batch 16 --weights ${{ matrix.model }}.pt --device $di 73 | python val.py --img 128 --batch 16 --weights runs/train/exp/weights/last.pt --device $di 74 | 75 | python hubconf.py # hub 76 | python models/yolo.py --cfg ${{ matrix.model }}.yaml # inspect 77 | python export.py --img 128 --batch 1 --weights ${{ matrix.model }}.pt # export 78 | shell: bash 79 | -------------------------------------------------------------------------------- /utils/loggers/wandb/sweep.yaml: -------------------------------------------------------------------------------- 1 | # Hyperparameters for training 2 | # To set range- 3 | # Provide min and max values as: 4 | # parameter: 5 | # 6 | # min: scalar 7 | # max: scalar 8 | # OR 9 | # 10 | # Set a specific list of search space- 11 | # parameter: 12 | # values: [scalar1, scalar2, scalar3...] 13 | # 14 | # You can use grid, bayesian and hyperopt search strategy 15 | # For more info on configuring sweeps visit - https://docs.wandb.ai/guides/sweeps/configuration 16 | 17 | program: utils/loggers/wandb/sweep.py 18 | method: random 19 | metric: 20 | name: metrics/mAP_0.5 21 | goal: maximize 22 | 23 | parameters: 24 | # hyperparameters: set either min, max range or values list 25 | data: 26 | value: "data/coco128.yaml" 27 | batch_size: 28 | values: [64] 29 | epochs: 30 | values: [10] 31 | 32 | lr0: 33 | distribution: uniform 34 | min: 1e-5 35 | max: 1e-1 36 | lrf: 37 | distribution: uniform 38 | min: 0.01 39 | max: 1.0 40 | momentum: 41 | distribution: uniform 42 | min: 0.6 43 | max: 0.98 44 | weight_decay: 45 | distribution: uniform 46 | min: 0.0 47 | max: 0.001 48 | warmup_epochs: 49 | distribution: uniform 50 | min: 0.0 51 | max: 5.0 52 | warmup_momentum: 53 | distribution: uniform 54 | min: 0.0 55 | max: 0.95 56 | warmup_bias_lr: 57 | distribution: uniform 58 | min: 0.0 59 | max: 0.2 60 | box: 61 | distribution: uniform 62 | min: 0.02 63 | max: 0.2 64 | cls: 65 | distribution: uniform 66 | min: 0.2 67 | max: 4.0 68 | cls_pw: 69 | distribution: uniform 70 | min: 0.5 71 | max: 2.0 72 | obj: 73 | distribution: uniform 74 | min: 0.2 75 | max: 4.0 76 | obj_pw: 77 | distribution: uniform 78 | min: 0.5 79 | max: 2.0 80 | iou_t: 81 | distribution: uniform 82 | min: 0.1 83 | max: 0.7 84 | anchor_t: 85 | distribution: uniform 86 | min: 2.0 87 | max: 8.0 88 | fl_gamma: 89 | distribution: uniform 90 | min: 0.0 91 | max: 0.1 92 | hsv_h: 93 | distribution: uniform 94 | min: 0.0 95 | max: 0.1 96 | hsv_s: 97 | distribution: uniform 98 | min: 0.0 99 | max: 0.9 100 | hsv_v: 101 | distribution: uniform 102 | min: 0.0 103 | max: 0.9 104 | degrees: 105 | distribution: uniform 106 | min: 0.0 107 | max: 45.0 108 | translate: 109 | distribution: uniform 110 | min: 0.0 111 | max: 0.9 112 | scale: 113 | distribution: uniform 114 | min: 0.0 115 | max: 0.9 116 | shear: 117 | distribution: uniform 118 | min: 0.0 119 | max: 10.0 120 | perspective: 121 | distribution: uniform 122 | min: 0.0 123 | max: 0.001 124 | flipud: 125 | distribution: uniform 126 | min: 0.0 127 | max: 1.0 128 | fliplr: 129 | distribution: uniform 130 | min: 0.0 131 | max: 1.0 132 | mosaic: 133 | distribution: uniform 134 | min: 0.0 135 | max: 1.0 136 | mixup: 137 | distribution: uniform 138 | min: 0.0 139 | max: 1.0 140 | copy_paste: 141 | distribution: uniform 142 | min: 0.0 143 | max: 1.0 144 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /data/VOC.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC 3 | # Example usage: python train.py --data VOC.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── VOC ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/VOC 12 | train: # train images (relative to 'path') 16551 images 13 | - images/train2012 14 | - images/train2007 15 | - images/val2012 16 | - images/val2007 17 | val: # val images (relative to 'path') 4952 images 18 | - images/test2007 19 | test: # test images (optional) 20 | - images/test2007 21 | 22 | # Classes 23 | nc: 20 # number of classes 24 | names: ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 25 | 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] # class names 26 | 27 | 28 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 29 | download: | 30 | import xml.etree.ElementTree as ET 31 | 32 | from tqdm import tqdm 33 | from utils.general import download, Path 34 | 35 | 36 | def convert_label(path, lb_path, year, image_id): 37 | def convert_box(size, box): 38 | dw, dh = 1. / size[0], 1. / size[1] 39 | x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2] 40 | return x * dw, y * dh, w * dw, h * dh 41 | 42 | in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml') 43 | out_file = open(lb_path, 'w') 44 | tree = ET.parse(in_file) 45 | root = tree.getroot() 46 | size = root.find('size') 47 | w = int(size.find('width').text) 48 | h = int(size.find('height').text) 49 | 50 | for obj in root.iter('object'): 51 | cls = obj.find('name').text 52 | if cls in yaml['names'] and not int(obj.find('difficult').text) == 1: 53 | xmlbox = obj.find('bndbox') 54 | bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')]) 55 | cls_id = yaml['names'].index(cls) # class id 56 | out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n') 57 | 58 | 59 | # Download 60 | dir = Path(yaml['path']) # dataset root dir 61 | url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' 62 | urls = [url + 'VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images 63 | url + 'VOCtest_06-Nov-2007.zip', # 438MB, 4953 images 64 | url + 'VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images 65 | download(urls, dir=dir / 'images', delete=False) 66 | 67 | # Convert 68 | path = dir / f'images/VOCdevkit' 69 | for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'): 70 | imgs_path = dir / 'images' / f'{image_set}{year}' 71 | lbs_path = dir / 'labels' / f'{image_set}{year}' 72 | imgs_path.mkdir(exist_ok=True, parents=True) 73 | lbs_path.mkdir(exist_ok=True, parents=True) 74 | 75 | image_ids = open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt').read().strip().split() 76 | for id in tqdm(image_ids, desc=f'{image_set}{year}'): 77 | f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path 78 | lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path 79 | f.rename(imgs_path / f.name) # move image 80 | convert_label(path, lb_path, year, id) # convert labels to YOLO format 81 | -------------------------------------------------------------------------------- /utils/activations.py: -------------------------------------------------------------------------------- 1 | # Activation functions 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | 8 | # SiLU https://arxiv.org/pdf/1606.08415.pdf ---------------------------------------------------------------------------- 9 | class SiLU(nn.Module): # export-friendly version of nn.SiLU() 10 | @staticmethod 11 | def forward(x): 12 | return x * torch.sigmoid(x) 13 | 14 | 15 | class Hardswish(nn.Module): # export-friendly version of nn.Hardswish() 16 | @staticmethod 17 | def forward(x): 18 | # return x * F.hardsigmoid(x) # for torchscript and CoreML 19 | return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX 20 | 21 | 22 | # Mish https://github.com/digantamisra98/Mish -------------------------------------------------------------------------- 23 | class Mish(nn.Module): 24 | @staticmethod 25 | def forward(x): 26 | return x * F.softplus(x).tanh() 27 | 28 | 29 | class MemoryEfficientMish(nn.Module): 30 | class F(torch.autograd.Function): 31 | @staticmethod 32 | def forward(ctx, x): 33 | ctx.save_for_backward(x) 34 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) 35 | 36 | @staticmethod 37 | def backward(ctx, grad_output): 38 | x = ctx.saved_tensors[0] 39 | sx = torch.sigmoid(x) 40 | fx = F.softplus(x).tanh() 41 | return grad_output * (fx + x * sx * (1 - fx * fx)) 42 | 43 | def forward(self, x): 44 | return self.F.apply(x) 45 | 46 | 47 | # FReLU https://arxiv.org/abs/2007.11824 ------------------------------------------------------------------------------- 48 | class FReLU(nn.Module): 49 | def __init__(self, c1, k=3): # ch_in, kernel 50 | super().__init__() 51 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) 52 | self.bn = nn.BatchNorm2d(c1) 53 | 54 | def forward(self, x): 55 | return torch.max(x, self.bn(self.conv(x))) 56 | 57 | 58 | # ACON https://arxiv.org/pdf/2009.04759.pdf ---------------------------------------------------------------------------- 59 | class AconC(nn.Module): 60 | r""" ACON activation (activate or not). 61 | AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter 62 | according to "Activate or Not: Learning Customized Activation" . 63 | """ 64 | 65 | def __init__(self, c1): 66 | super().__init__() 67 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) 68 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) 69 | self.beta = nn.Parameter(torch.ones(1, c1, 1, 1)) 70 | 71 | def forward(self, x): 72 | dpx = (self.p1 - self.p2) * x 73 | return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x 74 | 75 | 76 | class MetaAconC(nn.Module): 77 | r""" ACON activation (activate or not). 78 | MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network 79 | according to "Activate or Not: Learning Customized Activation" . 80 | """ 81 | 82 | def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r 83 | super().__init__() 84 | c2 = max(r, c1 // r) 85 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) 86 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) 87 | self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True) 88 | self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True) 89 | # self.bn1 = nn.BatchNorm2d(c2) 90 | # self.bn2 = nn.BatchNorm2d(c1) 91 | 92 | def forward(self, x): 93 | y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True) 94 | # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891 95 | # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable 96 | beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed 97 | dpx = (self.p1 - self.p2) * x 98 | return dpx * torch.sigmoid(beta * dpx) + self.p2 * x 99 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | # Repo-specific DockerIgnore ------------------------------------------------------------------------------------------- 2 | #.git 3 | .cache 4 | .idea 5 | runs 6 | output 7 | coco 8 | storage.googleapis.com 9 | 10 | data/samples/* 11 | **/results*.csv 12 | *.jpg 13 | 14 | # Neural Network weights ----------------------------------------------------------------------------------------------- 15 | **/*.pt 16 | **/*.pth 17 | **/*.onnx 18 | **/*.mlmodel 19 | **/*.torchscript 20 | **/*.torchscript.pt 21 | 22 | 23 | # Below Copied From .gitignore ----------------------------------------------------------------------------------------- 24 | # Below Copied From .gitignore ----------------------------------------------------------------------------------------- 25 | 26 | 27 | # GitHub Python GitIgnore ---------------------------------------------------------------------------------------------- 28 | # Byte-compiled / optimized / DLL files 29 | __pycache__/ 30 | *.py[cod] 31 | *$py.class 32 | 33 | # C extensions 34 | *.so 35 | 36 | # Distribution / packaging 37 | .Python 38 | env/ 39 | build/ 40 | develop-eggs/ 41 | dist/ 42 | downloads/ 43 | eggs/ 44 | .eggs/ 45 | lib/ 46 | lib64/ 47 | parts/ 48 | sdist/ 49 | var/ 50 | wheels/ 51 | *.egg-info/ 52 | wandb/ 53 | .installed.cfg 54 | *.egg 55 | 56 | # PyInstaller 57 | # Usually these files are written by a python script from a template 58 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 59 | *.manifest 60 | *.spec 61 | 62 | # Installer logs 63 | pip-log.txt 64 | pip-delete-this-directory.txt 65 | 66 | # Unit test / coverage reports 67 | htmlcov/ 68 | .tox/ 69 | .coverage 70 | .coverage.* 71 | .cache 72 | nosetests.xml 73 | coverage.xml 74 | *.cover 75 | .hypothesis/ 76 | 77 | # Translations 78 | *.mo 79 | *.pot 80 | 81 | # Django stuff: 82 | *.log 83 | local_settings.py 84 | 85 | # Flask stuff: 86 | instance/ 87 | .webassets-cache 88 | 89 | # Scrapy stuff: 90 | .scrapy 91 | 92 | # Sphinx documentation 93 | docs/_build/ 94 | 95 | # PyBuilder 96 | target/ 97 | 98 | # Jupyter Notebook 99 | .ipynb_checkpoints 100 | 101 | # pyenv 102 | .python-version 103 | 104 | # celery beat schedule file 105 | celerybeat-schedule 106 | 107 | # SageMath parsed files 108 | *.sage.py 109 | 110 | # dotenv 111 | .env 112 | 113 | # virtualenv 114 | .venv* 115 | venv*/ 116 | ENV*/ 117 | 118 | # Spyder project settings 119 | .spyderproject 120 | .spyproject 121 | 122 | # Rope project settings 123 | .ropeproject 124 | 125 | # mkdocs documentation 126 | /site 127 | 128 | # mypy 129 | .mypy_cache/ 130 | 131 | 132 | # https://github.com/github/gitignore/blob/master/Global/macOS.gitignore ----------------------------------------------- 133 | 134 | # General 135 | .DS_Store 136 | .AppleDouble 137 | .LSOverride 138 | 139 | # Icon must end with two \r 140 | Icon 141 | Icon? 142 | 143 | # Thumbnails 144 | ._* 145 | 146 | # Files that might appear in the root of a volume 147 | .DocumentRevisions-V100 148 | .fseventsd 149 | .Spotlight-V100 150 | .TemporaryItems 151 | .Trashes 152 | .VolumeIcon.icns 153 | .com.apple.timemachine.donotpresent 154 | 155 | # Directories potentially created on remote AFP share 156 | .AppleDB 157 | .AppleDesktop 158 | Network Trash Folder 159 | Temporary Items 160 | .apdisk 161 | 162 | 163 | # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore 164 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 165 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 166 | 167 | # User-specific stuff: 168 | .idea/* 169 | .idea/**/workspace.xml 170 | .idea/**/tasks.xml 171 | .idea/dictionaries 172 | .html # Bokeh Plots 173 | .pg # TensorFlow Frozen Graphs 174 | .avi # videos 175 | 176 | # Sensitive or high-churn files: 177 | .idea/**/dataSources/ 178 | .idea/**/dataSources.ids 179 | .idea/**/dataSources.local.xml 180 | .idea/**/sqlDataSources.xml 181 | .idea/**/dynamic.xml 182 | .idea/**/uiDesigner.xml 183 | 184 | # Gradle: 185 | .idea/**/gradle.xml 186 | .idea/**/libraries 187 | 188 | # CMake 189 | cmake-build-debug/ 190 | cmake-build-release/ 191 | 192 | # Mongo Explorer plugin: 193 | .idea/**/mongoSettings.xml 194 | 195 | ## File-based project format: 196 | *.iws 197 | 198 | ## Plugin-specific files: 199 | 200 | # IntelliJ 201 | out/ 202 | 203 | # mpeltonen/sbt-idea plugin 204 | .idea_modules/ 205 | 206 | # JIRA plugin 207 | atlassian-ide-plugin.xml 208 | 209 | # Cursive Clojure plugin 210 | .idea/replstate.xml 211 | 212 | # Crashlytics plugin (for Android Studio and IntelliJ) 213 | com_crashlytics_export_strings.xml 214 | crashlytics.properties 215 | crashlytics-build.properties 216 | fabric.properties 217 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: [ pull_request_target, issues ] 4 | 5 | jobs: 6 | greeting: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/first-interaction@v1 10 | with: 11 | repo-token: ${{ secrets.GITHUB_TOKEN }} 12 | pr-message: | 13 | 👋 Hello @${{ github.actor }}, thank you for submitting a 🚀 PR! To allow your work to be integrated as seamlessly as possible, we advise you to: 14 | - ✅ Verify your PR is **up-to-date with origin/master.** If your PR is behind origin/master an automatic [GitHub actions](https://github.com/ultralytics/yolov5/blob/master/.github/workflows/rebase.yml) rebase may be attempted by including the /rebase command in a comment body, or by running the following code, replacing 'feature' with the name of your local branch: 15 | ```bash 16 | git remote add upstream https://github.com/ultralytics/yolov5.git 17 | git fetch upstream 18 | git checkout feature # <----- replace 'feature' with local branch name 19 | git rebase upstream/master 20 | git push -u origin -f 21 | ``` 22 | - ✅ Verify all Continuous Integration (CI) **checks are passing**. 23 | - ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ -Bruce Lee 24 | 25 | issue-message: | 26 | 👋 Hello @${{ github.actor }}, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ [Tutorials](https://github.com/ultralytics/yolov5/wiki#tutorials) to get started, where you can find quickstart guides for simple tasks like [Custom Data Training](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) all the way to advanced concepts like [Hyperparameter Evolution](https://github.com/ultralytics/yolov5/issues/607). 27 | 28 | If this is a 🐛 Bug Report, please provide screenshots and **minimum viable code to reproduce your issue**, otherwise we can not help you. 29 | 30 | If this is a custom training ❓ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online [W&B logging](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data#visualize) if available. 31 | 32 | For business inquiries or professional support requests please visit https://ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com. 33 | 34 | ## Requirements 35 | 36 | [**Python>=3.6.0**](https://www.python.org/) with all [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) installed including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). To get started: 37 | ```bash 38 | $ git clone https://github.com/ultralytics/yolov5 39 | $ cd yolov5 40 | $ pip install -r requirements.txt 41 | ``` 42 | 43 | ## Environments 44 | 45 | YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled): 46 | 47 | - **Google Colab and Kaggle** notebooks with free GPU: Open In Colab Open In Kaggle 48 | - **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) 49 | - **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart) 50 | - **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) Docker Pulls 51 | 52 | 53 | ## Status 54 | 55 | ![CI CPU testing](https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg) 56 | 57 | If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), validation ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on MacOS, Windows, and Ubuntu every 24 hours and on every commit. 58 | 59 | -------------------------------------------------------------------------------- /.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 | *.cfg 23 | !cfg/yolov3*.cfg 24 | 25 | storage.googleapis.com 26 | runs/* 27 | data/* 28 | !data/hyps/* 29 | !data/images/zidane.jpg 30 | !data/images/bus.jpg 31 | !data/*.sh 32 | 33 | results*.csv 34 | 35 | # Datasets ------------------------------------------------------------------------------------------------------------- 36 | coco/ 37 | coco128/ 38 | VOC/ 39 | 40 | # MATLAB GitIgnore ----------------------------------------------------------------------------------------------------- 41 | *.m~ 42 | *.mat 43 | !targets*.mat 44 | 45 | # Neural Network weights ----------------------------------------------------------------------------------------------- 46 | *.weights 47 | *.pt 48 | *.onnx 49 | *.mlmodel 50 | *.torchscript 51 | darknet53.conv.74 52 | yolov3-tiny.conv.15 53 | 54 | # GitHub Python GitIgnore ---------------------------------------------------------------------------------------------- 55 | # Byte-compiled / optimized / DLL files 56 | __pycache__/ 57 | *.py[cod] 58 | *$py.class 59 | 60 | # C extensions 61 | *.so 62 | 63 | # Distribution / packaging 64 | .Python 65 | env/ 66 | build/ 67 | develop-eggs/ 68 | dist/ 69 | downloads/ 70 | eggs/ 71 | .eggs/ 72 | lib/ 73 | lib64/ 74 | parts/ 75 | sdist/ 76 | var/ 77 | wheels/ 78 | *.egg-info/ 79 | wandb/ 80 | .installed.cfg 81 | *.egg 82 | 83 | 84 | # PyInstaller 85 | # Usually these files are written by a python script from a template 86 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 87 | *.manifest 88 | *.spec 89 | 90 | # Installer logs 91 | pip-log.txt 92 | pip-delete-this-directory.txt 93 | 94 | # Unit test / coverage reports 95 | htmlcov/ 96 | .tox/ 97 | .coverage 98 | .coverage.* 99 | .cache 100 | nosetests.xml 101 | coverage.xml 102 | *.cover 103 | .hypothesis/ 104 | 105 | # Translations 106 | *.mo 107 | *.pot 108 | 109 | # Django stuff: 110 | *.log 111 | local_settings.py 112 | 113 | # Flask stuff: 114 | instance/ 115 | .webassets-cache 116 | 117 | # Scrapy stuff: 118 | .scrapy 119 | 120 | # Sphinx documentation 121 | docs/_build/ 122 | 123 | # PyBuilder 124 | target/ 125 | 126 | # Jupyter Notebook 127 | .ipynb_checkpoints 128 | 129 | # pyenv 130 | .python-version 131 | 132 | # celery beat schedule file 133 | celerybeat-schedule 134 | 135 | # SageMath parsed files 136 | *.sage.py 137 | 138 | # dotenv 139 | .env 140 | 141 | # virtualenv 142 | .venv* 143 | venv*/ 144 | ENV*/ 145 | 146 | # Spyder project settings 147 | .spyderproject 148 | .spyproject 149 | 150 | # Rope project settings 151 | .ropeproject 152 | 153 | # mkdocs documentation 154 | /site 155 | 156 | # mypy 157 | .mypy_cache/ 158 | 159 | 160 | # https://github.com/github/gitignore/blob/master/Global/macOS.gitignore ----------------------------------------------- 161 | 162 | # General 163 | .DS_Store 164 | .AppleDouble 165 | .LSOverride 166 | 167 | # Icon must end with two \r 168 | Icon 169 | Icon? 170 | 171 | # Thumbnails 172 | ._* 173 | 174 | # Files that might appear in the root of a volume 175 | .DocumentRevisions-V100 176 | .fseventsd 177 | .Spotlight-V100 178 | .TemporaryItems 179 | .Trashes 180 | .VolumeIcon.icns 181 | .com.apple.timemachine.donotpresent 182 | 183 | # Directories potentially created on remote AFP share 184 | .AppleDB 185 | .AppleDesktop 186 | Network Trash Folder 187 | Temporary Items 188 | .apdisk 189 | 190 | 191 | # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore 192 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 193 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 194 | 195 | # User-specific stuff: 196 | .idea/* 197 | .idea/**/workspace.xml 198 | .idea/**/tasks.xml 199 | .idea/dictionaries 200 | .html # Bokeh Plots 201 | .pg # TensorFlow Frozen Graphs 202 | .avi # videos 203 | 204 | # Sensitive or high-churn files: 205 | .idea/**/dataSources/ 206 | .idea/**/dataSources.ids 207 | .idea/**/dataSources.local.xml 208 | .idea/**/sqlDataSources.xml 209 | .idea/**/dynamic.xml 210 | .idea/**/uiDesigner.xml 211 | 212 | # Gradle: 213 | .idea/**/gradle.xml 214 | .idea/**/libraries 215 | 216 | # CMake 217 | cmake-build-debug/ 218 | cmake-build-release/ 219 | 220 | # Mongo Explorer plugin: 221 | .idea/**/mongoSettings.xml 222 | 223 | ## File-based project format: 224 | *.iws 225 | 226 | ## Plugin-specific files: 227 | 228 | # IntelliJ 229 | out/ 230 | 231 | # mpeltonen/sbt-idea plugin 232 | .idea_modules/ 233 | 234 | # JIRA plugin 235 | atlassian-ide-plugin.xml 236 | 237 | # Cursive Clojure plugin 238 | .idea/replstate.xml 239 | 240 | # Crashlytics plugin (for Android Studio and IntelliJ) 241 | com_crashlytics_export_strings.xml 242 | crashlytics.properties 243 | crashlytics-build.properties 244 | fabric.properties 245 | -------------------------------------------------------------------------------- /data/xView.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # xView 2018 dataset https://challenge.xviewdataset.org 3 | # -------- DOWNLOAD DATA MANUALLY from URL above and unzip to 'datasets/xView' before running train command! -------- 4 | # Example usage: python train.py --data xView.yaml 5 | # parent 6 | # ├── yolov5 7 | # └── datasets 8 | # └── xView ← downloads here 9 | 10 | 11 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 12 | path: ../datasets/xView # dataset root dir 13 | train: images/autosplit_train.txt # train images (relative to 'path') 90% of 847 train images 14 | val: images/autosplit_val.txt # train images (relative to 'path') 10% of 847 train images 15 | 16 | # Classes 17 | nc: 60 # number of classes 18 | names: ['Fixed-wing Aircraft', 'Small Aircraft', 'Cargo Plane', 'Helicopter', 'Passenger Vehicle', 'Small Car', 'Bus', 19 | 'Pickup Truck', 'Utility Truck', 'Truck', 'Cargo Truck', 'Truck w/Box', 'Truck Tractor', 'Trailer', 20 | 'Truck w/Flatbed', 'Truck w/Liquid', 'Crane Truck', 'Railway Vehicle', 'Passenger Car', 'Cargo Car', 21 | 'Flat Car', 'Tank car', 'Locomotive', 'Maritime Vessel', 'Motorboat', 'Sailboat', 'Tugboat', 'Barge', 22 | 'Fishing Vessel', 'Ferry', 'Yacht', 'Container Ship', 'Oil Tanker', 'Engineering Vehicle', 'Tower crane', 23 | 'Container Crane', 'Reach Stacker', 'Straddle Carrier', 'Mobile Crane', 'Dump Truck', 'Haul Truck', 24 | 'Scraper/Tractor', 'Front loader/Bulldozer', 'Excavator', 'Cement Mixer', 'Ground Grader', 'Hut/Tent', 'Shed', 25 | 'Building', 'Aircraft Hangar', 'Damaged Building', 'Facility', 'Construction Site', 'Vehicle Lot', 'Helipad', 26 | 'Storage Tank', 'Shipping container lot', 'Shipping Container', 'Pylon', 'Tower'] # class names 27 | 28 | 29 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 30 | download: | 31 | import json 32 | import os 33 | from pathlib import Path 34 | 35 | import numpy as np 36 | from PIL import Image 37 | from tqdm import tqdm 38 | 39 | from utils.datasets import autosplit 40 | from utils.general import download, xyxy2xywhn 41 | 42 | 43 | def convert_labels(fname=Path('xView/xView_train.geojson')): 44 | # Convert xView geoJSON labels to YOLO format 45 | path = fname.parent 46 | with open(fname) as f: 47 | print(f'Loading {fname}...') 48 | data = json.load(f) 49 | 50 | # Make dirs 51 | labels = Path(path / 'labels' / 'train') 52 | os.system(f'rm -rf {labels}') 53 | labels.mkdir(parents=True, exist_ok=True) 54 | 55 | # xView classes 11-94 to 0-59 56 | xview_class2index = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, -1, 9, 10, 11, 57 | 12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1, 58 | 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46, 59 | 47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59] 60 | 61 | shapes = {} 62 | for feature in tqdm(data['features'], desc=f'Converting {fname}'): 63 | p = feature['properties'] 64 | if p['bounds_imcoords']: 65 | id = p['image_id'] 66 | file = path / 'train_images' / id 67 | if file.exists(): # 1395.tif missing 68 | try: 69 | box = np.array([int(num) for num in p['bounds_imcoords'].split(",")]) 70 | assert box.shape[0] == 4, f'incorrect box shape {box.shape[0]}' 71 | cls = p['type_id'] 72 | cls = xview_class2index[int(cls)] # xView class to 0-60 73 | assert 59 >= cls >= 0, f'incorrect class index {cls}' 74 | 75 | # Write YOLO label 76 | if id not in shapes: 77 | shapes[id] = Image.open(file).size 78 | box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True) 79 | with open((labels / id).with_suffix('.txt'), 'a') as f: 80 | f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt 81 | except Exception as e: 82 | print(f'WARNING: skipping one label for {file}: {e}') 83 | 84 | 85 | # Download manually from https://challenge.xviewdataset.org 86 | dir = Path(yaml['path']) # dataset root dir 87 | # urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels 88 | # 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images 89 | # 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels) 90 | # download(urls, dir=dir, delete=False) 91 | 92 | # Convert labels 93 | convert_labels(dir / 'xView_train.geojson') 94 | 95 | # Move images 96 | images = Path(dir / 'images') 97 | images.mkdir(parents=True, exist_ok=True) 98 | Path(dir / 'train_images').rename(dir / 'images' / 'train') 99 | Path(dir / 'val_images').rename(dir / 'images' / 'val') 100 | 101 | # Split 102 | autosplit(dir / 'images' / 'train') 103 | -------------------------------------------------------------------------------- /models/experimental.py: -------------------------------------------------------------------------------- 1 | # YOLOv5 experimental modules 2 | 3 | import numpy as np 4 | import torch 5 | import torch.nn as nn 6 | 7 | from models.common import Conv, DWConv 8 | from utils.downloads 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().__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().__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().__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().__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 Depth-wise Conv https://arxiv.org/abs/1907.09595 76 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): 77 | super().__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().__init__() 102 | 103 | def forward(self, x, augment=False, profile=False, visualize=False): 104 | y = [] 105 | for module in self: 106 | y.append(module(x, augment, profile, visualize)[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, inplace=True): 114 | from models.yolo import Detect, Model 115 | 116 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a 117 | model = Ensemble() 118 | for w in weights if isinstance(weights, list) else [weights]: 119 | ckpt = torch.load(attempt_download(w), map_location=map_location) # load 120 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model 121 | 122 | # Compatibility updates 123 | for m in model.modules(): 124 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]: 125 | m.inplace = inplace # pytorch 1.7.0 compatibility 126 | elif type(m) is Conv: 127 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 128 | 129 | if len(model) == 1: 130 | return model[-1] # return model 131 | else: 132 | print(f'Ensemble created with {weights}\n') 133 | for k in ['names']: 134 | setattr(model, k, getattr(model[-1], k)) 135 | model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride 136 | return model # return ensemble 137 | -------------------------------------------------------------------------------- /hubconf.py: -------------------------------------------------------------------------------- 1 | """YOLOv5 PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/ 2 | 3 | Usage: 4 | import torch 5 | model = torch.hub.load('ultralytics/yolov5', 'yolov5s') 6 | """ 7 | 8 | import torch 9 | 10 | 11 | def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): 12 | """Creates a specified YOLOv5 model 13 | 14 | Arguments: 15 | name (str): name of model, i.e. 'yolov5s' 16 | pretrained (bool): load pretrained weights into the model 17 | channels (int): number of input channels 18 | classes (int): number of model classes 19 | autoshape (bool): apply YOLOv5 .autoshape() wrapper to model 20 | verbose (bool): print all information to screen 21 | device (str, torch.device, None): device to use for model parameters 22 | 23 | Returns: 24 | YOLOv5 pytorch model 25 | """ 26 | from pathlib import Path 27 | 28 | from models.yolo import Model, attempt_load 29 | from utils.general import check_requirements, set_logging 30 | from utils.downloads import attempt_download 31 | from utils.torch_utils import select_device 32 | 33 | file = Path(__file__).absolute() 34 | check_requirements(requirements=file.parent / 'requirements.txt', exclude=('tensorboard', 'thop', 'opencv-python')) 35 | set_logging(verbose=verbose) 36 | 37 | save_dir = Path('') if str(name).endswith('.pt') else file.parent 38 | path = (save_dir / name).with_suffix('.pt') # checkpoint path 39 | try: 40 | device = select_device(('0' if torch.cuda.is_available() else 'cpu') if device is None else device) 41 | 42 | if pretrained and channels == 3 and classes == 80: 43 | model = attempt_load(path, map_location=device) # download/load FP32 model 44 | else: 45 | cfg = list((Path(__file__).parent / 'models').rglob(f'{name}.yaml'))[0] # model.yaml path 46 | model = Model(cfg, channels, classes) # create model 47 | if pretrained: 48 | ckpt = torch.load(attempt_download(path), map_location=device) # load 49 | msd = model.state_dict() # model state_dict 50 | csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32 51 | csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter 52 | model.load_state_dict(csd, strict=False) # load 53 | if len(ckpt['model'].names) == classes: 54 | model.names = ckpt['model'].names # set class names attribute 55 | if autoshape: 56 | model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS 57 | return model.to(device) 58 | 59 | except Exception as e: 60 | help_url = 'https://github.com/ultralytics/yolov5/issues/36' 61 | s = 'Cache may be out of date, try `force_reload=True`. See %s for help.' % help_url 62 | raise Exception(s) from e 63 | 64 | 65 | def custom(path='path/to/model.pt', autoshape=True, verbose=True, device=None): 66 | # YOLOv5 custom or local model 67 | return _create(path, autoshape=autoshape, verbose=verbose, device=device) 68 | 69 | 70 | def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): 71 | # YOLOv5-small model https://github.com/ultralytics/yolov5 72 | return _create('yolov5s', pretrained, channels, classes, autoshape, verbose, device) 73 | 74 | 75 | def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): 76 | # YOLOv5-medium model https://github.com/ultralytics/yolov5 77 | return _create('yolov5m', pretrained, channels, classes, autoshape, verbose, device) 78 | 79 | 80 | def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): 81 | # YOLOv5-large model https://github.com/ultralytics/yolov5 82 | return _create('yolov5l', pretrained, channels, classes, autoshape, verbose, device) 83 | 84 | 85 | def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): 86 | # YOLOv5-xlarge model https://github.com/ultralytics/yolov5 87 | return _create('yolov5x', pretrained, channels, classes, autoshape, verbose, device) 88 | 89 | 90 | def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): 91 | # YOLOv5-small-P6 model https://github.com/ultralytics/yolov5 92 | return _create('yolov5s6', pretrained, channels, classes, autoshape, verbose, device) 93 | 94 | 95 | def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): 96 | # YOLOv5-medium-P6 model https://github.com/ultralytics/yolov5 97 | return _create('yolov5m6', pretrained, channels, classes, autoshape, verbose, device) 98 | 99 | 100 | def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): 101 | # YOLOv5-large-P6 model https://github.com/ultralytics/yolov5 102 | return _create('yolov5l6', pretrained, channels, classes, autoshape, verbose, device) 103 | 104 | 105 | def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): 106 | # YOLOv5-xlarge-P6 model https://github.com/ultralytics/yolov5 107 | return _create('yolov5x6', pretrained, channels, classes, autoshape, verbose, device) 108 | 109 | 110 | if __name__ == '__main__': 111 | model = _create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True, verbose=True) # pretrained 112 | # model = custom(path='path/to/model.pt') # custom 113 | 114 | # Verify inference 115 | import cv2 116 | import numpy as np 117 | from PIL import Image 118 | from pathlib import Path 119 | 120 | imgs = ['data/images/zidane.jpg', # filename 121 | Path('data/images/zidane.jpg'), # Path 122 | 'https://ultralytics.com/images/zidane.jpg', # URI 123 | cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV 124 | Image.open('data/images/bus.jpg'), # PIL 125 | np.zeros((320, 640, 3))] # numpy 126 | 127 | results = model(imgs) # batched inference 128 | results.print() 129 | results.save() 130 | -------------------------------------------------------------------------------- /utils/callbacks.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class Callbacks: 4 | """" 5 | Handles all registered callbacks for YOLOv5 Hooks 6 | """ 7 | 8 | _callbacks = { 9 | 'on_pretrain_routine_start': [], 10 | 'on_pretrain_routine_end': [], 11 | 12 | 'on_train_start': [], 13 | 'on_train_epoch_start': [], 14 | 'on_train_batch_start': [], 15 | 'optimizer_step': [], 16 | 'on_before_zero_grad': [], 17 | 'on_train_batch_end': [], 18 | 'on_train_epoch_end': [], 19 | 20 | 'on_val_start': [], 21 | 'on_val_batch_start': [], 22 | 'on_val_image_end': [], 23 | 'on_val_batch_end': [], 24 | 'on_val_end': [], 25 | 26 | 'on_fit_epoch_end': [], # fit = train + val 27 | 'on_model_save': [], 28 | 'on_train_end': [], 29 | 30 | 'teardown': [], 31 | } 32 | 33 | def __init__(self): 34 | return 35 | 36 | def register_action(self, hook, name='', callback=None): 37 | """ 38 | Register a new action to a callback hook 39 | 40 | Args: 41 | hook The callback hook name to register the action to 42 | name The name of the action 43 | callback The callback to fire 44 | """ 45 | assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}" 46 | assert callable(callback), f"callback '{callback}' is not callable" 47 | self._callbacks[hook].append({'name': name, 'callback': callback}) 48 | 49 | def get_registered_actions(self, hook=None): 50 | """" 51 | Returns all the registered actions by callback hook 52 | 53 | Args: 54 | hook The name of the hook to check, defaults to all 55 | """ 56 | if hook: 57 | return self._callbacks[hook] 58 | else: 59 | return self._callbacks 60 | 61 | def run_callbacks(self, hook, *args, **kwargs): 62 | """ 63 | Loop through the registered actions and fire all callbacks 64 | """ 65 | for logger in self._callbacks[hook]: 66 | # print(f"Running callbacks.{logger['callback'].__name__}()") 67 | logger['callback'](*args, **kwargs) 68 | 69 | def on_pretrain_routine_start(self, *args, **kwargs): 70 | """ 71 | Fires all registered callbacks at the start of each pretraining routine 72 | """ 73 | self.run_callbacks('on_pretrain_routine_start', *args, **kwargs) 74 | 75 | def on_pretrain_routine_end(self, *args, **kwargs): 76 | """ 77 | Fires all registered callbacks at the end of each pretraining routine 78 | """ 79 | self.run_callbacks('on_pretrain_routine_end', *args, **kwargs) 80 | 81 | def on_train_start(self, *args, **kwargs): 82 | """ 83 | Fires all registered callbacks at the start of each training 84 | """ 85 | self.run_callbacks('on_train_start', *args, **kwargs) 86 | 87 | def on_train_epoch_start(self, *args, **kwargs): 88 | """ 89 | Fires all registered callbacks at the start of each training epoch 90 | """ 91 | self.run_callbacks('on_train_epoch_start', *args, **kwargs) 92 | 93 | def on_train_batch_start(self, *args, **kwargs): 94 | """ 95 | Fires all registered callbacks at the start of each training batch 96 | """ 97 | self.run_callbacks('on_train_batch_start', *args, **kwargs) 98 | 99 | def optimizer_step(self, *args, **kwargs): 100 | """ 101 | Fires all registered callbacks on each optimizer step 102 | """ 103 | self.run_callbacks('optimizer_step', *args, **kwargs) 104 | 105 | def on_before_zero_grad(self, *args, **kwargs): 106 | """ 107 | Fires all registered callbacks before zero grad 108 | """ 109 | self.run_callbacks('on_before_zero_grad', *args, **kwargs) 110 | 111 | def on_train_batch_end(self, *args, **kwargs): 112 | """ 113 | Fires all registered callbacks at the end of each training batch 114 | """ 115 | self.run_callbacks('on_train_batch_end', *args, **kwargs) 116 | 117 | def on_train_epoch_end(self, *args, **kwargs): 118 | """ 119 | Fires all registered callbacks at the end of each training epoch 120 | """ 121 | self.run_callbacks('on_train_epoch_end', *args, **kwargs) 122 | 123 | def on_val_start(self, *args, **kwargs): 124 | """ 125 | Fires all registered callbacks at the start of the validation 126 | """ 127 | self.run_callbacks('on_val_start', *args, **kwargs) 128 | 129 | def on_val_batch_start(self, *args, **kwargs): 130 | """ 131 | Fires all registered callbacks at the start of each validation batch 132 | """ 133 | self.run_callbacks('on_val_batch_start', *args, **kwargs) 134 | 135 | def on_val_image_end(self, *args, **kwargs): 136 | """ 137 | Fires all registered callbacks at the end of each val image 138 | """ 139 | self.run_callbacks('on_val_image_end', *args, **kwargs) 140 | 141 | def on_val_batch_end(self, *args, **kwargs): 142 | """ 143 | Fires all registered callbacks at the end of each validation batch 144 | """ 145 | self.run_callbacks('on_val_batch_end', *args, **kwargs) 146 | 147 | def on_val_end(self, *args, **kwargs): 148 | """ 149 | Fires all registered callbacks at the end of the validation 150 | """ 151 | self.run_callbacks('on_val_end', *args, **kwargs) 152 | 153 | def on_fit_epoch_end(self, *args, **kwargs): 154 | """ 155 | Fires all registered callbacks at the end of each fit (train+val) epoch 156 | """ 157 | self.run_callbacks('on_fit_epoch_end', *args, **kwargs) 158 | 159 | def on_model_save(self, *args, **kwargs): 160 | """ 161 | Fires all registered callbacks after each model save 162 | """ 163 | self.run_callbacks('on_model_save', *args, **kwargs) 164 | 165 | def on_train_end(self, *args, **kwargs): 166 | """ 167 | Fires all registered callbacks at the end of training 168 | """ 169 | self.run_callbacks('on_train_end', *args, **kwargs) 170 | 171 | def teardown(self, *args, **kwargs): 172 | """ 173 | Fires all registered callbacks before teardown 174 | """ 175 | self.run_callbacks('teardown', *args, **kwargs) 176 | -------------------------------------------------------------------------------- /utils/downloads.py: -------------------------------------------------------------------------------- 1 | # Download utils 2 | 3 | import os 4 | import platform 5 | import subprocess 6 | import time 7 | import urllib 8 | from pathlib import Path 9 | 10 | import requests 11 | import torch 12 | 13 | 14 | def gsutil_getsize(url=''): 15 | # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du 16 | s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8') 17 | return eval(s.split(' ')[0]) if len(s) else 0 # bytes 18 | 19 | 20 | def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''): 21 | # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes 22 | file = Path(file) 23 | assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}" 24 | try: # url1 25 | print(f'Downloading {url} to {file}...') 26 | torch.hub.download_url_to_file(url, str(file)) 27 | assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check 28 | except Exception as e: # url2 29 | file.unlink(missing_ok=True) # remove partial downloads 30 | print(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...') 31 | os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail 32 | finally: 33 | if not file.exists() or file.stat().st_size < min_bytes: # check 34 | file.unlink(missing_ok=True) # remove partial downloads 35 | print(f"ERROR: {assert_msg}\n{error_msg}") 36 | print('') 37 | 38 | 39 | def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads import *; attempt_download() 40 | # Attempt file download if does not exist 41 | file = Path(str(file).strip().replace("'", '')) 42 | 43 | if not file.exists(): 44 | # URL specified 45 | name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc. 46 | if str(file).startswith(('http:/', 'https:/')): # download 47 | url = str(file).replace(':/', '://') # Pathlib turns :// -> :/ 48 | name = name.split('?')[0] # parse authentication https://url.com/file.txt?auth... 49 | safe_download(file=name, url=url, min_bytes=1E5) 50 | return name 51 | 52 | # GitHub assets 53 | file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required) 54 | try: 55 | response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api 56 | assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...] 57 | tag = response['tag_name'] # i.e. 'v1.0' 58 | except: # fallback plan 59 | assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 60 | 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] 61 | try: 62 | tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] 63 | except: 64 | tag = 'v5.0' # current release 65 | 66 | if name in assets: 67 | safe_download(file, 68 | url=f'https://github.com/{repo}/releases/download/{tag}/{name}', 69 | # url2=f'https://storage.googleapis.com/{repo}/ckpt/{name}', # backup url (optional) 70 | min_bytes=1E5, 71 | error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/') 72 | 73 | return str(file) 74 | 75 | 76 | def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'): 77 | # Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download() 78 | t = time.time() 79 | file = Path(file) 80 | cookie = Path('cookie') # gdrive cookie 81 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='') 82 | file.unlink(missing_ok=True) # remove existing file 83 | cookie.unlink(missing_ok=True) # remove existing cookie 84 | 85 | # Attempt file download 86 | out = "NUL" if platform.system() == "Windows" else "/dev/null" 87 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}') 88 | if os.path.exists('cookie'): # large file 89 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}' 90 | else: # small file 91 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"' 92 | r = os.system(s) # execute, capture return 93 | cookie.unlink(missing_ok=True) # remove existing cookie 94 | 95 | # Error check 96 | if r != 0: 97 | file.unlink(missing_ok=True) # remove partial 98 | print('Download error ') # raise Exception('Download error') 99 | return r 100 | 101 | # Unzip if archive 102 | if file.suffix == '.zip': 103 | print('unzipping... ', end='') 104 | os.system(f'unzip -q {file}') # unzip 105 | file.unlink() # remove zip to free space 106 | 107 | print(f'Done ({time.time() - t:.1f}s)') 108 | return r 109 | 110 | 111 | def get_token(cookie="./cookie"): 112 | with open(cookie) as f: 113 | for line in f: 114 | if "download" in line: 115 | return line.split()[-1] 116 | return "" 117 | 118 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries ---------------------------------------------- 119 | # 120 | # 121 | # def upload_blob(bucket_name, source_file_name, destination_blob_name): 122 | # # Uploads a file to a bucket 123 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python 124 | # 125 | # storage_client = storage.Client() 126 | # bucket = storage_client.get_bucket(bucket_name) 127 | # blob = bucket.blob(destination_blob_name) 128 | # 129 | # blob.upload_from_filename(source_file_name) 130 | # 131 | # print('File {} uploaded to {}.'.format( 132 | # source_file_name, 133 | # destination_blob_name)) 134 | # 135 | # 136 | # def download_blob(bucket_name, source_blob_name, destination_file_name): 137 | # # Uploads a blob from a bucket 138 | # storage_client = storage.Client() 139 | # bucket = storage_client.get_bucket(bucket_name) 140 | # blob = bucket.blob(source_blob_name) 141 | # 142 | # blob.download_to_filename(destination_file_name) 143 | # 144 | # print('Blob {} downloaded to {}.'.format( 145 | # source_blob_name, 146 | # destination_file_name)) 147 | -------------------------------------------------------------------------------- /utils/loggers/__init__.py: -------------------------------------------------------------------------------- 1 | # YOLOv5 experiment logging utils 2 | import warnings 3 | from threading import Thread 4 | 5 | import torch 6 | from torch.utils.tensorboard import SummaryWriter 7 | 8 | from utils.general import colorstr, emojis 9 | from utils.loggers.wandb.wandb_utils import WandbLogger 10 | from utils.plots import plot_images, plot_results 11 | from utils.torch_utils import de_parallel 12 | 13 | LOGGERS = ('csv', 'tb', 'wandb') # text-file, TensorBoard, Weights & Biases 14 | 15 | try: 16 | import wandb 17 | 18 | assert hasattr(wandb, '__version__') # verify package import not local dir 19 | except (ImportError, AssertionError): 20 | wandb = None 21 | 22 | 23 | class Loggers(): 24 | # YOLOv5 Loggers class 25 | def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS): 26 | self.save_dir = save_dir 27 | self.weights = weights 28 | self.opt = opt 29 | self.hyp = hyp 30 | self.logger = logger # for printing results to console 31 | self.include = include 32 | self.keys = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', 'train/angle_loss', # train loss 33 | 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', # metrics 34 | 'val/box_loss', 'val/obj_loss', 'val/cls_loss', 'val/angle_loss', # val loss 35 | 'x/lr0', 'x/lr1', 'x/lr2'] # params 36 | for k in LOGGERS: 37 | setattr(self, k, None) # init empty logger dictionary 38 | self.csv = True # always log to csv 39 | 40 | # Message 41 | if not wandb: 42 | prefix = colorstr('Weights & Biases: ') 43 | s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)" 44 | print(emojis(s)) 45 | 46 | # TensorBoard 47 | s = self.save_dir 48 | if 'tb' in self.include and not self.opt.evolve: 49 | prefix = colorstr('TensorBoard: ') 50 | self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/") 51 | self.tb = SummaryWriter(str(s)) 52 | 53 | # W&B 54 | if wandb and 'wandb' in self.include: 55 | wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://') 56 | run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None 57 | self.opt.hyp = self.hyp # add hyperparameters 58 | self.wandb = WandbLogger(self.opt, run_id) 59 | else: 60 | self.wandb = None 61 | 62 | def on_pretrain_routine_end(self): 63 | # Callback runs on pre-train routine end 64 | paths = self.save_dir.glob('*labels*.jpg') # training labels 65 | if self.wandb: 66 | self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]}) 67 | 68 | def on_train_batch_end(self, ni, model, imgs, targets, paths, plots): 69 | # Callback runs on train batch end 70 | if plots: 71 | if ni == 0: 72 | with warnings.catch_warnings(): 73 | warnings.simplefilter('ignore') # suppress jit trace warning 74 | self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), []) 75 | if ni < 20: 76 | f = self.save_dir / f'train_batch{ni}.jpg' # filename 77 | Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start() 78 | if self.wandb and ni == 10: 79 | files = sorted(self.save_dir.glob('train*.jpg')) 80 | self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]}) 81 | 82 | def on_train_epoch_end(self, epoch): 83 | # Callback runs on train epoch end 84 | if self.wandb: 85 | self.wandb.current_epoch = epoch + 1 86 | 87 | def on_val_image_end(self, pred, predn, path, names, im): 88 | # Callback runs on val image end 89 | if self.wandb: 90 | self.wandb.val_one_image(pred, predn, path, names, im) 91 | 92 | def on_val_end(self): 93 | # Callback runs on val end 94 | if self.wandb: 95 | files = sorted(self.save_dir.glob('val*.jpg')) 96 | self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]}) 97 | 98 | def on_fit_epoch_end(self, vals, epoch, best_fitness, fi): 99 | # Callback runs at the end of each fit (train+val) epoch 100 | x = {k: v for k, v in zip(self.keys, vals)} # dict 101 | if self.csv: 102 | file = self.save_dir / 'results.csv' 103 | n = len(x) + 1 # number of cols 104 | s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header 105 | with open(file, 'a') as f: 106 | f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n') 107 | 108 | if self.tb: 109 | for k, v in x.items(): 110 | self.tb.add_scalar(k, v, epoch) 111 | 112 | if self.wandb: 113 | self.wandb.log(x) 114 | self.wandb.end_epoch(best_result=best_fitness == fi) 115 | 116 | def on_model_save(self, last, epoch, final_epoch, best_fitness, fi): 117 | # Callback runs on model save event 118 | if self.wandb: 119 | if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1: 120 | self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi) 121 | 122 | def on_train_end(self, last, best, plots, epoch): 123 | # Callback runs on training end 124 | if plots: 125 | plot_results(file=self.save_dir / 'results.csv') # save results.png 126 | files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]] 127 | files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter 128 | 129 | if self.tb: 130 | from PIL import Image 131 | import numpy as np 132 | for f in files: 133 | self.tb.add_image(f.stem, np.asarray(Image.open(f)), epoch, dataformats='HWC') 134 | 135 | if self.wandb: 136 | self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]}) 137 | # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model 138 | wandb.log_artifact(str(best if best.exists() else last), type='model', 139 | name='run_' + self.wandb.wandb_run.id + '_model', 140 | aliases=['latest', 'best', 'stripped']) 141 | self.wandb.finish_run() 142 | -------------------------------------------------------------------------------- /data/Objects365.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # Objects365 dataset https://www.objects365.org/ 3 | # Example usage: python train.py --data Objects365.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── Objects365 ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/Objects365 # dataset root dir 12 | train: images/train # train images (relative to 'path') 1742289 images 13 | val: images/val # val images (relative to 'path') 5570 images 14 | test: # test images (optional) 15 | 16 | # Classes 17 | nc: 365 # number of classes 18 | names: ['Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup', 19 | 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book', 20 | 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag', 21 | 'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV', 22 | 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle', 23 | 'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird', 24 | 'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck', 25 | 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning', 26 | 'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife', 27 | 'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock', 28 | 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish', 29 | 'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan', 30 | 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard', 31 | 'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign', 32 | 'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat', 33 | 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard', 34 | 'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry', 35 | 'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks', 36 | 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors', 37 | 'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape', 38 | 'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck', 39 | 'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette', 40 | 'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket', 41 | 'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine', 42 | 'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine', 43 | 'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon', 44 | 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse', 45 | 'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball', 46 | 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin', 47 | 'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts', 48 | 'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit', 49 | 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD', 50 | 'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder', 51 | 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips', 52 | 'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab', 53 | 'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal', 54 | 'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart', 55 | 'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French', 56 | 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell', 57 | 'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil', 58 | 'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis'] 59 | 60 | 61 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 62 | download: | 63 | from pycocotools.coco import COCO 64 | from tqdm import tqdm 65 | 66 | from utils.general import download, Path 67 | 68 | # Make Directories 69 | dir = Path(yaml['path']) # dataset root dir 70 | for p in 'images', 'labels': 71 | (dir / p).mkdir(parents=True, exist_ok=True) 72 | for q in 'train', 'val': 73 | (dir / p / q).mkdir(parents=True, exist_ok=True) 74 | 75 | # Download 76 | url = "https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/train/" 77 | download([url + 'zhiyuan_objv2_train.tar.gz'], dir=dir, delete=False) # annotations json 78 | download([url + f for f in [f'patch{i}.tar.gz' for i in range(51)]], dir=dir / 'images' / 'train', 79 | curl=True, delete=False, threads=8) 80 | 81 | # Move 82 | train = dir / 'images' / 'train' 83 | for f in tqdm(train.rglob('*.jpg'), desc=f'Moving images'): 84 | f.rename(train / f.name) # move to /images/train 85 | 86 | # Labels 87 | coco = COCO(dir / 'zhiyuan_objv2_train.json') 88 | names = [x["name"] for x in coco.loadCats(coco.getCatIds())] 89 | for cid, cat in enumerate(names): 90 | catIds = coco.getCatIds(catNms=[cat]) 91 | imgIds = coco.getImgIds(catIds=catIds) 92 | for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'): 93 | width, height = im["width"], im["height"] 94 | path = Path(im["file_name"]) # image filename 95 | try: 96 | with open(dir / 'labels' / 'train' / path.with_suffix('.txt').name, 'a') as file: 97 | annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None) 98 | for a in coco.loadAnns(annIds): 99 | x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner) 100 | x, y = x + w / 2, y + h / 2 # xy to center 101 | file.write(f"{cid} {x / width:.5f} {y / height:.5f} {w / width:.5f} {h / height:.5f}\n") 102 | 103 | except Exception as e: 104 | print(e) 105 | -------------------------------------------------------------------------------- /utils/autoanchor.py: -------------------------------------------------------------------------------- 1 | # Auto-anchor utils 2 | 3 | import random 4 | 5 | import numpy as np 6 | import torch 7 | import yaml 8 | from tqdm import tqdm 9 | 10 | from utils.general import colorstr 11 | 12 | 13 | def check_anchor_order(m): 14 | # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary 15 | a = m.anchor_grid.prod(-1).view(-1) # anchor area 16 | da = a[-1] - a[0] # delta a 17 | ds = m.stride[-1] - m.stride[0] # delta s 18 | if da.sign() != ds.sign(): # same order 19 | print('Reversing anchor order') 20 | m.anchors[:] = m.anchors.flip(0) 21 | m.anchor_grid[:] = m.anchor_grid.flip(0) 22 | 23 | 24 | def check_anchors(dataset, model, thr=4.0, imgsz=640): 25 | # Check anchor fit to data, recompute if necessary 26 | prefix = colorstr('autoanchor: ') 27 | print(f'\n{prefix}Analyzing anchors... ', end='') 28 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() 29 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) 30 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale 31 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh 32 | 33 | def metric(k): # compute metric 34 | r = wh[:, None] / k[None] 35 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric 36 | best = x.max(1)[0] # best_x 37 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold 38 | bpr = (best > 1. / thr).float().mean() # best possible recall 39 | return bpr, aat 40 | 41 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors 42 | bpr, aat = metric(anchors) 43 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='') 44 | if bpr < 0.98: # threshold to recompute 45 | print('. Attempting to improve anchors, please wait...') 46 | na = m.anchor_grid.numel() // 2 # number of anchors 47 | try: 48 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) 49 | except Exception as e: 50 | print(f'{prefix}ERROR: {e}') 51 | new_bpr = metric(anchors)[0] 52 | if new_bpr > bpr: # replace anchors 53 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors) 54 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference 55 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss 56 | check_anchor_order(m) 57 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.') 58 | else: 59 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.') 60 | print('') # newline 61 | 62 | 63 | def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): 64 | """ Creates kmeans-evolved anchors from training dataset 65 | 66 | Arguments: 67 | dataset: path to data.yaml, or a loaded dataset 68 | n: number of anchors 69 | img_size: image size used for training 70 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 71 | gen: generations to evolve anchors using genetic algorithm 72 | verbose: print all results 73 | 74 | Return: 75 | k: kmeans evolved anchors 76 | 77 | Usage: 78 | from utils.autoanchor import *; _ = kmean_anchors() 79 | """ 80 | from scipy.cluster.vq import kmeans 81 | 82 | thr = 1. / thr 83 | prefix = colorstr('autoanchor: ') 84 | 85 | def metric(k, wh): # compute metrics 86 | r = wh[:, None] / k[None] 87 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric 88 | # x = wh_iou(wh, torch.tensor(k)) # iou metric 89 | return x, x.max(1)[0] # x, best_x 90 | 91 | def anchor_fitness(k): # mutation fitness 92 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh) 93 | return (best * (best > thr).float()).mean() # fitness 94 | 95 | def print_results(k): 96 | k = k[np.argsort(k.prod(1))] # sort small to large 97 | x, best = metric(k, wh0) 98 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr 99 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr') 100 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' 101 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='') 102 | for i, x in enumerate(k): 103 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg 104 | return k 105 | 106 | if isinstance(dataset, str): # *.yaml file 107 | with open(dataset, encoding='ascii', errors='ignore') as f: 108 | data_dict = yaml.safe_load(f) # model dict 109 | from utils.datasets import LoadImagesAndLabels 110 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) 111 | 112 | # Get label wh 113 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) 114 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh 115 | 116 | # Filter 117 | i = (wh0 < 3.0).any(1).sum() 118 | if i: 119 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.') 120 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels 121 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 122 | 123 | # Kmeans calculation 124 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...') 125 | s = wh.std(0) # sigmas for whitening 126 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance 127 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}') 128 | k *= s 129 | wh = torch.tensor(wh, dtype=torch.float32) # filtered 130 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered 131 | k = print_results(k) 132 | 133 | # Plot 134 | # k, d = [None] * 20, [None] * 20 135 | # for i in tqdm(range(1, 21)): 136 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance 137 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) 138 | # ax = ax.ravel() 139 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') 140 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh 141 | # ax[0].hist(wh[wh[:, 0]<100, 0],400) 142 | # ax[1].hist(wh[wh[:, 1]<100, 1],400) 143 | # fig.savefig('wh.png', dpi=200) 144 | 145 | # Evolve 146 | npr = np.random 147 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma 148 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar 149 | for _ in pbar: 150 | v = np.ones(sh) 151 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates) 152 | v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) 153 | kg = (k.copy() * v).clip(min=2.0) 154 | fg = anchor_fitness(kg) 155 | if fg > f: 156 | f, k = fg, kg.copy() 157 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' 158 | if verbose: 159 | print_results(k) 160 | 161 | return print_results(k) 162 | -------------------------------------------------------------------------------- /export.py: -------------------------------------------------------------------------------- 1 | """Export a YOLOv5 *.pt model to TorchScript, ONNX, CoreML formats 2 | 3 | Usage: 4 | $ python path/to/export.py --weights yolov5s.pt --img 640 --batch 1 5 | """ 6 | 7 | import argparse 8 | import sys 9 | import time 10 | from pathlib import Path 11 | 12 | import torch 13 | import torch.nn as nn 14 | from torch.utils.mobile_optimizer import optimize_for_mobile 15 | 16 | FILE = Path(__file__).absolute() 17 | sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path 18 | 19 | from models.common import Conv 20 | from models.yolo import Detect 21 | from models.experimental import attempt_load 22 | from utils.activations import Hardswish, SiLU 23 | from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging 24 | from utils.torch_utils import select_device 25 | 26 | 27 | def export_torchscript(model, img, file, optimize): 28 | # TorchScript model export 29 | prefix = colorstr('TorchScript:') 30 | try: 31 | print(f'\n{prefix} starting export with torch {torch.__version__}...') 32 | f = file.with_suffix('.torchscript.pt') 33 | ts = torch.jit.trace(model, img, strict=False) 34 | (optimize_for_mobile(ts) if optimize else ts).save(f) 35 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 36 | return ts 37 | except Exception as e: 38 | print(f'{prefix} export failure: {e}') 39 | 40 | 41 | def export_onnx(model, img, file, opset, train, dynamic, simplify): 42 | # ONNX model export 43 | prefix = colorstr('ONNX:') 44 | try: 45 | check_requirements(('onnx', 'onnx-simplifier')) 46 | import onnx 47 | 48 | print(f'\n{prefix} starting export with onnx {onnx.__version__}...') 49 | f = file.with_suffix('.onnx') 50 | torch.onnx.export(model, img, f, verbose=False, opset_version=opset, 51 | training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL, 52 | do_constant_folding=not train, 53 | input_names=['images'], 54 | output_names=['output'], 55 | dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640) 56 | 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85) 57 | } if dynamic else None) 58 | 59 | # Checks 60 | model_onnx = onnx.load(f) # load onnx model 61 | onnx.checker.check_model(model_onnx) # check onnx model 62 | # print(onnx.helper.printable_graph(model_onnx.graph)) # print 63 | 64 | # Simplify 65 | if simplify: 66 | try: 67 | import onnxsim 68 | 69 | print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...') 70 | model_onnx, check = onnxsim.simplify( 71 | model_onnx, 72 | dynamic_input_shape=dynamic, 73 | input_shapes={'images': list(img.shape)} if dynamic else None) 74 | assert check, 'assert check failed' 75 | onnx.save(model_onnx, f) 76 | except Exception as e: 77 | print(f'{prefix} simplifier failure: {e}') 78 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 79 | print(f"{prefix} run --dynamic ONNX model inference with detect.py: 'python detect.py --weights {f}'") 80 | except Exception as e: 81 | print(f'{prefix} export failure: {e}') 82 | 83 | 84 | def export_coreml(model, img, file): 85 | # CoreML model export 86 | prefix = colorstr('CoreML:') 87 | try: 88 | import coremltools as ct 89 | 90 | print(f'\n{prefix} starting export with coremltools {ct.__version__}...') 91 | f = file.with_suffix('.mlmodel') 92 | model.train() # CoreML exports should be placed in model.train() mode 93 | ts = torch.jit.trace(model, img, strict=False) # TorchScript model 94 | model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])]) 95 | model.save(f) 96 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 97 | except Exception as e: 98 | print(f'\n{prefix} export failure: {e}') 99 | 100 | 101 | def run(weights='./yolov5s.pt', # weights path 102 | img_size=(640, 640), # image (height, width) 103 | batch_size=1, # batch size 104 | device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu 105 | include=('torchscript', 'onnx', 'coreml'), # include formats 106 | half=False, # FP16 half-precision export 107 | inplace=False, # set YOLOv5 Detect() inplace=True 108 | train=False, # model.train() mode 109 | optimize=False, # TorchScript: optimize for mobile 110 | dynamic=False, # ONNX: dynamic axes 111 | simplify=False, # ONNX: simplify model 112 | opset=12, # ONNX: opset version 113 | ): 114 | t = time.time() 115 | include = [x.lower() for x in include] 116 | img_size *= 2 if len(img_size) == 1 else 1 # expand 117 | file = Path(weights) 118 | 119 | # Load PyTorch model 120 | device = select_device(device) 121 | assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0' 122 | model = attempt_load(weights, map_location=device) # load FP32 model 123 | names = model.names 124 | 125 | # Input 126 | gs = int(max(model.stride)) # grid size (max stride) 127 | img_size = [check_img_size(x, gs) for x in img_size] # verify img_size are gs-multiples 128 | img = torch.zeros(batch_size, 3, *img_size).to(device) # image size(1,3,320,192) iDetection 129 | 130 | # Update model 131 | if half: 132 | img, model = img.half(), model.half() # to FP16 133 | model.train() if train else model.eval() # training mode = no Detect() layer grid construction 134 | for k, m in model.named_modules(): 135 | if isinstance(m, Conv): # assign export-friendly activations 136 | if isinstance(m.act, nn.Hardswish): 137 | m.act = Hardswish() 138 | elif isinstance(m.act, nn.SiLU): 139 | m.act = SiLU() 140 | elif isinstance(m, Detect): 141 | m.inplace = inplace 142 | m.onnx_dynamic = dynamic 143 | # m.forward = m.forward_export # assign forward (optional) 144 | 145 | for _ in range(2): 146 | y = model(img) # dry runs 147 | print(f"\n{colorstr('PyTorch:')} starting from {weights} ({file_size(weights):.1f} MB)") 148 | 149 | # Exports 150 | if 'torchscript' in include: 151 | export_torchscript(model, img, file, optimize) 152 | if 'onnx' in include: 153 | export_onnx(model, img, file, opset, train, dynamic, simplify) 154 | if 'coreml' in include: 155 | export_coreml(model, img, file) 156 | 157 | # Finish 158 | print(f'\nExport complete ({time.time() - t:.2f}s)' 159 | f"\nResults saved to {colorstr('bold', file.parent.resolve())}" 160 | f'\nVisualize with https://netron.app') 161 | 162 | 163 | def parse_opt(): 164 | parser = argparse.ArgumentParser() 165 | parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path') 166 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image (height, width)') 167 | parser.add_argument('--batch-size', type=int, default=1, help='batch size') 168 | parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 169 | parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats') 170 | parser.add_argument('--half', action='store_true', help='FP16 half-precision export') 171 | parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True') 172 | parser.add_argument('--train', action='store_true', help='model.train() mode') 173 | parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile') 174 | parser.add_argument('--dynamic', action='store_true', help='ONNX: dynamic axes') 175 | parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model') 176 | parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version') 177 | opt = parser.parse_args() 178 | return opt 179 | 180 | 181 | def main(opt): 182 | set_logging() 183 | print(colorstr('export: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) 184 | run(**vars(opt)) 185 | 186 | 187 | if __name__ == "__main__": 188 | opt = parse_opt() 189 | main(opt) 190 | -------------------------------------------------------------------------------- /utils/loggers/wandb/README.md: -------------------------------------------------------------------------------- 1 | 📚 This guide explains how to use **Weights & Biases** (W&B) with YOLOv5 🚀. 2 | * [About Weights & Biases](#about-weights-&-biases) 3 | * [First-Time Setup](#first-time-setup) 4 | * [Viewing runs](#viewing-runs) 5 | * [Advanced Usage: Dataset Versioning and Evaluation](#advanced-usage) 6 | * [Reports: Share your work with the world!](#reports) 7 | 8 | ## About Weights & Biases 9 | Think of [W&B](https://wandb.ai/site?utm_campaign=repo_yolo_wandbtutorial) like GitHub for machine learning models. With a few lines of code, save everything you need to debug, compare and reproduce your models — architecture, hyperparameters, git commits, model weights, GPU usage, and even datasets and predictions. 10 | 11 | Used by top researchers including teams at OpenAI, Lyft, Github, and MILA, W&B is part of the new standard of best practices for machine learning. How W&B can help you optimize your machine learning workflows: 12 | 13 | * [Debug](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Free-2) model performance in real time 14 | * [GPU usage](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#System-4), visualized automatically 15 | * [Custom charts](https://wandb.ai/wandb/customizable-charts/reports/Powerful-Custom-Charts-To-Debug-Model-Peformance--VmlldzoyNzY4ODI) for powerful, extensible visualization 16 | * [Share insights](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Share-8) interactively with collaborators 17 | * [Optimize hyperparameters](https://docs.wandb.com/sweeps) efficiently 18 | * [Track](https://docs.wandb.com/artifacts) datasets, pipelines, and production models 19 | 20 | ## First-Time Setup 21 |
22 | Toggle Details 23 | When you first train, W&B will prompt you to create a new account and will generate an **API key** for you. If you are an existing user you can retrieve your key from https://wandb.ai/authorize. This key is used to tell W&B where to log your data. You only need to supply your key once, and then it is remembered on the same device. 24 | 25 | W&B will create a cloud **project** (default is 'YOLOv5') for your training runs, and each new training run will be provided a unique run **name** within that project as project/name. You can also manually set your project and run name as: 26 | 27 | ```shell 28 | $ python train.py --project ... --name ... 29 | ``` 30 | 31 | 32 |
33 | 34 | ## Viewing Runs 35 |
36 | Toggle Details 37 | Run information streams from your environment to the W&B cloud console as you train. This allows you to monitor and even cancel runs in realtime . All important information is logged: 38 | 39 | * Training & Validation losses 40 | * Metrics: Precision, Recall, mAP@0.5, mAP@0.5:0.95 41 | * Learning Rate over time 42 | * A bounding box debugging panel, showing the training progress over time 43 | * GPU: Type, **GPU Utilization**, power, temperature, **CUDA memory usage** 44 | * System: Disk I/0, CPU utilization, RAM memory usage 45 | * Your trained model as W&B Artifact 46 | * Environment: OS and Python types, Git repository and state, **training command** 47 | 48 | 49 |
50 | 51 | ## Advanced Usage 52 | You can leverage W&B artifacts and Tables integration to easily visualize and manage your datasets, models and training evaluations. Here are some quick examples to get you started. 53 |
54 |

1. Visualize and Version Datasets

55 | Log, visualize, dynamically query, and understand your data with W&B Tables. You can use the following command to log your dataset as a W&B Table. This will generate a {dataset}_wandb.yaml file which can be used to train from dataset artifact. 56 |
57 | Usage 58 | Code $ python utils/logger/wandb/log_dataset.py --project ... --name ... --data .. 59 | 60 | ![Screenshot (64)](https://user-images.githubusercontent.com/15766192/128486078-d8433890-98a3-4d12-8986-b6c0e3fc64b9.png) 61 |
62 | 63 |

2: Train and Log Evaluation simultaneousy

64 | This is an extension of the previous section, but it'll also training after uploading the dataset. This also evaluation Table 65 | Evaluation table compares your predictions and ground truths across the validation set for each epoch. It uses the references to the already uploaded datasets, 66 | so no images will be uploaded from your system more than once. 67 |
68 | Usage 69 | Code $ python utils/logger/wandb/log_dataset.py --data .. --upload_data 70 | 71 | ![Screenshot (72)](https://user-images.githubusercontent.com/15766192/128979739-4cf63aeb-a76f-483f-8861-1c0100b938a5.png) 72 |
73 | 74 |

3: Train using dataset artifact

75 | When you upload a dataset as described in the first section, you get a new config file with an added `_wandb` to its name. This file contains the information that 76 | can be used to train a model directly from the dataset artifact. This also logs evaluation 77 |
78 | Usage 79 | Code $ python utils/logger/wandb/log_dataset.py --data {data}_wandb.yaml 80 | 81 | ![Screenshot (72)](https://user-images.githubusercontent.com/15766192/128979739-4cf63aeb-a76f-483f-8861-1c0100b938a5.png) 82 |
83 | 84 |

4: Save model checkpoints as artifacts

85 | To enable saving and versioning checkpoints of your experiment, pass `--save_period n` with the base cammand, where `n` represents checkpoint interval. 86 | You can also log both the dataset and model checkpoints simultaneously. If not passed, only the final model will be logged 87 | 88 |
89 | Usage 90 | Code $ python train.py --save_period 1 91 | 92 | ![Screenshot (68)](https://user-images.githubusercontent.com/15766192/128726138-ec6c1f60-639d-437d-b4ee-3acd9de47ef3.png) 93 |
94 | 95 |
96 | 97 |

5: Resume runs from checkpoint artifacts.

98 | Any run can be resumed using artifacts if the --resume argument starts with wandb-artifact:// prefix followed by the run path, i.e, wandb-artifact://username/project/runid . This doesn't require the model checkpoint to be present on the local system. 99 | 100 |
101 | Usage 102 | Code $ python train.py --resume wandb-artifact://{run_path} 103 | 104 | ![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png) 105 |
106 | 107 |

6: Resume runs from dataset artifact & checkpoint artifacts.

108 | Local dataset or model checkpoints are not required. This can be used to resume runs directly on a different device 109 | The syntax is same as the previous section, but you'll need to lof both the dataset and model checkpoints as artifacts, i.e, set bot --upload_dataset or 110 | train from _wandb.yaml file and set --save_period 111 | 112 |
113 | Usage 114 | Code $ python train.py --resume wandb-artifact://{run_path} 115 | 116 | ![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png) 117 |
118 | 119 | 120 | 121 | 122 | 123 |

Reports

124 | W&B Reports can be created from your saved runs for sharing online. Once a report is created you will receive a link you can use to publically share your results. Here is an example report created from the COCO128 tutorial trainings of all four YOLOv5 models ([link](https://wandb.ai/glenn-jocher/yolov5_tutorial/reports/YOLOv5-COCO128-Tutorial-Results--VmlldzozMDI5OTY)). 125 | 126 | 127 | 128 | ## Environments 129 | YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled): 130 | 131 | * **Google Colab and Kaggle** notebooks with free GPU: [![Open In Colab](https://camo.githubusercontent.com/84f0493939e0c4de4e6dbe113251b4bfb5353e57134ffd9fcab6b8714514d4d1/68747470733a2f2f636f6c61622e72657365617263682e676f6f676c652e636f6d2f6173736574732f636f6c61622d62616467652e737667)](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb) [![Open In Kaggle](https://camo.githubusercontent.com/a08ca511178e691ace596a95d334f73cf4ce06e83a5c4a5169b8bb68cac27bef/68747470733a2f2f6b6167676c652e636f6d2f7374617469632f696d616765732f6f70656e2d696e2d6b6167676c652e737667)](https://www.kaggle.com/ultralytics/yolov5) 132 | * **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) 133 | * **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart) 134 | * **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) [![Docker Pulls](https://camo.githubusercontent.com/280faedaf431e4c0c24fdb30ec00a66d627404e5c4c498210d3f014dd58c2c7e/68747470733a2f2f696d672e736869656c64732e696f2f646f636b65722f70756c6c732f756c7472616c79746963732f796f6c6f76353f6c6f676f3d646f636b6572)](https://hub.docker.com/r/ultralytics/yolov5) 135 | 136 | ## Status 137 | ![CI CPU testing](https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg) 138 | 139 | If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), validation ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on MacOS, Windows, and Ubuntu every 24 hours and on every commit. 140 | 141 | -------------------------------------------------------------------------------- /detect.py: -------------------------------------------------------------------------------- 1 | """Run inference with a YOLOv5 model on images, videos, directories, streams 2 | 3 | Usage: 4 | $ python path/to/detect.py --source path/to/img.jpg --weights yolov5s.pt --img 640 5 | """ 6 | 7 | import argparse 8 | import sys 9 | import time 10 | from pathlib import Path 11 | 12 | import cv2 13 | import torch 14 | import torch.backends.cudnn as cudnn 15 | 16 | FILE = Path(__file__).absolute() 17 | sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path 18 | 19 | from models.experimental import attempt_load 20 | from utils.datasets import LoadStreams, LoadImages 21 | from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \ 22 | apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box 23 | from utils.plots import colors, plot_one_box 24 | from utils.torch_utils import select_device, load_classifier, time_sync 25 | 26 | 27 | @torch.no_grad() 28 | def run(weights='yolov5s.pt', # model.pt path(s) 29 | source='data/images', # file/dir/URL/glob, 0 for webcam 30 | imgsz=640, # inference size (pixels) 31 | conf_thres=0.25, # confidence threshold 32 | iou_thres=0.45, # NMS IOU threshold 33 | max_det=1000, # maximum detections per image 34 | device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu 35 | view_img=False, # show results 36 | save_txt=False, # save results to *.txt 37 | save_conf=False, # save confidences in --save-txt labels 38 | save_crop=False, # save cropped prediction boxes 39 | nosave=False, # do not save images/videos 40 | classes=None, # filter by class: --class 0, or --class 0 2 3 41 | agnostic_nms=False, # class-agnostic NMS 42 | augment=False, # augmented inference 43 | visualize=False, # visualize features 44 | update=False, # update all models 45 | project='runs/detect', # save results to project/name 46 | name='exp', # save results to project/name 47 | exist_ok=False, # existing project/name ok, do not increment 48 | line_thickness=3, # bounding box thickness (pixels) 49 | hide_labels=False, # hide labels 50 | hide_conf=False, # hide confidences 51 | half=False, # use FP16 half-precision inference 52 | ): 53 | save_img = not nosave and not source.endswith('.txt') # save inference images 54 | webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith( 55 | ('rtsp://', 'rtmp://', 'http://', 'https://')) 56 | 57 | # Directories 58 | save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run 59 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir 60 | 61 | # Initialize 62 | set_logging() 63 | device = select_device(device) 64 | half &= device.type != 'cpu' # half precision only supported on CUDA 65 | 66 | # Load model 67 | w = weights[0] if isinstance(weights, list) else weights 68 | classify, pt, onnx = False, w.endswith('.pt'), w.endswith('.onnx') # inference type 69 | stride, names = 64, [f'class{i}' for i in range(1000)] # assign defaults 70 | if pt: 71 | model = attempt_load(weights, map_location=device) # load FP32 model 72 | stride = int(model.stride.max()) # model stride 73 | names = model.module.names if hasattr(model, 'module') else model.names # get class names 74 | if half: 75 | model.half() # to FP16 76 | if classify: # second-stage classifier 77 | modelc = load_classifier(name='resnet50', n=2) # initialize 78 | modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval() 79 | elif onnx: 80 | check_requirements(('onnx', 'onnxruntime')) 81 | import onnxruntime 82 | session = onnxruntime.InferenceSession(w, None) 83 | imgsz = check_img_size(imgsz, s=stride) # check image size 84 | 85 | # Dataloader 86 | if webcam: 87 | view_img = check_imshow() 88 | cudnn.benchmark = True # set True to speed up constant image size inference 89 | dataset = LoadStreams(source, img_size=imgsz, stride=stride) 90 | bs = len(dataset) # batch_size 91 | else: 92 | dataset = LoadImages(source, img_size=imgsz, stride=stride) 93 | bs = 1 # batch_size 94 | vid_path, vid_writer = [None] * bs, [None] * bs 95 | 96 | # Run inference 97 | if pt and device.type != 'cpu': 98 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once 99 | t0 = time.time() 100 | for path, img, im0s, vid_cap in dataset: 101 | if pt: 102 | img = torch.from_numpy(img).to(device) 103 | img = img.half() if half else img.float() # uint8 to fp16/32 104 | elif onnx: 105 | img = img.astype('float32') 106 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 107 | if len(img.shape) == 3: 108 | img = img[None] # expand for batch dim 109 | 110 | # Inference 111 | t1 = time_sync() 112 | if pt: 113 | visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False 114 | pred = model(img, augment=augment, visualize=visualize)[0] 115 | elif onnx: 116 | pred = torch.tensor(session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: img})) 117 | 118 | # NMS 119 | pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) 120 | t2 = time_sync() 121 | 122 | # Second-stage classifier (optional) 123 | if classify: 124 | pred = apply_classifier(pred, modelc, img, im0s) 125 | 126 | # Process predictions 127 | for i, det in enumerate(pred): # detections per image 128 | if webcam: # batch_size >= 1 129 | p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count 130 | else: 131 | p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0) 132 | 133 | p = Path(p) # to Path 134 | save_path = str(save_dir / p.name) # img.jpg 135 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt 136 | s += '%gx%g ' % img.shape[2:] # print string 137 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh 138 | imc = im0.copy() if save_crop else im0 # for save_crop 139 | if len(det): 140 | # Rescale boxes from img_size to im0 size 141 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 142 | 143 | # Print results 144 | for c in det[:, -2].unique(): 145 | n = (det[:, -2] == c).sum() # detections per class 146 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string 147 | 148 | # Write results 149 | for *xyxy, conf, cls, angle in reversed(det): 150 | if save_txt: # Write to file 151 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 152 | line = (cls, *xywh, conf, angle) if save_conf else (cls, *xywh, angle) # label format 153 | with open(txt_path + '.txt', 'a') as f: 154 | f.write(('%g ' * len(line)).rstrip() % line + '\n') 155 | 156 | if save_img or save_crop or view_img: # Add bbox to image 157 | c = int(cls) # integer class 158 | label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') 159 | plot_one_box(xyxy, angle, im0, label=label, color=colors(c, True), line_thickness=line_thickness) 160 | if save_crop: 161 | save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) 162 | 163 | # Print time (inference + NMS) 164 | print(f'{s}Done. ({t2 - t1:.3f}s)') 165 | 166 | # Stream results 167 | if view_img: 168 | cv2.imshow(str(p), im0) 169 | cv2.waitKey(1) # 1 millisecond 170 | 171 | # Save results (image with detections) 172 | if save_img: 173 | if dataset.mode == 'image': 174 | cv2.imwrite(save_path, im0) 175 | else: # 'video' or 'stream' 176 | if vid_path[i] != save_path: # new video 177 | vid_path[i] = save_path 178 | if isinstance(vid_writer[i], cv2.VideoWriter): 179 | vid_writer[i].release() # release previous video writer 180 | if vid_cap: # video 181 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 182 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 183 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 184 | else: # stream 185 | fps, w, h = 30, im0.shape[1], im0.shape[0] 186 | save_path += '.mp4' 187 | vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) 188 | vid_writer[i].write(im0) 189 | 190 | if save_txt or save_img: 191 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' 192 | print(f"Results saved to {colorstr('bold', save_dir)}{s}") 193 | 194 | if update: 195 | strip_optimizer(weights) # update model (to fix SourceChangeWarning) 196 | 197 | print(f'Done. ({time.time() - t0:.3f}s)') 198 | 199 | 200 | def parse_opt(): 201 | parser = argparse.ArgumentParser() 202 | parser.add_argument('--weights', nargs='+', type=str, default='./runs/train/exp3/weights/best.pt', help='model.pt path(s)') 203 | parser.add_argument('--source', type=str, default='/data/dataset/dataset_download/val/jueyuanzi_fangzhenchui/', help='file/dir/URL/glob, 0 for webcam')#/data/dataset/dataset_download/val/img_640 204 | parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') 205 | parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold') 206 | parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold') 207 | parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image') 208 | parser.add_argument('--device', default='4', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 209 | parser.add_argument('--view-img', action='store_true', help='show results') 210 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 211 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') 212 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes') 213 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos') 214 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') 215 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 216 | parser.add_argument('--augment', action='store_true', help='augmented inference') 217 | parser.add_argument('--visualize', action='store_true', help='visualize features') 218 | parser.add_argument('--update', action='store_true', help='update all models') 219 | parser.add_argument('--project', default='runs/detect', help='save results to project/name') 220 | parser.add_argument('--name', default='exp', help='save results to project/name') 221 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') 222 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') 223 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') 224 | parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') 225 | parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') 226 | opt = parser.parse_args() 227 | return opt 228 | 229 | 230 | def main(opt): 231 | print(colorstr('detect: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) 232 | check_requirements(exclude=('tensorboard', 'thop')) 233 | run(**vars(opt)) 234 | 235 | 236 | if __name__ == "__main__": 237 | opt = parse_opt() 238 | main(opt) 239 | -------------------------------------------------------------------------------- /utils/loss.py: -------------------------------------------------------------------------------- 1 | # Loss functions 2 | 3 | import torch 4 | import torch.nn as nn 5 | import numpy as np 6 | import math 7 | 8 | from utils.metrics import bbox_iou 9 | from utils.torch_utils import is_parallel 10 | 11 | 12 | def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441 13 | # return positive, negative label smoothing BCE targets 14 | return 1.0 - 0.5 * eps, 0.5 * eps 15 | 16 | 17 | class BCEBlurWithLogitsLoss(nn.Module): 18 | # BCEwithLogitLoss() with reduced missing label effects. 19 | def __init__(self, alpha=0.05): 20 | super(BCEBlurWithLogitsLoss, self).__init__() 21 | self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss() 22 | self.alpha = alpha 23 | 24 | def forward(self, pred, true): 25 | loss = self.loss_fcn(pred, true) 26 | pred = torch.sigmoid(pred) # prob from logits 27 | dx = pred - true # reduce only missing label effects 28 | # dx = (pred - true).abs() # reduce missing label and false label effects 29 | alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4)) 30 | loss *= alpha_factor 31 | return loss.mean() 32 | 33 | 34 | class FocalLoss(nn.Module): 35 | # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) 36 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): 37 | super(FocalLoss, self).__init__() 38 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() 39 | self.gamma = gamma 40 | self.alpha = alpha 41 | self.reduction = loss_fcn.reduction 42 | self.loss_fcn.reduction = 'none' # required to apply FL to each element 43 | 44 | def forward(self, pred, true): 45 | loss = self.loss_fcn(pred, true) 46 | # p_t = torch.exp(-loss) 47 | # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability 48 | 49 | # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py 50 | pred_prob = torch.sigmoid(pred) # prob from logits 51 | p_t = true * pred_prob + (1 - true) * (1 - pred_prob) 52 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) 53 | modulating_factor = (1.0 - p_t) ** self.gamma 54 | loss *= alpha_factor * modulating_factor 55 | 56 | if self.reduction == 'mean': 57 | return loss.mean() 58 | elif self.reduction == 'sum': 59 | return loss.sum() 60 | else: # 'none' 61 | return loss 62 | 63 | 64 | class QFocalLoss(nn.Module): 65 | # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) 66 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): 67 | super(QFocalLoss, self).__init__() 68 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() 69 | self.gamma = gamma 70 | self.alpha = alpha 71 | self.reduction = loss_fcn.reduction 72 | self.loss_fcn.reduction = 'none' # required to apply FL to each element 73 | 74 | def forward(self, pred, true): 75 | loss = self.loss_fcn(pred, true) 76 | 77 | pred_prob = torch.sigmoid(pred) # prob from logits 78 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) 79 | modulating_factor = torch.abs(true - pred_prob) ** self.gamma 80 | loss *= alpha_factor * modulating_factor 81 | 82 | if self.reduction == 'mean': 83 | return loss.mean() 84 | elif self.reduction == 'sum': 85 | return loss.sum() 86 | else: # 'none' 87 | return loss 88 | 89 | 90 | def gaussian_label(label, num_class, u=0, sig=4.0): 91 | ''' 92 | 转换成CSL Labels: 93 | 用高斯窗口函数根据角度θ的周期性赋予gt labels同样的周期性,使得损失函数在计算边界处时可以做到“差值很大但loss很小”; 94 | 并且使得其labels具有环形特征,能够反映各个θ之间的角度距离 95 | @param label: 当前box的θ类别 shape(1) 96 | @param num_class: θ类别数量=180 97 | @param u: 高斯函数中的μ 98 | @param sig: 高斯函数中的σ 99 | @return: 高斯离散数组:将高斯函数的最高值设置在θ所在的位置,例如label为45,则将高斯分布数列向右移动直至x轴为45时,取值为1 shape(180) 100 | ''' 101 | # floor()返回数字的下舍整数 ceil() 函数返回数字的上入整数 range(-90,90) 102 | # 以num_class=180为例,生成从-90到89的数字整形list shape(180) 103 | x = np.array(range(math.floor(-num_class / 2), math.ceil(num_class / 2), 1)) 104 | y_sig = np.exp(-(x - u) ** 2 / (2 * sig ** 2)) # shape(180) 为-90到89的经高斯公式计算后的数值 105 | # 将高斯函数的最高值设置在θ所在的位置,例如label为45,则将高斯分布数列向右移动直至x轴为45时,取值为1 106 | return np.concatenate([y_sig[math.ceil(num_class / 2) - int(label.item()):], 107 | y_sig[:math.ceil(num_class / 2) - int(label.item())]], axis=0) 108 | 109 | 110 | class ComputeLoss: 111 | # Compute losses 112 | def __init__(self, model, autobalance=False): 113 | super(ComputeLoss, self).__init__() 114 | self.sort_obj_iou = False 115 | device = next(model.parameters()).device # get model device 116 | h = model.hyp # hyperparameters 117 | self.class_index = 5 + model.nc 118 | 119 | # Define criteria 120 | BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device)) 121 | BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device)) 122 | BCEangle = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([h['angle_pw']])).to(device) 123 | 124 | # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3 125 | self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets 126 | 127 | # Focal loss 128 | g = h['fl_gamma'] # focal loss gamma 129 | if g > 0: 130 | BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g) 131 | BCEangle = FocalLoss(BCEangle, g) 132 | 133 | det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module 134 | self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7 135 | self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index 136 | self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance 137 | self.BCEangle = BCEangle 138 | for k in 'na', 'nc', 'nl', 'anchors': 139 | setattr(self, k, getattr(det, k)) 140 | 141 | def __call__(self, p, targets): # predictions, targets, model 142 | device = targets.device 143 | lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device) 144 | langle = torch.zeros(1, device=device) 145 | tcls, tangle, tbox, indices, anchors = self.build_targets(p, targets) # targets 146 | 147 | # Losses 148 | for i, pi in enumerate(p): # layer index, layer predictions 149 | b, a, gj, gi = indices[i] # image, anchor, gridy, gridx 150 | tobj = torch.zeros_like(pi[..., 0], device=device) # target obj 151 | 152 | n = b.shape[0] # number of targets 153 | if n: 154 | ps = pi[b, a, gj, gi] # prediction subset corresponding to targets 155 | 156 | # Regression 157 | pxy = ps[:, :2].sigmoid() * 2. - 0.5 158 | pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i] 159 | pbox = torch.cat((pxy, pwh), 1) # predicted box 160 | iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target) 161 | lbox += (1.0 - iou).mean() # iou loss 162 | 163 | # Objectness 164 | score_iou = iou.detach().clamp(0).type(tobj.dtype) 165 | if self.sort_obj_iou: 166 | sort_id = torch.argsort(score_iou) 167 | b, a, gj, gi, score_iou = b[sort_id], a[sort_id], gj[sort_id], gi[sort_id], score_iou[sort_id] 168 | tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * score_iou # iou ratio 169 | 170 | # Classification 171 | if self.nc > 1: # cls loss (only if multiple classes) 172 | t = torch.full_like(ps[:, 5:self.class_index], self.cn, device=device) # targets 173 | t[range(n), tcls[i]] = self.cp 174 | lcls += self.BCEcls(ps[:, 5:self.class_index], t) # BCE 175 | 176 | # Θ类别损失 177 | ttheta = torch.zeros_like(ps[:, self.class_index:]) # size(num, 180) 178 | for idx in range(len(ps)): # idx start from 0 to len(ps)-1 179 | # 3个tensor组成的list (tensor_angle_list[i]) 对每个步长网络生成对应的class tensor tangle[i].shape=(num_i, 1) 180 | theta = tangle[i][idx] # 取出第i个layer中的第idx个目标的角度数值 例如取值θ=90 181 | # CSL论文中窗口半径为6效果最佳,过小无法学到角度信息,过大则角度预测偏差加大 182 | csl_label = gaussian_label(theta, 180, u=0, sig=6) # 用长度为1的θ值构建长度为180的csl_label 183 | ttheta[idx] = torch.from_numpy(csl_label) # 将cls_label放入对应的目标中 184 | langle += self.BCEangle(ps[:, self.class_index:], ttheta) 185 | 186 | # Append targets to text file 187 | # with open('targets.txt', 'a') as file: 188 | # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)] 189 | 190 | obji = self.BCEobj(pi[..., 4], tobj) 191 | lobj += obji * self.balance[i] # obj loss 192 | if self.autobalance: 193 | self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item() 194 | 195 | if self.autobalance: 196 | self.balance = [x / self.balance[self.ssi] for x in self.balance] 197 | lbox *= self.hyp['box'] 198 | lobj *= self.hyp['obj'] 199 | lcls *= self.hyp['cls'] 200 | langle *= self.hyp['angle'] 201 | bs = tobj.shape[0] # batch size 202 | 203 | return (lbox + lobj + lcls + langle) * bs, torch.cat((lbox, lobj, lcls, langle)).detach() 204 | 205 | def build_targets(self, p, targets): 206 | # Build targets for compute_loss(), input targets(image,class,x,y,w,h) 207 | na, nt = self.na, targets.shape[0] # number of anchors, targets 208 | tcls, tbox, indices, anch = [], [], [], [] 209 | tangle = [] 210 | gain = torch.ones(8, device=targets.device) # normalized to gridspace gain 211 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) 212 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices 213 | 214 | g = 0.5 # bias 215 | off = torch.tensor([[0, 0], 216 | [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m 217 | # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm 218 | ], device=targets.device).float() * g # offsets 219 | 220 | for i in range(self.nl): 221 | anchors = self.anchors[i] 222 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain 223 | 224 | # Match targets to anchors 225 | t = targets * gain 226 | if nt: 227 | # Matches 228 | r = t[:, :, 4:6] / anchors[:, None] # wh ratio 229 | j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare 230 | # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) 231 | t = t[j] # filter 232 | 233 | # Offsets 234 | gxy = t[:, 2:4] # grid xy 235 | gxi = gain[[2, 3]] - gxy # inverse 236 | j, k = ((gxy % 1. < g) & (gxy > 1.)).T 237 | l, m = ((gxi % 1. < g) & (gxi > 1.)).T 238 | j = torch.stack((torch.ones_like(j), j, k, l, m)) 239 | t = t.repeat((5, 1, 1))[j] 240 | offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] 241 | else: 242 | t = targets[0] 243 | offsets = 0 244 | 245 | # Define 246 | b, c = t[:, :2].long().T # image, class 247 | angle = t[:, 6].long() # angle 248 | gxy = t[:, 2:4] # grid xy 249 | gwh = t[:, 4:6] # grid wh 250 | gij = (gxy - offsets).long() 251 | gi, gj = gij.T # grid xy indices 252 | 253 | # Append 254 | a = t[:, 7].long() # anchor indices 255 | indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices 256 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box 257 | anch.append(anchors[a]) # anchors 258 | tcls.append(c) # class 259 | tangle.append(angle) # angle 260 | 261 | return tcls, tangle, tbox, indices, anch 262 | --------------------------------------------------------------------------------