├── models ├── __init__.py ├── hub │ ├── yolov3-tiny.yaml │ ├── yolov5-fpn.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 ├── yolov5s.yaml ├── yolov5x.yaml └── experimental.py ├── utils ├── __init__.py ├── aws │ ├── __init__.py │ ├── mime.sh │ ├── resume.py │ └── userdata.sh ├── wandb_logging │ ├── __init__.py │ ├── log_dataset.py │ ├── sweep.py │ └── sweep.yaml ├── google_app_engine │ ├── additional_requirements.txt │ ├── app.yaml │ └── Dockerfile ├── flask_rest_api │ ├── example_request.py │ ├── restapi.py │ └── README.md ├── activations.py ├── google_utils.py ├── autoanchor.py ├── distill_fun.py ├── loss.py ├── augmentations.py └── torch_utils.py ├── .gitattributes ├── data ├── images │ ├── bus.jpg │ └── zidane.jpg ├── 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 ├── coco128.yaml ├── GlobalWheat2020.yaml ├── coco.yaml ├── SKU-110K.yaml ├── Argoverse_HD.yaml ├── VisDrone.yaml ├── VOC.yaml ├── xView.yaml └── Objects365.yaml ├── .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 ├── requirements.txt ├── README.md ├── Dockerfile ├── .dockerignore ├── CONTRIBUTING.md ├── .gitignore ├── hubconf.py ├── export.py └── detect.py /models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /utils/aws/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /utils/wandb_logging/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # this drop notebooks from GitHub language stats 2 | *.ipynb linguist-vendored 3 | -------------------------------------------------------------------------------- /data/images/bus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/magicshuang/yolov5_distillation/HEAD/data/images/bus.jpg -------------------------------------------------------------------------------- /data/images/zidane.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/magicshuang/yolov5_distillation/HEAD/data/images/zidane.jpg -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: glenn-jocher 4 | patreon: ultralytics 5 | open_collective: ultralytics 6 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | 13 | ## Additional context 14 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /data/scripts/download_weights.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Download latest models from https://github.com/ultralytics/yolov5/releases 3 | # Usage: 4 | # $ bash path/to/download_weights.sh 5 | 6 | python - <=3.2.2 5 | numpy>=1.18.5 6 | opencv-python>=4.1.2 7 | Pillow 8 | PyYAML>=5.3.1 9 | scipy>=1.4.1 10 | torch>=1.7.0 11 | torchvision>=0.8.1 12 | tqdm>=4.41.0 13 | 14 | # logging ------------------------------------- 15 | tensorboard>=2.4.1 16 | # wandb 17 | 18 | # plotting ------------------------------------ 19 | seaborn>=0.11.0 20 | pandas 21 | 22 | # export -------------------------------------- 23 | # coremltools>=4.1 24 | # onnx>=1.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.2 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 | 17 | 18 | ## Pitch 19 | 20 | 21 | 22 | ## Alternatives 23 | 24 | 25 | 26 | ## Additional context 27 | 28 | 29 | -------------------------------------------------------------------------------- /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/wandb_logging/log_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import yaml 4 | 5 | from wandb_utils import WandbLogger 6 | 7 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' 8 | 9 | 10 | def create_dataset_artifact(opt): 11 | with open(opt.data) as f: 12 | data = yaml.safe_load(f) # data dict 13 | logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation') 14 | 15 | 16 | if __name__ == '__main__': 17 | parser = argparse.ArgumentParser() 18 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') 19 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') 20 | parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project') 21 | parser.add_argument('--entity', default=None, help='W&B entity') 22 | 23 | opt = parser.parse_args() 24 | opt.resume = False # Explicitly disallow resume check for dataset upload job 25 | 26 | create_dataset_artifact(opt) 27 | -------------------------------------------------------------------------------- /utils/wandb_logging/sweep.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from pathlib import Path 3 | import wandb 4 | 5 | FILE = Path(__file__).absolute() 6 | sys.path.append(FILE.parents[2].as_posix()) # add utils/ to path 7 | 8 | from train import train, parse_opt 9 | import test 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/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 | iou_t: 0.2 24 | anchor_t: 2.91 25 | # anchors: 3.63 26 | fl_gamma: 0.0 27 | hsv_h: 0.0138 28 | hsv_s: 0.664 29 | hsv_v: 0.464 30 | degrees: 0.373 31 | translate: 0.245 32 | scale: 0.898 33 | shear: 0.602 34 | perspective: 0.0 35 | flipud: 0.00856 36 | fliplr: 0.5 37 | mosaic: 1.0 38 | mixup: 0.243 39 | copy_paste: 0.0 40 | -------------------------------------------------------------------------------- /data/scripts/get_coco.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # COCO 2017 dataset http://cocodataset.org 3 | # Download command: bash data/scripts/get_coco.sh 4 | # Train command: python train.py --data coco.yaml 5 | # Default dataset location is next to YOLOv5: 6 | # /parent_folder 7 | # /coco 8 | # /yolov5 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 & # download, unzip, remove in background 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 & # download, unzip, remove in background 26 | done 27 | wait # finish background tasks 28 | -------------------------------------------------------------------------------- /utils/flask_rest_api/restapi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Run a rest API exposing the yolov5s object detection model 3 | """ 4 | import argparse 5 | import io 6 | 7 | import torch 8 | from PIL import Image 9 | from flask import Flask, request 10 | 11 | app = Flask(__name__) 12 | 13 | DETECTION_URL = "/v1/object-detection/yolov5s" 14 | 15 | 16 | @app.route(DETECTION_URL, methods=["POST"]) 17 | def predict(): 18 | if not request.method == "POST": 19 | return 20 | 21 | if request.files.get("image"): 22 | image_file = request.files["image"] 23 | image_bytes = image_file.read() 24 | 25 | img = Image.open(io.BytesIO(image_bytes)) 26 | 27 | results = model(img, size=640) # reduce size=320 for faster inference 28 | return results.pandas().xyxy[0].to_json(orient="records") 29 | 30 | 31 | if __name__ == "__main__": 32 | parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model") 33 | parser.add_argument("--port", default=5000, type=int, help="port number") 34 | args = parser.parse_args() 35 | 36 | model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache 37 | app.run(host="0.0.0.0", port=args.port) # debug=True causes Restarting with stat 38 | -------------------------------------------------------------------------------- /utils/aws/resume.py: -------------------------------------------------------------------------------- 1 | # Resume all interrupted trainings in yolov5/ dir including DDP trainings 2 | # Usage: $ python utils/aws/resume.py 3 | 4 | import os 5 | import sys 6 | from pathlib import Path 7 | 8 | import torch 9 | import yaml 10 | 11 | sys.path.append('./') # to run '$ python *.py' files in subdirectories 12 | 13 | port = 0 # --master_port 14 | path = Path('').resolve() 15 | for last in path.rglob('*/**/last.pt'): 16 | ckpt = torch.load(last) 17 | if ckpt['optimizer'] is None: 18 | continue 19 | 20 | # Load opt.yaml 21 | with open(last.parent.parent / 'opt.yaml') as f: 22 | opt = yaml.safe_load(f) 23 | 24 | # Get device count 25 | d = opt['device'].split(',') # devices 26 | nd = len(d) # number of devices 27 | ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel 28 | 29 | if ddp: # multi-GPU 30 | port += 1 31 | cmd = f'python -m torch.distributed.launch --nproc_per_node {nd} --master_port {port} train.py --resume {last}' 32 | else: # single-GPU 33 | cmd = f'python train.py --resume {last}' 34 | 35 | cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread 36 | print(cmd) 37 | os.system(cmd) 38 | -------------------------------------------------------------------------------- /utils/aws/userdata.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html 3 | # This script will run only once on first instance start (for a re-start script see mime.sh) 4 | # /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir 5 | # Use >300 GB SSD 6 | 7 | cd home/ubuntu 8 | if [ ! -d yolov5 ]; then 9 | echo "Running first-time script." # install dependencies, download COCO, pull Docker 10 | git clone https://github.com/ultralytics/yolov5 -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/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 | -------------------------------------------------------------------------------- /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/yolov5s.yaml: -------------------------------------------------------------------------------- 1 | # Parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 0.33 # model depth multiple 4 | width_multiple: 0.50 # layer channel multiple 5 | 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # yolov5 知识蒸馏 2 | ##
介绍
3 | 4 | yolov5-l模型压缩至yolov5-s 5 | 压缩算法是 https://github.com/twangnh/Distilling-Object-Detectors 6 | 7 | ##
Quick Start Examples
8 | 9 | 10 |
11 | Install 12 | 13 | Python >= 3.6.0 required with all [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) dependencies installed: 14 | 15 | ```bash 16 | $ git clone https://github.com/magicshuang/yolov5_distillation 17 | $ cd magicshuang/yolov5_distillation 18 | $ pip install -r requirements.txt 19 | ``` 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 | 32 | Training 33 | 34 | 没有teacher模型的人,先训练teacher模型 35 | ```bash 36 | $ python train.py --data coco.yaml --cfg yolov5s.yaml --weights '' --batch-size 64 37 | yolov5m 40 38 | yolov5l 24 39 | yolov5x 16 40 | ``` 41 |
42 | 43 | 44 | 45 | 46 |
47 | Distillation Training 48 | 49 | ```bash 50 | $ python Distill_train.py --data coco.yaml --teacher-weights [your path] --batch-size 64 51 | 52 | ``` 53 | 54 |
55 | 56 | 57 | 58 | 59 | ##
详细了解
60 | 61 | 比yolov5源码只多了两个文件 62 | Distill_train.py & utils/distill_fun.py 63 | 64 | 所以可以直接下载这两个文件就可以了 65 | 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | iou_t: 0.20 # IoU training threshold 19 | anchor_t: 4.0 # anchor-multiple threshold 20 | # anchors: 3 # anchors per output layer (0 to ignore) 21 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) 22 | hsv_h: 0.015 # image HSV-Hue augmentation (fraction) 23 | hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) 24 | hsv_v: 0.4 # image HSV-Value augmentation (fraction) 25 | degrees: 0.0 # image rotation (+/- deg) 26 | translate: 0.1 # image translation (+/- fraction) 27 | scale: 0.5 # image scale (+/- gain) 28 | shear: 0.0 # image shear (+/- deg) 29 | perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 30 | flipud: 0.0 # image flip up-down (probability) 31 | fliplr: 0.5 # image flip left-right (probability) 32 | mosaic: 1.0 # image mosaic (probability) 33 | mixup: 0.0 # image mixup (probability) 34 | copy_paste: 0.0 # segment copy-paste (probability) 35 | -------------------------------------------------------------------------------- /data/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 | iou_t: 0.20 # IoU training threshold 19 | anchor_t: 4.0 # anchor-multiple threshold 20 | # anchors: 3 # anchors per output layer (0 to ignore) 21 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) 22 | hsv_h: 0.015 # image HSV-Hue augmentation (fraction) 23 | hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) 24 | hsv_v: 0.4 # image HSV-Value augmentation (fraction) 25 | degrees: 0.0 # image rotation (+/- deg) 26 | translate: 0.1 # image translation (+/- fraction) 27 | scale: 0.9 # image scale (+/- gain) 28 | shear: 0.0 # image shear (+/- deg) 29 | perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 30 | flipud: 0.0 # image flip up-down (probability) 31 | fliplr: 0.5 # image flip left-right (probability) 32 | mosaic: 1.0 # image mosaic (probability) 33 | mixup: 0.0 # image mixup (probability) 34 | copy_paste: 0.0 # segment copy-paste (probability) 35 | -------------------------------------------------------------------------------- /data/coco128.yaml: -------------------------------------------------------------------------------- 1 | # COCO 2017 dataset http://cocodataset.org - first 128 training images 2 | # Train command: python train.py --data coco128.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/coco128 6 | # /yolov5 7 | 8 | 9 | # 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, ..] 10 | path: ../datasets/coco128 # dataset root dir 11 | train: images/train2017 # train images (relative to 'path') 128 images 12 | val: images/train2017 # val images (relative to 'path') 128 images 13 | test: # test images (optional) 14 | 15 | # Classes 16 | nc: 80 # number of classes 17 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 18 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 19 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 20 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 21 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 22 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 23 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 24 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 25 | 'hair drier', 'toothbrush' ] # class names 26 | 27 | 28 | # Download script/URL (optional) 29 | download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip -------------------------------------------------------------------------------- /.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, otherwise it is non-actionable, and we can not help you: 11 | - **Current repo**: run `git fetch && git status -uno` to check and `git pull` to update repo 12 | - **Common dataset**: coco.yaml or coco128.yaml 13 | - **Common environment**: Colab, Google Cloud, or Docker image. See https://github.com/ultralytics/yolov5#environments 14 | 15 | If this is a custom dataset/training question you **must include** your `train*.jpg`, `val*.jpg` and `results.png` figures, or we can not help you. You can generate these with `utils.plot_results()`. 16 | 17 | 18 | ## 🐛 Bug 19 | A clear and concise description of what the bug is. 20 | 21 | 22 | ## To Reproduce (REQUIRED) 23 | 24 | Input: 25 | ``` 26 | import torch 27 | 28 | a = torch.tensor([5]) 29 | c = a / 0 30 | ``` 31 | 32 | Output: 33 | ``` 34 | Traceback (most recent call last): 35 | File "/Users/glennjocher/opt/anaconda3/envs/env1/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3331, in run_code 36 | exec(code_obj, self.user_global_ns, self.user_ns) 37 | File "", line 5, in 38 | c = a / 0 39 | RuntimeError: ZeroDivisionError 40 | ``` 41 | 42 | 43 | ## Expected behavior 44 | A clear and concise description of what you expected to happen. 45 | 46 | 47 | ## Environment 48 | If applicable, add screenshots to help explain your problem. 49 | 50 | - OS: [e.g. Ubuntu] 51 | - GPU [e.g. 2080 Ti] 52 | 53 | 54 | ## Additional context 55 | Add any other context about the problem here. 56 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch 2 | FROM nvcr.io/nvidia/pytorch:21.05-py3 3 | 4 | # Install linux packages 5 | RUN apt update && apt install -y zip htop screen libgl1-mesa-glx 6 | 7 | # Install python dependencies 8 | COPY requirements.txt . 9 | RUN python -m pip install --upgrade pip 10 | RUN pip uninstall -y nvidia-tensorboard nvidia-tensorboard-plugin-dlprof 11 | RUN pip install --no-cache -r requirements.txt coremltools onnx gsutil notebook 12 | RUN pip install --no-cache -U torch torchvision numpy 13 | # RUN pip install --no-cache torch==1.9.0+cu111 torchvision==0.10.0+cu111 -f https://download.pytorch.org/whl/torch_stable.html 14 | 15 | # Create working directory 16 | RUN mkdir -p /usr/src/app 17 | WORKDIR /usr/src/app 18 | 19 | # Copy contents 20 | COPY . /usr/src/app 21 | 22 | # Set environment variables 23 | ENV HOME=/usr/src/app 24 | 25 | 26 | # Usage Examples ------------------------------------------------------------------------------------------------------- 27 | 28 | # Build and Push 29 | # t=ultralytics/yolov5:latest && sudo docker build -t $t . && sudo docker push $t 30 | 31 | # Pull and Run 32 | # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t 33 | 34 | # Pull and Run with local directory access 35 | # t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/datasets:/usr/src/datasets $t 36 | 37 | # Kill all 38 | # sudo docker kill $(sudo docker ps -q) 39 | 40 | # Kill all image-based 41 | # sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest) 42 | 43 | # Bash into running container 44 | # sudo docker exec -it 5a9b5863d93d bash 45 | 46 | # Bash into stopped container 47 | # id=$(sudo docker ps -qa) && sudo docker start $id && sudo docker exec -it $id bash 48 | 49 | # Clean up 50 | # docker system prune -a --volumes 51 | -------------------------------------------------------------------------------- /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/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/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/GlobalWheat2020.yaml: -------------------------------------------------------------------------------- 1 | # Global Wheat 2020 dataset http://www.global-wheat.com/ 2 | # Train command: python train.py --data GlobalWheat2020.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/GlobalWheat2020 6 | # /yolov5 7 | 8 | 9 | # 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, ..] 10 | path: ../datasets/GlobalWheat2020 # dataset root dir 11 | train: # train images (relative to 'path') 3422 images 12 | - images/arvalis_1 13 | - images/arvalis_2 14 | - images/arvalis_3 15 | - images/ethz_1 16 | - images/rres_1 17 | - images/inrae_1 18 | - images/usask_1 19 | val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1) 20 | - images/ethz_1 21 | test: # test images (optional) 1276 images 22 | - images/utokyo_1 23 | - images/utokyo_2 24 | - images/nau_1 25 | - images/uq_1 26 | 27 | # Classes 28 | nc: 1 # number of classes 29 | names: [ 'wheat_head' ] # class names 30 | 31 | 32 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 33 | download: | 34 | from utils.general import download, Path 35 | 36 | # Download 37 | dir = Path(yaml['path']) # dataset root dir 38 | urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip', 39 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip'] 40 | download(urls, dir=dir) 41 | 42 | # Make Directories 43 | for p in 'annotations', 'images', 'labels': 44 | (dir / p).mkdir(parents=True, exist_ok=True) 45 | 46 | # Move 47 | for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \ 48 | 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1': 49 | (dir / p).rename(dir / 'images' / p) # move to /images 50 | f = (dir / p).with_suffix('.json') # json file 51 | if f.exists(): 52 | f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations 53 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | # COCO 2017 dataset http://cocodataset.org 2 | # Train command: python train.py --data coco.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/coco 6 | # /yolov5 7 | 8 | 9 | # 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, ..] 10 | path: ../datasets/coco # dataset root dir 11 | train: train2017.txt # train images (relative to 'path') 118287 images 12 | val: val2017.txt # train images (relative to 'path') 5000 images 13 | test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794 14 | 15 | # Classes 16 | nc: 80 # number of classes 17 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 18 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 19 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 20 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 21 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 22 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 23 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 24 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 25 | 'hair drier', 'toothbrush' ] # class names 26 | 27 | 28 | # Download script/URL (optional) 29 | download: | 30 | from utils.general import download, Path 31 | 32 | # Download labels 33 | segments = False # segment or box labels 34 | dir = Path(yaml['path']) # dataset root dir 35 | url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' 36 | urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels 37 | download(urls, dir=dir.parent) 38 | 39 | # Download data 40 | urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images 41 | 'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images 42 | 'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional) 43 | download(urls, dir=dir / 'images', threads=3) 44 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /data/SKU-110K.yaml: -------------------------------------------------------------------------------- 1 | # SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 2 | # Train command: python train.py --data SKU-110K.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/SKU-110K 6 | # /yolov5 7 | 8 | 9 | # 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, ..] 10 | path: ../datasets/SKU-110K # dataset root dir 11 | train: train.txt # train images (relative to 'path') 8219 images 12 | val: val.txt # val images (relative to 'path') 588 images 13 | test: test.txt # test images (optional) 2936 images 14 | 15 | # Classes 16 | nc: 1 # number of classes 17 | names: [ 'object' ] # class names 18 | 19 | 20 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 21 | download: | 22 | import shutil 23 | from tqdm import tqdm 24 | from utils.general import np, pd, Path, download, xyxy2xywh 25 | 26 | # Download 27 | dir = Path(yaml['path']) # dataset root dir 28 | parent = Path(dir.parent) # download dir 29 | urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz'] 30 | download(urls, dir=parent, delete=False) 31 | 32 | # Rename directories 33 | if dir.exists(): 34 | shutil.rmtree(dir) 35 | (parent / 'SKU110K_fixed').rename(dir) # rename dir 36 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir 37 | 38 | # Convert labels 39 | names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names 40 | for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv': 41 | x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations 42 | images, unique_images = x[:, 0], np.unique(x[:, 0]) 43 | with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f: 44 | f.writelines(f'./images/{s}\n' for s in unique_images) 45 | for im in tqdm(unique_images, desc=f'Converting {dir / d}'): 46 | cls = 0 # single-class dataset 47 | with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f: 48 | for r in x[images == im]: 49 | w, h = r[6], r[7] # image width, height 50 | xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance 51 | f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label 52 | -------------------------------------------------------------------------------- /data/Argoverse_HD.yaml: -------------------------------------------------------------------------------- 1 | # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ 2 | # Train command: python train.py --data Argoverse_HD.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/Argoverse 6 | # /yolov5 7 | 8 | 9 | # 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, ..] 10 | path: ../datasets/Argoverse # dataset root dir 11 | train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images 12 | val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images 13 | test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview 14 | 15 | # Classes 16 | nc: 8 # number of classes 17 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign' ] # class names 18 | 19 | 20 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 21 | download: | 22 | import json 23 | 24 | from tqdm import tqdm 25 | from utils.general import download, Path 26 | 27 | 28 | def argoverse2yolo(set): 29 | labels = {} 30 | a = json.load(open(set, "rb")) 31 | for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."): 32 | img_id = annot['image_id'] 33 | img_name = a['images'][img_id]['name'] 34 | img_label_name = img_name[:-3] + "txt" 35 | 36 | cls = annot['category_id'] # instance class id 37 | x_center, y_center, width, height = annot['bbox'] 38 | x_center = (x_center + width / 2) / 1920.0 # offset and scale 39 | y_center = (y_center + height / 2) / 1200.0 # offset and scale 40 | width /= 1920.0 # scale 41 | height /= 1200.0 # scale 42 | 43 | img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']] 44 | if not img_dir.exists(): 45 | img_dir.mkdir(parents=True, exist_ok=True) 46 | 47 | k = str(img_dir / img_label_name) 48 | if k not in labels: 49 | labels[k] = [] 50 | labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n") 51 | 52 | for k in labels: 53 | with open(k, "w") as f: 54 | f.writelines(labels[k]) 55 | 56 | 57 | # Download 58 | dir = Path('../datasets/Argoverse') # dataset root dir 59 | urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip'] 60 | download(urls, dir=dir, delete=False) 61 | 62 | # Convert 63 | annotations_dir = 'Argoverse-HD/annotations/' 64 | (dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images' 65 | for d in "train.json", "val.json": 66 | argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels 67 | -------------------------------------------------------------------------------- /data/VisDrone.yaml: -------------------------------------------------------------------------------- 1 | # VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset 2 | # Train command: python train.py --data VisDrone.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/VisDrone 6 | # /yolov5 7 | 8 | 9 | # 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, ..] 10 | path: ../datasets/VisDrone # dataset root dir 11 | train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images 12 | val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images 13 | test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images 14 | 15 | # Classes 16 | nc: 10 # number of classes 17 | names: [ 'pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor' ] 18 | 19 | 20 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 21 | download: | 22 | from utils.general import download, os, Path 23 | 24 | def visdrone2yolo(dir): 25 | from PIL import Image 26 | from tqdm import tqdm 27 | 28 | def convert_box(size, box): 29 | # Convert VisDrone box to YOLO xywh box 30 | dw = 1. / size[0] 31 | dh = 1. / size[1] 32 | return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh 33 | 34 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory 35 | pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}') 36 | for f in pbar: 37 | img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size 38 | lines = [] 39 | with open(f, 'r') as file: # read annotation.txt 40 | for row in [x.split(',') for x in file.read().strip().splitlines()]: 41 | if row[4] == '0': # VisDrone 'ignored regions' class 0 42 | continue 43 | cls = int(row[5]) - 1 44 | box = convert_box(img_size, tuple(map(int, row[:4]))) 45 | lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n") 46 | with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl: 47 | fl.writelines(lines) # write label.txt 48 | 49 | 50 | # Download 51 | dir = Path(yaml['path']) # dataset root dir 52 | urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip', 53 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip', 54 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip', 55 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip'] 56 | download(urls, dir=dir) 57 | 58 | # Convert 59 | for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev': 60 | visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels 61 | -------------------------------------------------------------------------------- /.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/wandb_logging/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/wandb_logging/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 | # PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC/ 2 | # Train command: python train.py --data VOC.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/VOC 6 | # /yolov5 7 | 8 | 9 | # 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, ..] 10 | path: ../datasets/VOC 11 | train: # train images (relative to 'path') 16551 images 12 | - images/train2012 13 | - images/train2007 14 | - images/val2012 15 | - images/val2007 16 | val: # val images (relative to 'path') 4952 images 17 | - images/test2007 18 | test: # test images (optional) 19 | - images/test2007 20 | 21 | # Classes 22 | nc: 20 # number of classes 23 | names: [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 24 | 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' ] # class names 25 | 26 | 27 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 28 | download: | 29 | import xml.etree.ElementTree as ET 30 | 31 | from tqdm import tqdm 32 | from utils.general import download, Path 33 | 34 | 35 | def convert_label(path, lb_path, year, image_id): 36 | def convert_box(size, box): 37 | dw, dh = 1. / size[0], 1. / size[1] 38 | 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] 39 | return x * dw, y * dh, w * dw, h * dh 40 | 41 | in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml') 42 | out_file = open(lb_path, 'w') 43 | tree = ET.parse(in_file) 44 | root = tree.getroot() 45 | size = root.find('size') 46 | w = int(size.find('width').text) 47 | h = int(size.find('height').text) 48 | 49 | for obj in root.iter('object'): 50 | cls = obj.find('name').text 51 | if cls in yaml['names'] and not int(obj.find('difficult').text) == 1: 52 | xmlbox = obj.find('bndbox') 53 | bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')]) 54 | cls_id = yaml['names'].index(cls) # class id 55 | out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n') 56 | 57 | 58 | # Download 59 | dir = Path(yaml['path']) # dataset root dir 60 | url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' 61 | urls = [url + 'VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images 62 | url + 'VOCtest_06-Nov-2007.zip', # 438MB, 4953 images 63 | url + 'VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images 64 | download(urls, dir=dir / 'images', delete=False) 65 | 66 | # Convert 67 | path = dir / f'images/VOCdevkit' 68 | for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'): 69 | imgs_path = dir / 'images' / f'{image_set}{year}' 70 | lbs_path = dir / 'labels' / f'{image_set}{year}' 71 | imgs_path.mkdir(exist_ok=True, parents=True) 72 | lbs_path.mkdir(exist_ok=True, parents=True) 73 | 74 | image_ids = open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt').read().strip().split() 75 | for id in tqdm(image_ids, desc=f'{image_set}{year}'): 76 | f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path 77 | lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path 78 | f.rename(imgs_path / f.name) # move image 79 | convert_label(path, lb_path, year, id) # convert labels to YOLO format 80 | -------------------------------------------------------------------------------- /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*.txt 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://www.ultralytics.com or email Glenn Jocher at glenn.jocher@ultralytics.com. 33 | 34 | ## Requirements 35 | 36 | Python 3.8 or later with all [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) dependencies installed, including `torch>=1.7`. To install run: 37 | ```bash 38 | $ pip install -r requirements.txt 39 | ``` 40 | 41 | ## Environments 42 | 43 | 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): 44 | 45 | - **Google Colab and Kaggle** notebooks with free GPU: Open In Colab Open In Kaggle 46 | - **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart) 47 | - **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart) 48 | - **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) Docker Pulls 49 | 50 | 51 | ## Status 52 | 53 | ![CI CPU testing](https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg) 54 | 55 | 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)), testing ([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. 56 | 57 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing to YOLOv5 🚀 2 | 3 | We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible, whether it's: 4 | 5 | - Reporting a bug 6 | - Discussing the current state of the code 7 | - Submitting a fix 8 | - Proposing a new feature 9 | - Becoming a maintainer 10 | 11 | YOLOv5 works so well due to our combined community effort, and for every small improvement you contribute you will be helping push the frontiers of what's possible in AI 😃! 12 | 13 | 14 | ## Submitting a Pull Request (PR) 🛠️ 15 | Submitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps: 16 | 17 | ### 1. Select File to Update 18 | Select `requirements.txt` to update by clicking on it in GitHub. 19 |

PR_step1

20 | 21 | ### 2. Click 'Edit this file' 22 | Button is in top-right corner. 23 |

PR_step2

24 | 25 | ### 3. Make Changes 26 | Change `matplotlib` version from `3.2.2` to `3.3`. 27 |

PR_step3

28 | 29 | ### 4. Preview Changes and Submit PR 30 | Click on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch** for this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose changes** button. All done, your PR is now submitted to YOLOv5 for review and approval 😃! 31 |

PR_step4

32 | 33 | ### PR recommendations 34 | 35 | To allow your work to be integrated as seamlessly as possible, we advise you to: 36 | - ✅ 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: 37 | ```bash 38 | git remote add upstream https://github.com/ultralytics/yolov5.git 39 | git fetch upstream 40 | git checkout feature # <----- replace 'feature' with local branch name 41 | git merge upstream/master 42 | git push -u origin -f 43 | ``` 44 | - ✅ Verify all Continuous Integration (CI) **checks are passing**. 45 | - ✅ 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 46 | 47 | 48 | ## Submitting a Bug Report 🐛 49 | 50 | If you spot a problem with YOLOv5 please submit a Bug Report! 51 | 52 | For us to start investigating a possibel problem we need to be able to reproduce it ourselves first. We've created a few short guidelines below to help users provide what we need in order to get started. 53 | 54 | When asking a question, people will be better able to provide help if you provide **code** that they can easily understand and use to **reproduce** the problem. This is referred to by community members as creating a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your code that reproduces the problem should be: 55 | 56 | * ✅ **Minimal** – Use as little code as possible that still produces the same problem 57 | * ✅ **Complete** – Provide **all** parts someone else needs to reproduce your problem in the question itself 58 | * ✅ **Reproducible** – Test the code you're about to provide to make sure it reproduces the problem 59 | 60 | In addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code should be: 61 | 62 | * ✅ **Current** – Verify that your code is up-to-date with current GitHub [master](https://github.com/ultralytics/yolov5/tree/master), and if necessary `git pull` or `git clone` a new copy to ensure your problem has not already been resolved by previous commits. 63 | * ✅ **Unmodified** – Your problem must be reproducible without any modifications to the codebase in this repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code ⚠️. 64 | 65 | If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the 🐛 **Bug Report** [template](https://github.com/ultralytics/yolov5/issues/new/choose) and providing a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to help us better understand and diagnose your problem. 66 | 67 | 68 | ## License 69 | 70 | By contributing, you agree that your contributions will be licensed under the [GPL-3.0 license](https://choosealicense.com/licenses/gpl-3.0/) 71 | -------------------------------------------------------------------------------- /.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*.txt 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 | # xView 2018 dataset https://challenge.xviewdataset.org 2 | # ----> NOTE: DOWNLOAD DATA MANUALLY from URL above and unzip to /datasets/xView before running train command below 3 | # Train command: python train.py --data xView.yaml 4 | # Default dataset location is next to YOLOv5: 5 | # /parent 6 | # /datasets/xView 7 | # /yolov5 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/xView # dataset root dir 12 | train: images/autosplit_train.txt # train images (relative to 'path') 90% of 847 train images 13 | val: images/autosplit_val.txt # train images (relative to 'path') 10% of 847 train images 14 | 15 | # Classes 16 | nc: 60 # number of classes 17 | names: [ 'Fixed-wing Aircraft', 'Small Aircraft', 'Cargo Plane', 'Helicopter', 'Passenger Vehicle', 'Small Car', 'Bus', 18 | 'Pickup Truck', 'Utility Truck', 'Truck', 'Cargo Truck', 'Truck w/Box', 'Truck Tractor', 'Trailer', 19 | 'Truck w/Flatbed', 'Truck w/Liquid', 'Crane Truck', 'Railway Vehicle', 'Passenger Car', 'Cargo Car', 20 | 'Flat Car', 'Tank car', 'Locomotive', 'Maritime Vessel', 'Motorboat', 'Sailboat', 'Tugboat', 'Barge', 21 | 'Fishing Vessel', 'Ferry', 'Yacht', 'Container Ship', 'Oil Tanker', 'Engineering Vehicle', 'Tower crane', 22 | 'Container Crane', 'Reach Stacker', 'Straddle Carrier', 'Mobile Crane', 'Dump Truck', 'Haul Truck', 23 | 'Scraper/Tractor', 'Front loader/Bulldozer', 'Excavator', 'Cement Mixer', 'Ground Grader', 'Hut/Tent', 'Shed', 24 | 'Building', 'Aircraft Hangar', 'Damaged Building', 'Facility', 'Construction Site', 'Vehicle Lot', 'Helipad', 25 | 'Storage Tank', 'Shipping container lot', 'Shipping Container', 'Pylon', 'Tower' ] # class names 26 | 27 | 28 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 29 | download: | 30 | import json 31 | import os 32 | from pathlib import Path 33 | 34 | import numpy as np 35 | from PIL import Image 36 | from tqdm import tqdm 37 | 38 | from utils.datasets import autosplit 39 | from utils.general import download, xyxy2xywhn 40 | 41 | 42 | def convert_labels(fname=Path('xView/xView_train.geojson')): 43 | # Convert xView geoJSON labels to YOLO format 44 | path = fname.parent 45 | with open(fname) as f: 46 | print(f'Loading {fname}...') 47 | data = json.load(f) 48 | 49 | # Make dirs 50 | labels = Path(path / 'labels' / 'train') 51 | os.system(f'rm -rf {labels}') 52 | labels.mkdir(parents=True, exist_ok=True) 53 | 54 | # xView classes 11-94 to 0-59 55 | 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, 56 | 12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1, 57 | 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46, 58 | 47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59] 59 | 60 | shapes = {} 61 | for feature in tqdm(data['features'], desc=f'Converting {fname}'): 62 | p = feature['properties'] 63 | if p['bounds_imcoords']: 64 | id = p['image_id'] 65 | file = path / 'train_images' / id 66 | if file.exists(): # 1395.tif missing 67 | try: 68 | box = np.array([int(num) for num in p['bounds_imcoords'].split(",")]) 69 | assert box.shape[0] == 4, f'incorrect box shape {box.shape[0]}' 70 | cls = p['type_id'] 71 | cls = xview_class2index[int(cls)] # xView class to 0-60 72 | assert 59 >= cls >= 0, f'incorrect class index {cls}' 73 | 74 | # Write YOLO label 75 | if id not in shapes: 76 | shapes[id] = Image.open(file).size 77 | box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True) 78 | with open((labels / id).with_suffix('.txt'), 'a') as f: 79 | f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt 80 | except Exception as e: 81 | print(f'WARNING: skipping one label for {file}: {e}') 82 | 83 | 84 | # Download manually from https://challenge.xviewdataset.org 85 | dir = Path(yaml['path']) # dataset root dir 86 | # urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels 87 | # 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images 88 | # 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels) 89 | # download(urls, dir=dir, delete=False) 90 | 91 | # Convert labels 92 | convert_labels(dir / 'xView_train.geojson') 93 | 94 | # Move images 95 | images = Path(dir / 'images') 96 | images.mkdir(parents=True, exist_ok=True) 97 | Path(dir / 'train_images').rename(dir / 'images' / 'train') 98 | Path(dir / 'val_images').rename(dir / 'images' / 'val') 99 | 100 | # Split 101 | autosplit(dir / 'images' / 'train') 102 | -------------------------------------------------------------------------------- /models/experimental.py: -------------------------------------------------------------------------------- 1 | # YOLOv5 experimental modules 2 | 3 | import numpy as np 4 | import torch 5 | import torch.nn as nn 6 | 7 | from models.common import Conv, DWConv 8 | from utils.google_utils import attempt_download 9 | 10 | 11 | class CrossConv(nn.Module): 12 | # Cross Convolution Downsample 13 | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): 14 | # ch_in, ch_out, kernel, stride, groups, expansion, shortcut 15 | super(CrossConv, self).__init__() 16 | c_ = int(c2 * e) # hidden channels 17 | self.cv1 = Conv(c1, c_, (1, k), (1, s)) 18 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) 19 | self.add = shortcut and c1 == c2 20 | 21 | def forward(self, x): 22 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) 23 | 24 | 25 | class Sum(nn.Module): 26 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 27 | def __init__(self, n, weight=False): # n: number of inputs 28 | super(Sum, self).__init__() 29 | self.weight = weight # apply weights boolean 30 | self.iter = range(n - 1) # iter object 31 | if weight: 32 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights 33 | 34 | def forward(self, x): 35 | y = x[0] # no weight 36 | if self.weight: 37 | w = torch.sigmoid(self.w) * 2 38 | for i in self.iter: 39 | y = y + x[i + 1] * w[i] 40 | else: 41 | for i in self.iter: 42 | y = y + x[i + 1] 43 | return y 44 | 45 | 46 | class GhostConv(nn.Module): 47 | # Ghost Convolution https://github.com/huawei-noah/ghostnet 48 | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups 49 | super(GhostConv, self).__init__() 50 | c_ = c2 // 2 # hidden channels 51 | self.cv1 = Conv(c1, c_, k, s, None, g, act) 52 | self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) 53 | 54 | def forward(self, x): 55 | y = self.cv1(x) 56 | return torch.cat([y, self.cv2(y)], 1) 57 | 58 | 59 | class GhostBottleneck(nn.Module): 60 | # Ghost Bottleneck https://github.com/huawei-noah/ghostnet 61 | def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride 62 | super(GhostBottleneck, self).__init__() 63 | c_ = c2 // 2 64 | self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw 65 | DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw 66 | GhostConv(c_, c2, 1, 1, act=False)) # pw-linear 67 | self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), 68 | Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() 69 | 70 | def forward(self, x): 71 | return self.conv(x) + self.shortcut(x) 72 | 73 | 74 | class MixConv2d(nn.Module): 75 | # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595 76 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): 77 | super(MixConv2d, self).__init__() 78 | groups = len(k) 79 | if equal_ch: # equal c_ per group 80 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices 81 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels 82 | else: # equal weight.numel() per group 83 | b = [c2] + [0] * groups 84 | a = np.eye(groups + 1, groups, k=-1) 85 | a -= np.roll(a, 1, axis=1) 86 | a *= np.array(k) ** 2 87 | a[0] = 1 88 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b 89 | 90 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)]) 91 | self.bn = nn.BatchNorm2d(c2) 92 | self.act = nn.LeakyReLU(0.1, inplace=True) 93 | 94 | def forward(self, x): 95 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) 96 | 97 | 98 | class Ensemble(nn.ModuleList): 99 | # Ensemble of models 100 | def __init__(self): 101 | super(Ensemble, self).__init__() 102 | 103 | def forward(self, x, augment=False, 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.google_utils 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 | 119 | imgs = ['data/images/zidane.jpg', # filename 120 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg', # URI 121 | cv2.imread('data/images/bus.jpg')[:, :, ::-1], # OpenCV 122 | Image.open('data/images/bus.jpg'), # PIL 123 | np.zeros((320, 640, 3))] # numpy 124 | 125 | results = model(imgs) # batched inference 126 | results.print() 127 | results.save() 128 | -------------------------------------------------------------------------------- /utils/google_utils.py: -------------------------------------------------------------------------------- 1 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries 2 | 3 | import os 4 | import platform 5 | import subprocess 6 | import time 7 | 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.google_utils 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.google_utils 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 | # def upload_blob(bucket_name, source_file_name, destination_blob_name): 119 | # # Uploads a file to a bucket 120 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python 121 | # 122 | # storage_client = storage.Client() 123 | # bucket = storage_client.get_bucket(bucket_name) 124 | # blob = bucket.blob(destination_blob_name) 125 | # 126 | # blob.upload_from_filename(source_file_name) 127 | # 128 | # print('File {} uploaded to {}.'.format( 129 | # source_file_name, 130 | # destination_blob_name)) 131 | # 132 | # 133 | # def download_blob(bucket_name, source_blob_name, destination_file_name): 134 | # # Uploads a blob from a bucket 135 | # storage_client = storage.Client() 136 | # bucket = storage_client.get_bucket(bucket_name) 137 | # blob = bucket.blob(source_blob_name) 138 | # 139 | # blob.download_to_filename(destination_file_name) 140 | # 141 | # print('Blob {} downloaded to {}.'.format( 142 | # source_blob_name, 143 | # destination_file_name)) 144 | -------------------------------------------------------------------------------- /data/Objects365.yaml: -------------------------------------------------------------------------------- 1 | # Objects365 dataset https://www.objects365.org/ 2 | # Train command: python train.py --data Objects365.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/Objects365 6 | # /yolov5 7 | 8 | 9 | # 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, ..] 10 | path: ../datasets/Objects365 # dataset root dir 11 | train: images/train # train images (relative to 'path') 1742289 images 12 | val: images/val # val images (relative to 'path') 5570 images 13 | test: # test images (optional) 14 | 15 | # Classes 16 | nc: 365 # number of classes 17 | names: [ 'Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup', 18 | 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book', 19 | 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag', 20 | 'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV', 21 | 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle', 22 | 'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird', 23 | 'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck', 24 | 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning', 25 | 'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife', 26 | 'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock', 27 | 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish', 28 | 'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan', 29 | 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard', 30 | 'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign', 31 | 'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat', 32 | 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard', 33 | 'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry', 34 | 'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks', 35 | 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors', 36 | 'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape', 37 | 'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck', 38 | 'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette', 39 | 'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket', 40 | 'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine', 41 | 'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine', 42 | 'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon', 43 | 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse', 44 | 'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball', 45 | 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin', 46 | 'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts', 47 | 'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit', 48 | 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD', 49 | 'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder', 50 | 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips', 51 | 'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab', 52 | 'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal', 53 | 'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart', 54 | 'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French', 55 | 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell', 56 | 'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil', 57 | 'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis' ] 58 | 59 | 60 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 61 | download: | 62 | from pycocotools.coco import COCO 63 | from tqdm import tqdm 64 | 65 | from utils.general import download, Path 66 | 67 | # Make Directories 68 | dir = Path(yaml['path']) # dataset root dir 69 | for p in 'images', 'labels': 70 | (dir / p).mkdir(parents=True, exist_ok=True) 71 | for q in 'train', 'val': 72 | (dir / p / q).mkdir(parents=True, exist_ok=True) 73 | 74 | # Download 75 | url = "https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/train/" 76 | download([url + 'zhiyuan_objv2_train.tar.gz'], dir=dir, delete=False) # annotations json 77 | download([url + f for f in [f'patch{i}.tar.gz' for i in range(51)]], dir=dir / 'images' / 'train', 78 | curl=True, delete=False, threads=8) 79 | 80 | # Move 81 | train = dir / 'images' / 'train' 82 | for f in tqdm(train.rglob('*.jpg'), desc=f'Moving images'): 83 | f.rename(train / f.name) # move to /images/train 84 | 85 | # Labels 86 | coco = COCO(dir / 'zhiyuan_objv2_train.json') 87 | names = [x["name"] for x in coco.loadCats(coco.getCatIds())] 88 | for cid, cat in enumerate(names): 89 | catIds = coco.getCatIds(catNms=[cat]) 90 | imgIds = coco.getImgIds(catIds=catIds) 91 | for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'): 92 | width, height = im["width"], im["height"] 93 | path = Path(im["file_name"]) # image filename 94 | try: 95 | with open(dir / 'labels' / 'train' / path.with_suffix('.txt').name, 'a') as file: 96 | annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None) 97 | for a in coco.loadAnns(annIds): 98 | x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner) 99 | x, y = x + w / 2, y + h / 2 # xy to center 100 | file.write(f"{cid} {x / width:.5f} {y / height:.5f} {w / width:.5f} {h / height:.5f}\n") 101 | 102 | except Exception as e: 103 | print(e) 104 | -------------------------------------------------------------------------------- /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(path='./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 | path: path to dataset *.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(path, str): # *.yaml file 107 | with open(path) 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 | else: 112 | dataset = path # dataset 113 | 114 | # Get label wh 115 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) 116 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh 117 | 118 | # Filter 119 | i = (wh0 < 3.0).any(1).sum() 120 | if i: 121 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.') 122 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels 123 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 124 | 125 | # Kmeans calculation 126 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...') 127 | s = wh.std(0) # sigmas for whitening 128 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance 129 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}') 130 | k *= s 131 | wh = torch.tensor(wh, dtype=torch.float32) # filtered 132 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered 133 | k = print_results(k) 134 | 135 | # Plot 136 | # k, d = [None] * 20, [None] * 20 137 | # for i in tqdm(range(1, 21)): 138 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance 139 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) 140 | # ax = ax.ravel() 141 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') 142 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh 143 | # ax[0].hist(wh[wh[:, 0]<100, 0],400) 144 | # ax[1].hist(wh[wh[:, 1]<100, 1],400) 145 | # fig.savefig('wh.png', dpi=200) 146 | 147 | # Evolve 148 | npr = np.random 149 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma 150 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar 151 | for _ in pbar: 152 | v = np.ones(sh) 153 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates) 154 | v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) 155 | kg = (k.copy() * v).clip(min=2.0) 156 | fg = anchor_fitness(kg) 157 | if fg > f: 158 | f, k = fg, kg.copy() 159 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' 160 | if verbose: 161 | print_results(k) 162 | 163 | return print_results(k) 164 | -------------------------------------------------------------------------------- /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 run(weights='./yolov5s.pt', # weights path 28 | img_size=(640, 640), # image (height, width) 29 | batch_size=1, # batch size 30 | device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu 31 | include=('torchscript', 'onnx', 'coreml'), # include formats 32 | half=False, # FP16 half-precision export 33 | inplace=False, # set YOLOv5 Detect() inplace=True 34 | train=False, # model.train() mode 35 | optimize=False, # TorchScript: optimize for mobile 36 | dynamic=False, # ONNX: dynamic axes 37 | simplify=False, # ONNX: simplify model 38 | opset_version=12, # ONNX: opset version 39 | ): 40 | t = time.time() 41 | include = [x.lower() for x in include] 42 | img_size *= 2 if len(img_size) == 1 else 1 # expand 43 | 44 | # Load PyTorch model 45 | device = select_device(device) 46 | assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0' 47 | model = attempt_load(weights, map_location=device) # load FP32 model 48 | labels = model.names 49 | 50 | # Input 51 | gs = int(max(model.stride)) # grid size (max stride) 52 | img_size = [check_img_size(x, gs) for x in img_size] # verify img_size are gs-multiples 53 | img = torch.zeros(batch_size, 3, *img_size).to(device) # image size(1,3,320,192) iDetection 54 | 55 | # Update model 56 | if half: 57 | img, model = img.half(), model.half() # to FP16 58 | model.train() if train else model.eval() # training mode = no Detect() layer grid construction 59 | for k, m in model.named_modules(): 60 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 61 | if isinstance(m, Conv): # assign export-friendly activations 62 | if isinstance(m.act, nn.Hardswish): 63 | m.act = Hardswish() 64 | elif isinstance(m.act, nn.SiLU): 65 | m.act = SiLU() 66 | elif isinstance(m, Detect): 67 | m.inplace = inplace 68 | m.onnx_dynamic = dynamic 69 | # m.forward = m.forward_export # assign forward (optional) 70 | 71 | for _ in range(2): 72 | y = model(img) # dry runs 73 | print(f"\n{colorstr('PyTorch:')} starting from {weights} ({file_size(weights):.1f} MB)") 74 | 75 | # TorchScript export ----------------------------------------------------------------------------------------------- 76 | if 'torchscript' in include or 'coreml' in include: 77 | prefix = colorstr('TorchScript:') 78 | try: 79 | print(f'\n{prefix} starting export with torch {torch.__version__}...') 80 | f = weights.replace('.pt', '.torchscript.pt') # filename 81 | ts = torch.jit.trace(model, img, strict=False) 82 | (optimize_for_mobile(ts) if optimize else ts).save(f) 83 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 84 | except Exception as e: 85 | print(f'{prefix} export failure: {e}') 86 | 87 | # ONNX export ------------------------------------------------------------------------------------------------------ 88 | if 'onnx' in include: 89 | prefix = colorstr('ONNX:') 90 | try: 91 | import onnx 92 | 93 | print(f'{prefix} starting export with onnx {onnx.__version__}...') 94 | f = weights.replace('.pt', '.onnx') # filename 95 | torch.onnx.export(model, img, f, verbose=False, opset_version=opset_version, 96 | training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL, 97 | do_constant_folding=not train, 98 | input_names=['images'], 99 | output_names=['output'], 100 | dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640) 101 | 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85) 102 | } if dynamic else None) 103 | 104 | # Checks 105 | model_onnx = onnx.load(f) # load onnx model 106 | onnx.checker.check_model(model_onnx) # check onnx model 107 | # print(onnx.helper.printable_graph(model_onnx.graph)) # print 108 | 109 | # Simplify 110 | if simplify: 111 | try: 112 | check_requirements(['onnx-simplifier']) 113 | import onnxsim 114 | 115 | print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...') 116 | model_onnx, check = onnxsim.simplify( 117 | model_onnx, 118 | dynamic_input_shape=dynamic, 119 | input_shapes={'images': list(img.shape)} if dynamic else None) 120 | assert check, 'assert check failed' 121 | onnx.save(model_onnx, f) 122 | except Exception as e: 123 | print(f'{prefix} simplifier failure: {e}') 124 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 125 | except Exception as e: 126 | print(f'{prefix} export failure: {e}') 127 | 128 | # CoreML export ---------------------------------------------------------------------------------------------------- 129 | if 'coreml' in include: 130 | prefix = colorstr('CoreML:') 131 | try: 132 | import coremltools as ct 133 | 134 | print(f'{prefix} starting export with coremltools {ct.__version__}...') 135 | assert train, 'CoreML exports should be placed in model.train() mode with `python export.py --train`' 136 | model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])]) 137 | f = weights.replace('.pt', '.mlmodel') # filename 138 | model.save(f) 139 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 140 | except Exception as e: 141 | print(f'{prefix} export failure: {e}') 142 | 143 | # Finish 144 | print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.') 145 | 146 | 147 | def parse_opt(): 148 | parser = argparse.ArgumentParser() 149 | parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path') 150 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image (height, width)') 151 | parser.add_argument('--batch-size', type=int, default=1, help='batch size') 152 | parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 153 | parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats') 154 | parser.add_argument('--half', action='store_true', help='FP16 half-precision export') 155 | parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True') 156 | parser.add_argument('--train', action='store_true', help='model.train() mode') 157 | parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile') 158 | parser.add_argument('--dynamic', action='store_true', help='ONNX: dynamic axes') 159 | parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model') 160 | parser.add_argument('--opset-version', type=int, default=12, help='ONNX: opset version') 161 | opt = parser.parse_args() 162 | return opt 163 | 164 | 165 | def main(opt): 166 | set_logging() 167 | print(colorstr('export: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) 168 | run(**vars(opt)) 169 | 170 | 171 | if __name__ == "__main__": 172 | opt = parse_opt() 173 | main(opt) 174 | -------------------------------------------------------------------------------- /utils/distill_fun.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import numpy as np 3 | def bbox_overlaps_batch(anchors, gt_boxes,imgsize): 4 | """ 5 | anchors: (N, 4) ndarray of float 6 | gt_boxes: (b, K, 5) ndarray of float 7 | overlaps: (N, K) ndarray of overlap between boxes and query_boxes 8 | """ 9 | batch_size = gt_boxes.size(0) 10 | 11 | 12 | if anchors.dim() == 2: 13 | 14 | N = anchors.size(0) 15 | K = gt_boxes.size(1) 16 | 17 | anchors = anchors.view(1, N, 4).expand(batch_size, N, 4).contiguous() 18 | gt_boxes = gt_boxes[:,:,2:].contiguous() # have2, 19 | 20 | 21 | gt_boxes_x = gt_boxes[:,:,2] - gt_boxes[:,:,0] + 1 22 | gt_boxes_y = gt_boxes[:,:,3] - gt_boxes[:,:,1] + 1 23 | gt_boxes_area = (gt_boxes_x * gt_boxes_y).view( batch_size,1, K) 24 | 25 | anchors_boxes_x = (anchors[:,:,2] - anchors[:,:,0] + 1) 26 | anchors_boxes_y = (anchors[:,:,3] - anchors[:,:,1] + 1) 27 | anchors_area = (anchors_boxes_x * anchors_boxes_y).view(batch_size, N, 1) 28 | 29 | gt_area_zero = (gt_boxes_x == 1) & (gt_boxes_y == 1) 30 | anchors_area_zero = (anchors_boxes_x == 1) & (anchors_boxes_y == 1) 31 | 32 | boxes = anchors.view(batch_size, N, 1, 4).expand(batch_size, N, K, 4) 33 | query_boxes = gt_boxes.view(batch_size, 1, K, 4).expand(batch_size, N, K, 4) 34 | 35 | iw = (torch.min(boxes[:,:,:,2], query_boxes[:,:,:,2]) - 36 | torch.max(boxes[:,:,:,0], query_boxes[:,:,:,0]) + 1) 37 | iw[iw < 0] = 0 38 | 39 | ih = (torch.min(boxes[:,:,:,3], query_boxes[:,:,:,3]) - 40 | torch.max(boxes[:,:,:,1], query_boxes[:,:,:,1]) + 1) 41 | ih[ih < 0] = 0 42 | ua = anchors_area + gt_boxes_area - (iw * ih) 43 | overlaps = iw * ih / ua 44 | 45 | # mask the overlap here. 46 | overlaps.masked_fill_(gt_area_zero.view(batch_size, 1, K).expand(batch_size, N, K), 0) 47 | overlaps.masked_fill_(anchors_area_zero.view(batch_size, N, 1).expand(batch_size, N, K), -1) 48 | 49 | elif anchors.dim() == 3: 50 | N = anchors.size(1) 51 | K = gt_boxes.size(1) 52 | 53 | if anchors.size(2) == 4: 54 | anchors = anchors[:,:,:4].contiguous() 55 | else: 56 | anchors = anchors[:,:,1:5].contiguous() 57 | 58 | gt_boxes = gt_boxes[:,:,:4].contiguous() 59 | 60 | gt_boxes_x = (gt_boxes[:,:,2] - gt_boxes[:,:,0] + 1) 61 | gt_boxes_y = (gt_boxes[:,:,3] - gt_boxes[:,:,1] + 1) 62 | gt_boxes_area = (gt_boxes_x * gt_boxes_y).view(batch_size, 1, K) 63 | 64 | anchors_boxes_x = (anchors[:,:,2] - anchors[:,:,0] + 1) 65 | anchors_boxes_y = (anchors[:,:,3] - anchors[:,:,1] + 1) 66 | anchors_area = (anchors_boxes_x * anchors_boxes_y).view(batch_size, N, 1) 67 | 68 | gt_area_zero = (gt_boxes_x == 1) & (gt_boxes_y == 1) 69 | anchors_area_zero = (anchors_boxes_x == 1) & (anchors_boxes_y == 1) 70 | 71 | boxes = anchors.view(batch_size, N, 1, 4).expand(batch_size, N, K, 4) 72 | query_boxes = gt_boxes.view(batch_size, 1, K, 4).expand(batch_size, N, K, 4) 73 | 74 | iw = (torch.min(boxes[:,:,:,2], query_boxes[:,:,:,2]) - 75 | torch.max(boxes[:,:,:,0], query_boxes[:,:,:,0]) + 1) 76 | iw[iw < 0] = 0 77 | 78 | ih = (torch.min(boxes[:,:,:,3], query_boxes[:,:,:,3]) - 79 | torch.max(boxes[:,:,:,1], query_boxes[:,:,:,1]) + 1) 80 | ih[ih < 0] = 0 81 | ua = anchors_area + gt_boxes_area - (iw * ih) 82 | 83 | overlaps = iw * ih / ua 84 | 85 | # mask the overlap here. 86 | overlaps.masked_fill_(gt_area_zero.view(batch_size, 1, K).expand(batch_size, N, K), 0) 87 | overlaps.masked_fill_(anchors_area_zero.view(batch_size, N, 1).expand(batch_size, N, K), -1) 88 | else: 89 | raise ValueError('anchors input dimension is not correct.') 90 | 91 | return overlaps 92 | def generate_anchors(base_size, anchors): 93 | """ 94 | Generate anchor (reference) windows by enumerating aspect ratios X 95 | scales wrt a reference (0, 0, 15, 15) window. 96 | - [3,6, 5,11, 7,14] # P3/8 97 | return shape=[3,4] 98 | """ 99 | 100 | base_anchor = np.array([1, 1, base_size, base_size]) - 1 101 | _, _, x_ctr, y_ctr = _whctrs(base_anchor) 102 | aim_ancher = [] 103 | for anchor in anchors: 104 | 105 | x1 = x_ctr - 0.5 * base_size * anchor[0] 106 | y1 = y_ctr - 0.5 * base_size * anchor[1] 107 | x2 = x_ctr + 0.5 * base_size * anchor[0] 108 | y2 = y_ctr + 0.5 * base_size * anchor[1] 109 | aim_ancher.append([x1,y1,x2,y2]) 110 | 111 | return np.array(aim_ancher) 112 | def _whctrs(anchor): 113 | """ 114 | Return width, height, x center, and y center for an anchor (window). 115 | """ 116 | 117 | w = anchor[2] - anchor[0] + 1 118 | h = anchor[3] - anchor[1] + 1 119 | x_ctr = anchor[0] + 0.5 * (w - 1) 120 | y_ctr = anchor[1] + 0.5 * (h - 1) 121 | return w, h, x_ctr, y_ctr 122 | 123 | def make_gt_boxes(gt_boxes,max_num_box,batch,imgsize): 124 | new_gt_boxes = [] 125 | for i in range(batch): 126 | boxes = gt_boxes[gt_boxes[:,0]==i] 127 | num_boxes = boxes.size(0) 128 | if num_boxesmax_iou_per_gt, 182 | dim = 2) 183 | mask_per_im +=mask_per_gt.cuda() 184 | mask_batch.append(mask_per_im) 185 | return mask_batch 186 | 187 | 188 | 189 | 190 | 191 | 192 | def compute_mask_loss(mask_batch,student_feature,teacher_feature,imitation_loss_weigth): 193 | mask_list = [] 194 | for mask in mask_batch: 195 | mask = (mask > 0).float().unsqueeze(0) 196 | mask_list.append(mask) 197 | mask_batch = torch.stack(mask_list, dim=0) 198 | norms = mask_batch.sum() * 2 199 | mask_batch_s = mask_batch.unsqueeze(4) 200 | #stu_feature_adap = feature_adap(student_feature) 201 | mask_batch_7 = torch.cat([mask_batch_s,mask_batch_s,mask_batch_s, 202 | mask_batch_s,mask_batch_s,mask_batch_s,mask_batch_s],dim=-1) 203 | sup_loss = (torch.pow(teacher_feature - student_feature, 2) * mask_batch_7).sum() / norms 204 | sup_loss = sup_loss * imitation_loss_weigth 205 | 206 | return sup_loss 207 | -------------------------------------------------------------------------------- /utils/loss.py: -------------------------------------------------------------------------------- 1 | # Loss functions 2 | 3 | import torch 4 | import torch.nn as nn 5 | 6 | from utils.metrics import bbox_iou 7 | from utils.torch_utils import is_parallel 8 | 9 | 10 | def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441 11 | # return positive, negative label smoothing BCE targets 12 | return 1.0 - 0.5 * eps, 0.5 * eps 13 | 14 | 15 | class BCEBlurWithLogitsLoss(nn.Module): 16 | # BCEwithLogitLoss() with reduced missing label effects. 17 | def __init__(self, alpha=0.05): 18 | super(BCEBlurWithLogitsLoss, self).__init__() 19 | self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss() 20 | self.alpha = alpha 21 | 22 | def forward(self, pred, true): 23 | loss = self.loss_fcn(pred, true) 24 | pred = torch.sigmoid(pred) # prob from logits 25 | dx = pred - true # reduce only missing label effects 26 | # dx = (pred - true).abs() # reduce missing label and false label effects 27 | alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4)) 28 | loss *= alpha_factor 29 | return loss.mean() 30 | 31 | 32 | class FocalLoss(nn.Module): 33 | # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) 34 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): 35 | super(FocalLoss, self).__init__() 36 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() 37 | self.gamma = gamma 38 | self.alpha = alpha 39 | self.reduction = loss_fcn.reduction 40 | self.loss_fcn.reduction = 'none' # required to apply FL to each element 41 | 42 | def forward(self, pred, true): 43 | loss = self.loss_fcn(pred, true) 44 | # p_t = torch.exp(-loss) 45 | # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability 46 | 47 | # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py 48 | pred_prob = torch.sigmoid(pred) # prob from logits 49 | p_t = true * pred_prob + (1 - true) * (1 - pred_prob) 50 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) 51 | modulating_factor = (1.0 - p_t) ** self.gamma 52 | loss *= alpha_factor * modulating_factor 53 | 54 | if self.reduction == 'mean': 55 | return loss.mean() 56 | elif self.reduction == 'sum': 57 | return loss.sum() 58 | else: # 'none' 59 | return loss 60 | 61 | 62 | class QFocalLoss(nn.Module): 63 | # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) 64 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): 65 | super(QFocalLoss, self).__init__() 66 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() 67 | self.gamma = gamma 68 | self.alpha = alpha 69 | self.reduction = loss_fcn.reduction 70 | self.loss_fcn.reduction = 'none' # required to apply FL to each element 71 | 72 | def forward(self, pred, true): 73 | loss = self.loss_fcn(pred, true) 74 | 75 | pred_prob = torch.sigmoid(pred) # prob from logits 76 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) 77 | modulating_factor = torch.abs(true - pred_prob) ** self.gamma 78 | loss *= alpha_factor * modulating_factor 79 | 80 | if self.reduction == 'mean': 81 | return loss.mean() 82 | elif self.reduction == 'sum': 83 | return loss.sum() 84 | else: # 'none' 85 | return loss 86 | 87 | 88 | class ComputeLoss: 89 | # Compute losses 90 | def __init__(self, model, autobalance=False): 91 | super(ComputeLoss, self).__init__() 92 | self.sort_obj_iou = False 93 | device = next(model.parameters()).device # get model device 94 | h = model.hyp # hyperparameters 95 | 96 | # Define criteria 97 | BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device)) 98 | BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device)) 99 | 100 | # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3 101 | self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets 102 | 103 | # Focal loss 104 | g = h['fl_gamma'] # focal loss gamma 105 | if g > 0: 106 | BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g) 107 | 108 | det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module 109 | self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7 110 | self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index 111 | self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance 112 | for k in 'na', 'nc', 'nl', 'anchors': 113 | setattr(self, k, getattr(det, k)) 114 | 115 | def __call__(self, p, targets): # predictions, targets, model 116 | device = targets.device 117 | lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device) 118 | tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets 119 | 120 | # Losses 121 | for i, pi in enumerate(p): # layer index, layer predictions 122 | b, a, gj, gi = indices[i] # image, anchor, gridy, gridx 123 | tobj = torch.zeros_like(pi[..., 0], device=device) # target obj 124 | 125 | n = b.shape[0] # number of targets 126 | if n: 127 | ps = pi[b, a, gj, gi] # prediction subset corresponding to targets 128 | 129 | # Regression 130 | pxy = ps[:, :2].sigmoid() * 2. - 0.5 131 | pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i] 132 | pbox = torch.cat((pxy, pwh), 1) # predicted box 133 | iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target) 134 | lbox += (1.0 - iou).mean() # iou loss 135 | 136 | # Objectness 137 | score_iou = iou.detach().clamp(0).type(tobj.dtype) 138 | if self.sort_obj_iou: 139 | sort_id = torch.argsort(score_iou) 140 | b, a, gj, gi, score_iou = b[sort_id], a[sort_id], gj[sort_id], gi[sort_id], score_iou[sort_id] 141 | tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * score_iou # iou ratio 142 | 143 | # Classification 144 | if self.nc > 1: # cls loss (only if multiple classes) 145 | t = torch.full_like(ps[:, 5:], self.cn, device=device) # targets 146 | t[range(n), tcls[i]] = self.cp 147 | lcls += self.BCEcls(ps[:, 5:], t) # BCE 148 | 149 | # Append targets to text file 150 | # with open('targets.txt', 'a') as file: 151 | # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)] 152 | 153 | obji = self.BCEobj(pi[..., 4], tobj) 154 | lobj += obji * self.balance[i] # obj loss 155 | if self.autobalance: 156 | self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item() 157 | 158 | if self.autobalance: 159 | self.balance = [x / self.balance[self.ssi] for x in self.balance] 160 | lbox *= self.hyp['box'] 161 | lobj *= self.hyp['obj'] 162 | lcls *= self.hyp['cls'] 163 | bs = tobj.shape[0] # batch size 164 | 165 | loss = lbox + lobj + lcls 166 | return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach() 167 | 168 | def build_targets(self, p, targets): 169 | # Build targets for compute_loss(), input targets(image,class,x,y,w,h) 170 | na, nt = self.na, targets.shape[0] # number of anchors, targets 171 | tcls, tbox, indices, anch = [], [], [], [] 172 | gain = torch.ones(7, device=targets.device) # normalized to gridspace gain 173 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) 174 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices 175 | 176 | g = 0.5 # bias 177 | off = torch.tensor([[0, 0], 178 | [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m 179 | # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm 180 | ], device=targets.device).float() * g # offsets 181 | 182 | for i in range(self.nl): 183 | anchors = self.anchors[i] 184 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain 185 | 186 | # Match targets to anchors 187 | t = targets * gain 188 | if nt: 189 | # Matches 190 | r = t[:, :, 4:6] / anchors[:, None] # wh ratio 191 | j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare 192 | # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) 193 | t = t[j] # filter 194 | 195 | # Offsets 196 | gxy = t[:, 2:4] # grid xy 197 | gxi = gain[[2, 3]] - gxy # inverse 198 | j, k = ((gxy % 1. < g) & (gxy > 1.)).T 199 | l, m = ((gxi % 1. < g) & (gxi > 1.)).T 200 | j = torch.stack((torch.ones_like(j), j, k, l, m)) 201 | t = t.repeat((5, 1, 1))[j] 202 | offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] 203 | else: 204 | t = targets[0] 205 | offsets = 0 206 | 207 | # Define 208 | b, c = t[:, :2].long().T # image, class 209 | gxy = t[:, 2:4] # grid xy 210 | gwh = t[:, 4:6] # grid wh 211 | gij = (gxy - offsets).long() 212 | gi, gj = gij.T # grid xy indices 213 | 214 | # Append 215 | a = t[:, 6].long() # anchor indices 216 | indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices 217 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box 218 | anch.append(anchors[a]) # anchors 219 | tcls.append(c) # class 220 | 221 | return tcls, tbox, indices, anch 222 | -------------------------------------------------------------------------------- /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_synchronized 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 | model = attempt_load(weights, map_location=device) # load FP32 model 68 | stride = int(model.stride.max()) # model stride 69 | imgsz = check_img_size(imgsz, s=stride) # check image size 70 | names = model.module.names if hasattr(model, 'module') else model.names # get class names 71 | if half: 72 | model.half() # to FP16 73 | 74 | # Second-stage classifier 75 | classify = False 76 | if classify: 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 | 80 | # Dataloader 81 | if webcam: 82 | view_img = check_imshow() 83 | cudnn.benchmark = True # set True to speed up constant image size inference 84 | dataset = LoadStreams(source, img_size=imgsz, stride=stride) 85 | bs = len(dataset) # batch_size 86 | else: 87 | dataset = LoadImages(source, img_size=imgsz, stride=stride) 88 | bs = 1 # batch_size 89 | vid_path, vid_writer = [None] * bs, [None] * bs 90 | 91 | # Run inference 92 | if device.type != 'cpu': 93 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once 94 | t0 = time.time() 95 | for path, img, im0s, vid_cap in dataset: 96 | img = torch.from_numpy(img).to(device) 97 | img = img.half() if half else img.float() # uint8 to fp16/32 98 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 99 | if img.ndimension() == 3: 100 | img = img.unsqueeze(0) 101 | 102 | # Inference 103 | t1 = time_synchronized() 104 | pred = model(img, 105 | augment=augment, 106 | visualize=increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False)[0] 107 | 108 | # Apply NMS 109 | pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) 110 | t2 = time_synchronized() 111 | 112 | # Apply Classifier 113 | if classify: 114 | pred = apply_classifier(pred, modelc, img, im0s) 115 | 116 | # Process detections 117 | for i, det in enumerate(pred): # detections per image 118 | if webcam: # batch_size >= 1 119 | p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count 120 | else: 121 | p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0) 122 | 123 | p = Path(p) # to Path 124 | save_path = str(save_dir / p.name) # img.jpg 125 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt 126 | s += '%gx%g ' % img.shape[2:] # print string 127 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh 128 | imc = im0.copy() if save_crop else im0 # for save_crop 129 | if len(det): 130 | # Rescale boxes from img_size to im0 size 131 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 132 | 133 | # Print results 134 | for c in det[:, -1].unique(): 135 | n = (det[:, -1] == c).sum() # detections per class 136 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string 137 | 138 | # Write results 139 | for *xyxy, conf, cls in reversed(det): 140 | if save_txt: # Write to file 141 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 142 | line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format 143 | with open(txt_path + '.txt', 'a') as f: 144 | f.write(('%g ' * len(line)).rstrip() % line + '\n') 145 | 146 | if save_img or save_crop or view_img: # Add bbox to image 147 | c = int(cls) # integer class 148 | label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') 149 | plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness) 150 | if save_crop: 151 | save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) 152 | 153 | # Print time (inference + NMS) 154 | print(f'{s}Done. ({t2 - t1:.3f}s)') 155 | 156 | # Stream results 157 | if view_img: 158 | cv2.imshow(str(p), im0) 159 | cv2.waitKey(1) # 1 millisecond 160 | 161 | # Save results (image with detections) 162 | if save_img: 163 | if dataset.mode == 'image': 164 | cv2.imwrite(save_path, im0) 165 | else: # 'video' or 'stream' 166 | if vid_path[i] != save_path: # new video 167 | vid_path[i] = save_path 168 | if isinstance(vid_writer[i], cv2.VideoWriter): 169 | vid_writer[i].release() # release previous video writer 170 | if vid_cap: # video 171 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 172 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 173 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 174 | else: # stream 175 | fps, w, h = 30, im0.shape[1], im0.shape[0] 176 | save_path += '.mp4' 177 | vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) 178 | vid_writer[i].write(im0) 179 | 180 | if save_txt or save_img: 181 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' 182 | print(f"Results saved to {save_dir}{s}") 183 | 184 | if update: 185 | strip_optimizer(weights) # update model (to fix SourceChangeWarning) 186 | 187 | print(f'Done. ({time.time() - t0:.3f}s)') 188 | 189 | 190 | def parse_opt(): 191 | parser = argparse.ArgumentParser() 192 | parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)') 193 | parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam') 194 | parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') 195 | parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold') 196 | parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold') 197 | parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image') 198 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 199 | parser.add_argument('--view-img', action='store_true', help='show results') 200 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 201 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') 202 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes') 203 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos') 204 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') 205 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 206 | parser.add_argument('--augment', action='store_true', help='augmented inference') 207 | parser.add_argument('--visualize', action='store_true', help='visualize features') 208 | parser.add_argument('--update', action='store_true', help='update all models') 209 | parser.add_argument('--project', default='runs/detect', help='save results to project/name') 210 | parser.add_argument('--name', default='exp', help='save results to project/name') 211 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') 212 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') 213 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') 214 | parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') 215 | parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') 216 | opt = parser.parse_args() 217 | return opt 218 | 219 | 220 | def main(opt): 221 | print(colorstr('detect: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) 222 | check_requirements(exclude=('tensorboard', 'thop')) 223 | run(**vars(opt)) 224 | 225 | 226 | if __name__ == "__main__": 227 | opt = parse_opt() 228 | main(opt) 229 | -------------------------------------------------------------------------------- /utils/augmentations.py: -------------------------------------------------------------------------------- 1 | # YOLOv5 image augmentation functions 2 | 3 | import logging 4 | import random 5 | 6 | import cv2 7 | import math 8 | import numpy as np 9 | 10 | from utils.general import colorstr, segment2box, resample_segments, check_version 11 | from utils.metrics import bbox_ioa 12 | 13 | 14 | class Albumentations: 15 | # YOLOv5 Albumentations class (optional, only used if package is installed) 16 | def __init__(self): 17 | self.transform = None 18 | try: 19 | import albumentations as A 20 | check_version(A.__version__, '1.0.2') # version requirement 21 | 22 | self.transform = A.Compose([ 23 | A.Blur(p=0.1), 24 | A.MedianBlur(p=0.1), 25 | A.ToGray(p=0.01)], 26 | bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels'])) 27 | 28 | logging.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p)) 29 | except ImportError: # package not installed, skip 30 | pass 31 | except Exception as e: 32 | logging.info(colorstr('albumentations: ') + f'{e}') 33 | 34 | def __call__(self, im, labels, p=1.0): 35 | if self.transform and random.random() < p: 36 | new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed 37 | im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])]) 38 | return im, labels 39 | 40 | 41 | def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5): 42 | # HSV color-space augmentation 43 | if hgain or sgain or vgain: 44 | r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains 45 | hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV)) 46 | dtype = im.dtype # uint8 47 | 48 | x = np.arange(0, 256, dtype=r.dtype) 49 | lut_hue = ((x * r[0]) % 180).astype(dtype) 50 | lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) 51 | lut_val = np.clip(x * r[2], 0, 255).astype(dtype) 52 | 53 | im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) 54 | cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed 55 | 56 | 57 | def hist_equalize(im, clahe=True, bgr=False): 58 | # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255 59 | yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV) 60 | if clahe: 61 | c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) 62 | yuv[:, :, 0] = c.apply(yuv[:, :, 0]) 63 | else: 64 | yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram 65 | return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB 66 | 67 | 68 | def replicate(im, labels): 69 | # Replicate labels 70 | h, w = im.shape[:2] 71 | boxes = labels[:, 1:].astype(int) 72 | x1, y1, x2, y2 = boxes.T 73 | s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels) 74 | for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices 75 | x1b, y1b, x2b, y2b = boxes[i] 76 | bh, bw = y2b - y1b, x2b - x1b 77 | yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y 78 | x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh] 79 | im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax] 80 | labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0) 81 | 82 | return im, labels 83 | 84 | 85 | def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32): 86 | # Resize and pad image while meeting stride-multiple constraints 87 | shape = im.shape[:2] # current shape [height, width] 88 | if isinstance(new_shape, int): 89 | new_shape = (new_shape, new_shape) 90 | 91 | # Scale ratio (new / old) 92 | r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) 93 | if not scaleup: # only scale down, do not scale up (for better val mAP) 94 | r = min(r, 1.0) 95 | 96 | # Compute padding 97 | ratio = r, r # width, height ratios 98 | new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) 99 | dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding 100 | if auto: # minimum rectangle 101 | dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding 102 | elif scaleFill: # stretch 103 | dw, dh = 0.0, 0.0 104 | new_unpad = (new_shape[1], new_shape[0]) 105 | ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios 106 | 107 | dw /= 2 # divide padding into 2 sides 108 | dh /= 2 109 | 110 | if shape[::-1] != new_unpad: # resize 111 | im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR) 112 | top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) 113 | left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) 114 | im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border 115 | return im, ratio, (dw, dh) 116 | 117 | 118 | def random_perspective(im, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0, 119 | border=(0, 0)): 120 | # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10)) 121 | # targets = [cls, xyxy] 122 | 123 | height = im.shape[0] + border[0] * 2 # shape(h,w,c) 124 | width = im.shape[1] + border[1] * 2 125 | 126 | # Center 127 | C = np.eye(3) 128 | C[0, 2] = -im.shape[1] / 2 # x translation (pixels) 129 | C[1, 2] = -im.shape[0] / 2 # y translation (pixels) 130 | 131 | # Perspective 132 | P = np.eye(3) 133 | P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y) 134 | P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x) 135 | 136 | # Rotation and Scale 137 | R = np.eye(3) 138 | a = random.uniform(-degrees, degrees) 139 | # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations 140 | s = random.uniform(1 - scale, 1 + scale) 141 | # s = 2 ** random.uniform(-scale, scale) 142 | R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s) 143 | 144 | # Shear 145 | S = np.eye(3) 146 | S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg) 147 | S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg) 148 | 149 | # Translation 150 | T = np.eye(3) 151 | T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels) 152 | T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels) 153 | 154 | # Combined rotation matrix 155 | M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT 156 | if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed 157 | if perspective: 158 | im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114)) 159 | else: # affine 160 | im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114)) 161 | 162 | # Visualize 163 | # import matplotlib.pyplot as plt 164 | # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel() 165 | # ax[0].imshow(im[:, :, ::-1]) # base 166 | # ax[1].imshow(im2[:, :, ::-1]) # warped 167 | 168 | # Transform label coordinates 169 | n = len(targets) 170 | if n: 171 | use_segments = any(x.any() for x in segments) 172 | new = np.zeros((n, 4)) 173 | if use_segments: # warp segments 174 | segments = resample_segments(segments) # upsample 175 | for i, segment in enumerate(segments): 176 | xy = np.ones((len(segment), 3)) 177 | xy[:, :2] = segment 178 | xy = xy @ M.T # transform 179 | xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine 180 | 181 | # clip 182 | new[i] = segment2box(xy, width, height) 183 | 184 | else: # warp boxes 185 | xy = np.ones((n * 4, 3)) 186 | xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1 187 | xy = xy @ M.T # transform 188 | xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine 189 | 190 | # create new boxes 191 | x = xy[:, [0, 2, 4, 6]] 192 | y = xy[:, [1, 3, 5, 7]] 193 | new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T 194 | 195 | # clip 196 | new[:, [0, 2]] = new[:, [0, 2]].clip(0, width) 197 | new[:, [1, 3]] = new[:, [1, 3]].clip(0, height) 198 | 199 | # filter candidates 200 | i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10) 201 | targets = targets[i] 202 | targets[:, 1:5] = new[i] 203 | 204 | return im, targets 205 | 206 | 207 | def copy_paste(im, labels, segments, p=0.5): 208 | # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy) 209 | n = len(segments) 210 | if p and n: 211 | h, w, c = im.shape # height, width, channels 212 | im_new = np.zeros(im.shape, np.uint8) 213 | for j in random.sample(range(n), k=round(p * n)): 214 | l, s = labels[j], segments[j] 215 | box = w - l[3], l[2], w - l[1], l[4] 216 | ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area 217 | if (ioa < 0.30).all(): # allow 30% obscuration of existing labels 218 | labels = np.concatenate((labels, [[l[0], *box]]), 0) 219 | segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1)) 220 | cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED) 221 | 222 | result = cv2.bitwise_and(src1=im, src2=im_new) 223 | result = cv2.flip(result, 1) # augment segments (flip left-right) 224 | i = result > 0 # pixels to replace 225 | # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch 226 | im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug 227 | 228 | return im, labels, segments 229 | 230 | 231 | def cutout(im, labels, p=0.5): 232 | # Applies image cutout augmentation https://arxiv.org/abs/1708.04552 233 | if random.random() < p: 234 | h, w = im.shape[:2] 235 | scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction 236 | for s in scales: 237 | mask_h = random.randint(1, int(h * s)) # create random masks 238 | mask_w = random.randint(1, int(w * s)) 239 | 240 | # box 241 | xmin = max(0, random.randint(0, w) - mask_w // 2) 242 | ymin = max(0, random.randint(0, h) - mask_h // 2) 243 | xmax = min(w, xmin + mask_w) 244 | ymax = min(h, ymin + mask_h) 245 | 246 | # apply random color mask 247 | im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)] 248 | 249 | # return unobscured labels 250 | if len(labels) and s > 0.03: 251 | box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32) 252 | ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area 253 | labels = labels[ioa < 0.60] # remove >60% obscured labels 254 | 255 | return labels 256 | 257 | 258 | def mixup(im, labels, im2, labels2): 259 | # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf 260 | r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0 261 | im = (im * r + im2 * (1 - r)).astype(np.uint8) 262 | labels = np.concatenate((labels, labels2), 0) 263 | return im, labels 264 | 265 | 266 | def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n) 267 | # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio 268 | w1, h1 = box1[2] - box1[0], box1[3] - box1[1] 269 | w2, h2 = box2[2] - box2[0], box2[3] - box2[1] 270 | ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio 271 | return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates 272 | -------------------------------------------------------------------------------- /utils/torch_utils.py: -------------------------------------------------------------------------------- 1 | # YOLOv5 PyTorch utils 2 | 3 | import datetime 4 | import logging 5 | import os 6 | import platform 7 | import subprocess 8 | import time 9 | from contextlib import contextmanager 10 | from copy import deepcopy 11 | from pathlib import Path 12 | 13 | import math 14 | import torch 15 | import torch.backends.cudnn as cudnn 16 | import torch.distributed as dist 17 | import torch.nn as nn 18 | import torch.nn.functional as F 19 | import torchvision 20 | 21 | try: 22 | import thop # for FLOPs computation 23 | except ImportError: 24 | thop = None 25 | logger = logging.getLogger(__name__) 26 | 27 | 28 | @contextmanager 29 | def torch_distributed_zero_first(local_rank: int): 30 | """ 31 | Decorator to make all processes in distributed training wait for each local_master to do something. 32 | """ 33 | if local_rank not in [-1, 0]: 34 | dist.barrier() 35 | yield 36 | if local_rank == 0: 37 | dist.barrier() 38 | 39 | 40 | def init_torch_seeds(seed=0): 41 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html 42 | torch.manual_seed(seed) 43 | if seed == 0: # slower, more reproducible 44 | cudnn.benchmark, cudnn.deterministic = False, True 45 | else: # faster, less reproducible 46 | cudnn.benchmark, cudnn.deterministic = True, False 47 | 48 | 49 | def date_modified(path=__file__): 50 | # return human-readable file modification date, i.e. '2021-3-26' 51 | t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime) 52 | return f'{t.year}-{t.month}-{t.day}' 53 | 54 | 55 | def git_describe(path=Path(__file__).parent): # path must be a directory 56 | # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe 57 | s = f'git -C {path} describe --tags --long --always' 58 | try: 59 | return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1] 60 | except subprocess.CalledProcessError as e: 61 | return '' # not a git repository 62 | 63 | 64 | def select_device(device='', batch_size=None): 65 | # device = 'cpu' or '0' or '0,1,2,3' 66 | s = f'YOLOv5 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string 67 | device = str(device).strip().lower().replace('cuda:', '') # to string, 'cuda:0' to '0' 68 | cpu = device == 'cpu' 69 | if cpu: 70 | os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False 71 | elif device: # non-cpu device requested 72 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable 73 | assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability 74 | 75 | cuda = not cpu and torch.cuda.is_available() 76 | if cuda: 77 | devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7 78 | n = len(devices) # device count 79 | if n > 1 and batch_size: # check batch_size is divisible by device_count 80 | assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' 81 | space = ' ' * (len(s) + 1) 82 | for i, d in enumerate(devices): 83 | p = torch.cuda.get_device_properties(i) 84 | s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB 85 | else: 86 | s += 'CPU\n' 87 | 88 | logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe 89 | return torch.device('cuda:0' if cuda else 'cpu') 90 | 91 | 92 | def time_synchronized(): 93 | # pytorch-accurate time 94 | if torch.cuda.is_available(): 95 | torch.cuda.synchronize() 96 | return time.time() 97 | 98 | 99 | def profile(x, ops, n=100, device=None): 100 | # profile a pytorch module or list of modules. Example usage: 101 | # x = torch.randn(16, 3, 640, 640) # input 102 | # m1 = lambda x: x * torch.sigmoid(x) 103 | # m2 = nn.SiLU() 104 | # profile(x, [m1, m2], n=100) # profile speed over 100 iterations 105 | 106 | device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') 107 | x = x.to(device) 108 | x.requires_grad = True 109 | print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '') 110 | print(f"\n{'Params':>12s}{'GFLOPs':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}") 111 | for m in ops if isinstance(ops, list) else [ops]: 112 | m = m.to(device) if hasattr(m, 'to') else m # device 113 | m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type 114 | dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward 115 | try: 116 | flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs 117 | except: 118 | flops = 0 119 | 120 | for _ in range(n): 121 | t[0] = time_synchronized() 122 | y = m(x) 123 | t[1] = time_synchronized() 124 | try: 125 | _ = y.sum().backward() 126 | t[2] = time_synchronized() 127 | except: # no backward method 128 | t[2] = float('nan') 129 | dtf += (t[1] - t[0]) * 1000 / n # ms per op forward 130 | dtb += (t[2] - t[1]) * 1000 / n # ms per op backward 131 | 132 | s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' 133 | s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list' 134 | p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters 135 | print(f'{p:12}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}') 136 | 137 | 138 | def is_parallel(model): 139 | # Returns True if model is of type DP or DDP 140 | return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) 141 | 142 | 143 | def de_parallel(model): 144 | # De-parallelize a model: returns single-GPU model if model is of type DP or DDP 145 | return model.module if is_parallel(model) else model 146 | 147 | 148 | def intersect_dicts(da, db, exclude=()): 149 | # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values 150 | return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape} 151 | 152 | 153 | def initialize_weights(model): 154 | for m in model.modules(): 155 | t = type(m) 156 | if t is nn.Conv2d: 157 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 158 | elif t is nn.BatchNorm2d: 159 | m.eps = 1e-3 160 | m.momentum = 0.03 161 | elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]: 162 | m.inplace = True 163 | 164 | 165 | def find_modules(model, mclass=nn.Conv2d): 166 | # Finds layer indices matching module class 'mclass' 167 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] 168 | 169 | 170 | def sparsity(model): 171 | # Return global model sparsity 172 | a, b = 0., 0. 173 | for p in model.parameters(): 174 | a += p.numel() 175 | b += (p == 0).sum() 176 | return b / a 177 | 178 | 179 | def prune(model, amount=0.3): 180 | # Prune model to requested global sparsity 181 | import torch.nn.utils.prune as prune 182 | print('Pruning model... ', end='') 183 | for name, m in model.named_modules(): 184 | if isinstance(m, nn.Conv2d): 185 | prune.l1_unstructured(m, name='weight', amount=amount) # prune 186 | prune.remove(m, 'weight') # make permanent 187 | print(' %.3g global sparsity' % sparsity(model)) 188 | 189 | 190 | def fuse_conv_and_bn(conv, bn): 191 | # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ 192 | fusedconv = nn.Conv2d(conv.in_channels, 193 | conv.out_channels, 194 | kernel_size=conv.kernel_size, 195 | stride=conv.stride, 196 | padding=conv.padding, 197 | groups=conv.groups, 198 | bias=True).requires_grad_(False).to(conv.weight.device) 199 | 200 | # prepare filters 201 | w_conv = conv.weight.clone().view(conv.out_channels, -1) 202 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) 203 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape)) 204 | 205 | # prepare spatial bias 206 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias 207 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) 208 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) 209 | 210 | return fusedconv 211 | 212 | 213 | def model_info(model, verbose=False, img_size=640): 214 | # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320] 215 | n_p = sum(x.numel() for x in model.parameters()) # number parameters 216 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients 217 | if verbose: 218 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma')) 219 | for i, (name, p) in enumerate(model.named_parameters()): 220 | name = name.replace('module_list.', '') 221 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' % 222 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) 223 | 224 | try: # FLOPs 225 | from thop import profile 226 | stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 227 | img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input 228 | flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPs 229 | img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float 230 | fs = ', %.1f GFLOPs' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPs 231 | except (ImportError, Exception): 232 | fs = '' 233 | 234 | logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") 235 | 236 | 237 | def load_classifier(name='resnet101', n=2): 238 | # Loads a pretrained model reshaped to n-class output 239 | model = torchvision.models.__dict__[name](pretrained=True) 240 | 241 | # ResNet model properties 242 | # input_size = [3, 224, 224] 243 | # input_space = 'RGB' 244 | # input_range = [0, 1] 245 | # mean = [0.485, 0.456, 0.406] 246 | # std = [0.229, 0.224, 0.225] 247 | 248 | # Reshape output to n classes 249 | filters = model.fc.weight.shape[1] 250 | model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True) 251 | model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True) 252 | model.fc.out_features = n 253 | return model 254 | 255 | 256 | def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) 257 | # scales img(bs,3,y,x) by ratio constrained to gs-multiple 258 | if ratio == 1.0: 259 | return img 260 | else: 261 | h, w = img.shape[2:] 262 | s = (int(h * ratio), int(w * ratio)) # new size 263 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize 264 | if not same_shape: # pad/crop img 265 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)] 266 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean 267 | 268 | 269 | def copy_attr(a, b, include=(), exclude=()): 270 | # Copy attributes from b to a, options to only include [...] and to exclude [...] 271 | for k, v in b.__dict__.items(): 272 | if (len(include) and k not in include) or k.startswith('_') or k in exclude: 273 | continue 274 | else: 275 | setattr(a, k, v) 276 | 277 | 278 | class ModelEMA: 279 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models 280 | Keep a moving average of everything in the model state_dict (parameters and buffers). 281 | This is intended to allow functionality like 282 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage 283 | A smoothed version of the weights is necessary for some training schemes to perform well. 284 | This class is sensitive where it is initialized in the sequence of model init, 285 | GPU assignment and distributed training wrappers. 286 | """ 287 | 288 | def __init__(self, model, decay=0.9999, updates=0): 289 | # Create EMA 290 | self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA 291 | # if next(model.parameters()).device.type != 'cpu': 292 | # self.ema.half() # FP16 EMA 293 | self.updates = updates # number of EMA updates 294 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs) 295 | for p in self.ema.parameters(): 296 | p.requires_grad_(False) 297 | 298 | def update(self, model): 299 | # Update EMA parameters 300 | with torch.no_grad(): 301 | self.updates += 1 302 | d = self.decay(self.updates) 303 | 304 | msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict 305 | for k, v in self.ema.state_dict().items(): 306 | if v.dtype.is_floating_point: 307 | v *= d 308 | v += (1. - d) * msd[k].detach() 309 | 310 | def update_attr(self, model, include=(), exclude=('process_group', 'reducer')): 311 | # Update EMA attributes 312 | copy_attr(self.ema, model, include, exclude) 313 | --------------------------------------------------------------------------------