├── 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_modify.yaml ├── experimental.py └── yolo.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 ├── loss.py ├── augmentations.py ├── torch_utils.py └── metrics.py ├── 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 ├── README.md ├── requirements.txt ├── Dockerfile ├── CONTRIBUTING.md ├── 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 | -------------------------------------------------------------------------------- /data/images/bus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hongyu-Yue/yoloV5_modify_smalltarget/HEAD/data/images/bus.jpg -------------------------------------------------------------------------------- /data/images/zidane.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hongyu-Yue/yoloV5_modify_smalltarget/HEAD/data/images/zidane.jpg -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 修改了网络NECK部分增加小目标识别能力。 2 | 修改了DETECT.py函数,针对分辨率非常大的航拍图像,使用图形分割的办法以检测时间换准确率。 3 | 具体思路参考:https://blog.csdn.net/weixin_56184890/article/details/119840555?spm=1001.2014.3001.5501 4 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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.3 31 | thop # FLOPs computation 32 | -------------------------------------------------------------------------------- /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/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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /models/yolov5l_modify.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [5,6, 8,14, 15,11] #4 9 | - [10,13, 16,30, 33,23] # P3/8 10 | - [30,61, 62,45, 59,119] # P4/16 11 | - [116,90, 156,198, 373,326] # P5/32 12 | 13 | # YOLOv5 backbone 14 | backbone: 15 | # [from, number, module, args] 16 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 17 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 18 | [-1, 3, BottleneckCSP, [128]], #160*160 19 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 20 | [-1, 9, BottleneckCSP, [256]], #80*80 21 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 22 | [-1, 9, BottleneckCSP, [512]], #40*40 23 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 24 | [-1, 1, SPP, [1024, [5, 9, 13]]], 25 | [-1, 3, BottleneckCSP, [1024, False]], # 9 20*20 26 | ] 27 | 28 | # YOLOv5 head 29 | head: 30 | [[-1, 1, Conv, [512, 1, 1]], #20*20 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], #40*40 32 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 40*40 33 | [-1, 3, BottleneckCSP, [512, False]], # 13 40*40 34 | 35 | [-1, 1, Conv, [512, 1, 1]], #40*40 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 80*80 38 | [-1, 3, BottleneckCSP, [512, False]], # 17 (P3/8-small) 80*80 39 | 40 | [-1, 1, Conv, [256, 1, 1]], #18 80*80 41 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], #19 160*160 42 | [[-1, 2], 1, Concat, [1]], #20 cat backbone p2 160*160 43 | [-1, 3, BottleneckCSP, [256, False]], #21 160*160 44 | 45 | [-1, 1, Conv, [256, 3, 2]], #22 80*80 46 | [[-1, 18], 1, Concat, [1]], #23 80*80 47 | [-1, 3, BottleneckCSP, [256, False]], #24 80*80 48 | 49 | [-1, 1, Conv, [256, 3, 2]], #25 40*40 50 | [[-1, 14], 1, Concat, [1]], # 26 cat head P4 40*40 51 | [-1, 3, BottleneckCSP, [512, False]], # 27 (P4/16-medium) 40*40 52 | 53 | [-1, 1, Conv, [512, 3, 2]], #28 20*20 54 | [[-1, 10], 1, Concat, [1]], #29 cat head P5 #20*20 55 | [-1, 3, BottleneckCSP, [1024, False]], # 30 (P5/32-large) 20*20 56 | 57 | [[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(p2, P3, P4, P5) 58 | ] -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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().__init__() 16 | c_ = int(c2 * e) # hidden channels 17 | self.cv1 = Conv(c1, c_, (1, k), (1, s)) 18 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) 19 | self.add = shortcut and c1 == c2 20 | 21 | def forward(self, x): 22 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) 23 | 24 | 25 | class Sum(nn.Module): 26 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 27 | def __init__(self, n, weight=False): # n: number of inputs 28 | super().__init__() 29 | self.weight = weight # apply weights boolean 30 | self.iter = range(n - 1) # iter object 31 | if weight: 32 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights 33 | 34 | def forward(self, x): 35 | y = x[0] # no weight 36 | if self.weight: 37 | w = torch.sigmoid(self.w) * 2 38 | for i in self.iter: 39 | y = y + x[i + 1] * w[i] 40 | else: 41 | for i in self.iter: 42 | y = y + x[i + 1] 43 | return y 44 | 45 | 46 | class GhostConv(nn.Module): 47 | # Ghost Convolution https://github.com/huawei-noah/ghostnet 48 | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups 49 | super().__init__() 50 | c_ = c2 // 2 # hidden channels 51 | self.cv1 = Conv(c1, c_, k, s, None, g, act) 52 | self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) 53 | 54 | def forward(self, x): 55 | y = self.cv1(x) 56 | return torch.cat([y, self.cv2(y)], 1) 57 | 58 | 59 | class GhostBottleneck(nn.Module): 60 | # Ghost Bottleneck https://github.com/huawei-noah/ghostnet 61 | def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride 62 | super().__init__() 63 | c_ = c2 // 2 64 | self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw 65 | DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw 66 | GhostConv(c_, c2, 1, 1, act=False)) # pw-linear 67 | self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), 68 | Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() 69 | 70 | def forward(self, x): 71 | return self.conv(x) + self.shortcut(x) 72 | 73 | 74 | class MixConv2d(nn.Module): 75 | # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595 76 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): 77 | super().__init__() 78 | groups = len(k) 79 | if equal_ch: # equal c_ per group 80 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices 81 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels 82 | else: # equal weight.numel() per group 83 | b = [c2] + [0] * groups 84 | a = np.eye(groups + 1, groups, k=-1) 85 | a -= np.roll(a, 1, axis=1) 86 | a *= np.array(k) ** 2 87 | a[0] = 1 88 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b 89 | 90 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)]) 91 | self.bn = nn.BatchNorm2d(c2) 92 | self.act = nn.LeakyReLU(0.1, inplace=True) 93 | 94 | def forward(self, x): 95 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) 96 | 97 | 98 | class Ensemble(nn.ModuleList): 99 | # Ensemble of models 100 | def __init__(self): 101 | super().__init__() 102 | 103 | def forward(self, x, augment=False, profile=False, visualize=False): 104 | y = [] 105 | for module in self: 106 | y.append(module(x, augment, profile, visualize)[0]) 107 | # y = torch.stack(y).max(0)[0] # max ensemble 108 | # y = torch.stack(y).mean(0) # mean ensemble 109 | y = torch.cat(y, 1) # nms ensemble 110 | return y, None # inference, train output 111 | 112 | 113 | def attempt_load(weights, map_location=None, inplace=True): 114 | from models.yolo import Detect, Model 115 | 116 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a 117 | model = Ensemble() 118 | for w in weights if isinstance(weights, list) else [weights]: 119 | ckpt = torch.load(attempt_download(w), map_location=map_location) # load 120 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model 121 | 122 | # Compatibility updates 123 | for m in model.modules(): 124 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]: 125 | m.inplace = inplace # pytorch 1.7.0 compatibility 126 | elif type(m) is Conv: 127 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 128 | 129 | if len(model) == 1: 130 | return model[-1] # return model 131 | else: 132 | print(f'Ensemble created with {weights}\n') 133 | for k in ['names']: 134 | setattr(model, k, getattr(model[-1], k)) 135 | model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride 136 | return model # return ensemble 137 | -------------------------------------------------------------------------------- /hubconf.py: -------------------------------------------------------------------------------- 1 | """YOLOv5 PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5/ 2 | 3 | Usage: 4 | import torch 5 | model = torch.hub.load('ultralytics/yolov5', 'yolov5s') 6 | """ 7 | 8 | import torch 9 | 10 | 11 | def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None): 12 | """Creates a specified YOLOv5 model 13 | 14 | Arguments: 15 | name (str): name of model, i.e. 'yolov5s' 16 | pretrained (bool): load pretrained weights into the model 17 | channels (int): number of input channels 18 | classes (int): number of model classes 19 | autoshape (bool): apply YOLOv5 .autoshape() wrapper to model 20 | verbose (bool): print all information to screen 21 | device (str, torch.device, None): device to use for model parameters 22 | 23 | Returns: 24 | YOLOv5 pytorch model 25 | """ 26 | from pathlib import Path 27 | 28 | from models.yolo import Model, attempt_load 29 | from utils.general import check_requirements, set_logging 30 | from utils.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 export_torchscript(model, img, file, optimize): 28 | # TorchScript model export 29 | prefix = colorstr('TorchScript:') 30 | try: 31 | print(f'\n{prefix} starting export with torch {torch.__version__}...') 32 | f = file.with_suffix('.torchscript.pt') 33 | ts = torch.jit.trace(model, img, strict=False) 34 | (optimize_for_mobile(ts) if optimize else ts).save(f) 35 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 36 | return ts 37 | except Exception as e: 38 | print(f'{prefix} export failure: {e}') 39 | 40 | 41 | def export_onnx(model, img, file, opset_version, train, dynamic, simplify): 42 | # ONNX model export 43 | prefix = colorstr('ONNX:') 44 | try: 45 | check_requirements(('onnx', 'onnx-simplifier')) 46 | import onnx 47 | 48 | print(f'\n{prefix} starting export with onnx {onnx.__version__}...') 49 | f = file.with_suffix('.onnx') 50 | torch.onnx.export(model, img, f, verbose=False, opset_version=opset_version, 51 | training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL, 52 | do_constant_folding=not train, 53 | input_names=['images'], 54 | output_names=['output'], 55 | dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640) 56 | 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85) 57 | } if dynamic else None) 58 | 59 | # Checks 60 | model_onnx = onnx.load(f) # load onnx model 61 | onnx.checker.check_model(model_onnx) # check onnx model 62 | # print(onnx.helper.printable_graph(model_onnx.graph)) # print 63 | 64 | # Simplify 65 | if simplify: 66 | try: 67 | import onnxsim 68 | 69 | print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...') 70 | model_onnx, check = onnxsim.simplify( 71 | model_onnx, 72 | dynamic_input_shape=dynamic, 73 | input_shapes={'images': list(img.shape)} if dynamic else None) 74 | assert check, 'assert check failed' 75 | onnx.save(model_onnx, f) 76 | except Exception as e: 77 | print(f'{prefix} simplifier failure: {e}') 78 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 79 | except Exception as e: 80 | print(f'{prefix} export failure: {e}') 81 | 82 | 83 | def export_coreml(model, img, file): 84 | # CoreML model export 85 | prefix = colorstr('CoreML:') 86 | try: 87 | import coremltools as ct 88 | 89 | print(f'\n{prefix} starting export with coremltools {ct.__version__}...') 90 | f = file.with_suffix('.mlmodel') 91 | model.train() # CoreML exports should be placed in model.train() mode 92 | ts = torch.jit.trace(model, img, strict=False) # TorchScript model 93 | model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])]) 94 | model.save(f) 95 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 96 | except Exception as e: 97 | print(f'{prefix} export failure: {e}') 98 | 99 | 100 | def run(weights='./yolov5s.pt', # weights path 101 | img_size=(640, 640), # image (height, width) 102 | batch_size=1, # batch size 103 | device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu 104 | include=('torchscript', 'onnx', 'coreml'), # include formats 105 | half=False, # FP16 half-precision export 106 | inplace=False, # set YOLOv5 Detect() inplace=True 107 | train=False, # model.train() mode 108 | optimize=False, # TorchScript: optimize for mobile 109 | dynamic=False, # ONNX: dynamic axes 110 | simplify=False, # ONNX: simplify model 111 | opset_version=12, # ONNX: opset version 112 | ): 113 | t = time.time() 114 | include = [x.lower() for x in include] 115 | img_size *= 2 if len(img_size) == 1 else 1 # expand 116 | file = Path(weights) 117 | 118 | # Load PyTorch model 119 | device = select_device(device) 120 | assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0' 121 | model = attempt_load(weights, map_location=device) # load FP32 model 122 | names = model.names 123 | 124 | # Input 125 | gs = int(max(model.stride)) # grid size (max stride) 126 | img_size = [check_img_size(x, gs) for x in img_size] # verify img_size are gs-multiples 127 | img = torch.zeros(batch_size, 3, *img_size).to(device) # image size(1,3,320,192) iDetection 128 | 129 | # Update model 130 | if half: 131 | img, model = img.half(), model.half() # to FP16 132 | model.train() if train else model.eval() # training mode = no Detect() layer grid construction 133 | for k, m in model.named_modules(): 134 | if isinstance(m, Conv): # assign export-friendly activations 135 | if isinstance(m.act, nn.Hardswish): 136 | m.act = Hardswish() 137 | elif isinstance(m.act, nn.SiLU): 138 | m.act = SiLU() 139 | elif isinstance(m, Detect): 140 | m.inplace = inplace 141 | m.onnx_dynamic = dynamic 142 | # m.forward = m.forward_export # assign forward (optional) 143 | 144 | for _ in range(2): 145 | y = model(img) # dry runs 146 | print(f"\n{colorstr('PyTorch:')} starting from {weights} ({file_size(weights):.1f} MB)") 147 | 148 | # Exports 149 | if 'torchscript' in include: 150 | export_torchscript(model, img, file, optimize) 151 | if 'onnx' in include: 152 | export_onnx(model, img, file, opset_version, train, dynamic, simplify) 153 | if 'coreml' in include: 154 | export_coreml(model, img, file) 155 | 156 | # Finish 157 | print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.') 158 | 159 | 160 | def parse_opt(): 161 | parser = argparse.ArgumentParser() 162 | parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path') 163 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image (height, width)') 164 | parser.add_argument('--batch-size', type=int, default=1, help='batch size') 165 | parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 166 | parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats') 167 | parser.add_argument('--half', action='store_true', help='FP16 half-precision export') 168 | parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True') 169 | parser.add_argument('--train', action='store_true', help='model.train() mode') 170 | parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile') 171 | parser.add_argument('--dynamic', action='store_true', help='ONNX: dynamic axes') 172 | parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model') 173 | parser.add_argument('--opset-version', type=int, default=12, help='ONNX: opset version') 174 | opt = parser.parse_args() 175 | return opt 176 | 177 | 178 | def main(opt): 179 | set_logging() 180 | print(colorstr('export: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) 181 | run(**vars(opt)) 182 | 183 | 184 | if __name__ == "__main__": 185 | opt = parse_opt() 186 | main(opt) 187 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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.3') # 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 | -------------------------------------------------------------------------------- /detect.py: -------------------------------------------------------------------------------- 1 | """Run inference with a YOLOv5 model on images, videos, directories, streams 2 | 3 | Usage: 4 | $ python path/to/detect.py --source path/to/img.jpg --weights yolov5s.pt --img 640 5 | """ 6 | 7 | import argparse 8 | import sys 9 | import time 10 | from pathlib import Path 11 | 12 | import cv2 13 | import torch 14 | import torch.backends.cudnn as cudnn 15 | 16 | FILE = Path(__file__).absolute() 17 | sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path 18 | 19 | from models.experimental import attempt_load 20 | from utils.datasets import LoadStreams, LoadImages 21 | from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \ 22 | apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box 23 | from utils.plots import colors, plot_one_box 24 | from utils.torch_utils import select_device, load_classifier, time_sync 25 | 26 | 27 | 28 | @torch.no_grad() 29 | def run(weights='yolov5s.pt', # model.pt path(s) 30 | source='data/images', # file/dir/URL/glob, 0 for webcam 31 | imgsz=640, # inference size (pixels) 32 | conf_thres=0.25, # confidence threshold 33 | iou_thres=0.45, # NMS IOU threshold 34 | max_det=1000, # maximum detections per image 35 | device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu 36 | view_img=False, # show results 37 | save_txt=False, # save results to *.txt 38 | save_conf=False, # save confidences in --save-txt labels 39 | save_crop=False, # save cropped prediction boxes 40 | nosave=False, # do not save images/videos 41 | classes=None, # filter by class: --class 0, or --class 0 2 3 42 | agnostic_nms=False, # class-agnostic NMS 43 | augment=False, # augmented inference 44 | visualize=False, # visualize features 45 | update=False, # update all models 46 | project='runs/detect', # save results to project/name 47 | name='exp', # save results to project/name 48 | exist_ok=False, # existing project/name ok, do not increment 49 | line_thickness=3, # bounding box thickness (pixels) 50 | hide_labels=False, # hide labels 51 | hide_conf=False, # hide confidences 52 | half=False, # use FP16 half-precision inference 53 | ): 54 | save_img = not nosave and not source.endswith('.txt') # save inference images 55 | webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith( 56 | ('rtsp://', 'rtmp://', 'http://', 'https://')) 57 | 58 | # Directories 59 | save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run 60 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir 61 | 62 | # Initialize 63 | set_logging() 64 | device = select_device(device) 65 | half &= device.type != 'cpu' # half precision only supported on CUDA 66 | 67 | # Load model 68 | model = attempt_load(weights, map_location=device) # load FP32 model 69 | stride = int(model.stride.max()) # model stride 70 | imgsz = check_img_size(imgsz, s=stride) # check image size 71 | names = model.module.names if hasattr(model, 'module') else model.names # get class names 72 | if half: 73 | model.half() # to FP16 74 | 75 | # Second-stage classifier 76 | classify = False 77 | if classify: 78 | modelc = load_classifier(name='resnet50', n=2) # initialize 79 | modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval() 80 | 81 | # Dataloader 82 | if webcam: 83 | view_img = check_imshow() 84 | cudnn.benchmark = True # set True to speed up constant image size inference 85 | dataset = LoadStreams(source, img_size=imgsz, stride=stride) 86 | bs = len(dataset) # batch_size 87 | else: 88 | dataset = LoadImages(source, img_size=imgsz, stride=stride) 89 | bs = 1 # batch_size 90 | vid_path, vid_writer = [None] * bs, [None] * bs 91 | 92 | # Run inference 93 | if device.type != 'cpu': 94 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once 95 | t0 = time.time() 96 | for path, img, im0s, vid_cap in dataset: 97 | img = torch.from_numpy(img).to(device) 98 | img = img.half() if half else img.float() # uint8 to fp16/32 99 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 100 | if img.ndimension() == 3: 101 | img = img.unsqueeze(0) 102 | 103 | # Inference 104 | t1 = time_sync() 105 | 106 | mulpicplus = "3" #1 for normal,2 for 4pic plus,3 for 9pic plus and so on 107 | assert(int(mulpicplus)>=1) 108 | if mulpicplus == "1": 109 | pred = model(img, 110 | augment=augment, 111 | visualize=increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False)[0] 112 | 113 | else: 114 | xsz = img.shape[2] 115 | ysz = img.shape[3] 116 | mulpicplus = int(mulpicplus) 117 | x_smalloccur = int(xsz / mulpicplus * 1.2) 118 | y_smalloccur = int(ysz / mulpicplus * 1.2) 119 | for i in range(mulpicplus): 120 | x_startpoint = int(i * (xsz / mulpicplus)) 121 | for j in range(mulpicplus): 122 | y_startpoint = int(j * (ysz / mulpicplus)) 123 | x_real = min(x_startpoint + x_smalloccur, xsz) 124 | y_real = min(y_startpoint + y_smalloccur, ysz) 125 | if (x_real - x_startpoint) % 64 != 0: 126 | x_real = x_real - (x_real-x_startpoint) % 64 127 | if (y_real - y_startpoint) % 64 != 0: 128 | y_real = y_real - (y_real - y_startpoint) % 64 129 | dicsrc = img[:, :, x_startpoint:x_real, 130 | y_startpoint:y_real] 131 | pred_temp = model(dicsrc, 132 | augment=augment, 133 | visualize=increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False)[0] 134 | pred_temp[..., 0] = pred_temp[..., 0] + y_startpoint 135 | pred_temp[..., 1] = pred_temp[..., 1] + x_startpoint 136 | if i==0 and j == 0: 137 | pred = pred_temp 138 | else: 139 | pred = torch.cat([pred, pred_temp], dim=1) 140 | 141 | 142 | # Apply NMS 143 | pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) 144 | t2 = time_sync() 145 | 146 | # Apply Classifier 147 | if classify: 148 | pred = apply_classifier(pred, modelc, img, im0s) 149 | 150 | 151 | # Process detections 152 | for i, det in enumerate(pred): # detections per image 153 | if webcam: # batch_size >= 1 154 | p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count 155 | else: 156 | p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0) 157 | 158 | p = Path(p) # to Path 159 | save_path = str(save_dir / p.name) 160 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt 161 | s += '%gx%g ' % img.shape[2:] # print string 162 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh 163 | imc = im0.copy() if save_crop else im0 # for save_crop 164 | if len(det): 165 | # Rescale boxes from img_size to im0 size 166 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 167 | 168 | # Print results 169 | for c in det[:, -1].unique(): 170 | n = (det[:, -1] == c).sum() # detections per class 171 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string 172 | 173 | # Write results 174 | for *xyxy, conf, cls in reversed(det): 175 | if save_txt: # Write to file 176 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 177 | line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format 178 | with open(txt_path + '.txt', 'a') as f: 179 | f.write(('%g ' * len(line)).rstrip() % line + '\n') 180 | 181 | if save_img or save_crop or view_img: # Add bbox to image 182 | c = int(cls) # integer class 183 | label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') 184 | plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness) 185 | if save_crop: 186 | save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) 187 | 188 | # Print time (inference + ) 189 | print(f'{s}Done. ({t2 - t1:.3f}s)') 190 | 191 | # Stream results 192 | if view_img: 193 | cv2.imshow(str(p), im0) 194 | cv2.waitKey(1) # 1 millisecond 195 | 196 | # Save results (image with detections) 197 | if save_img: 198 | if dataset.mode == 'image': 199 | cv2.imwrite(save_path, im0) 200 | else: # 'video' or 'stream' 201 | if vid_path[i] != save_path: # new video 202 | vid_path[i] = save_path 203 | if isinstance(vid_writer[i], cv2.VideoWriter): 204 | vid_writer[i].release() # release previous video writer 205 | if vid_cap: # video 206 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 207 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 208 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 209 | else: # stream 210 | fps, w, h = 30, im0.shape[1], im0.shape[0] 211 | save_path += '.mp4' 212 | vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) 213 | vid_writer[i].write(im0) 214 | 215 | if save_txt or save_img: 216 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' 217 | print(f"Results saved to {save_dir}{s}") 218 | 219 | if update: 220 | strip_optimizer(weights) # update model (to fix SourceChangeWarning) 221 | 222 | print(f'Done. ({time.time() - t0:.3f}s)') 223 | 224 | 225 | def parse_opt(): 226 | parser = argparse.ArgumentParser() 227 | parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)') 228 | parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam') 229 | parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') 230 | parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold') 231 | parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold') 232 | parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image') 233 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 234 | parser.add_argument('--view-img', action='store_true', help='show results') 235 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 236 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') 237 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes') 238 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos') 239 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') 240 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 241 | parser.add_argument('--augment', action='store_true', help='augmented inference') 242 | parser.add_argument('--visualize', action='store_true', help='visualize features') 243 | parser.add_argument('--update', action='store_true', help='update all models') 244 | parser.add_argument('--project', default='runs/detect', help='save results to project/name') 245 | parser.add_argument('--name', default='exp', help='save results to project/name') 246 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') 247 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') 248 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') 249 | parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') 250 | parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') 251 | 252 | 253 | opt = parser.parse_args() 254 | return opt 255 | 256 | 257 | def main(opt): 258 | print(colorstr('detect: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) 259 | check_requirements(exclude=('tensorboard', 'thop')) 260 | run(**vars(opt)) 261 | 262 | 263 | if __name__ == "__main__": 264 | opt = parse_opt() 265 | main(opt) 266 | -------------------------------------------------------------------------------- /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_sync(): 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_sync() 122 | y = m(x) 123 | t[1] = time_sync() 124 | try: 125 | _ = y.sum().backward() 126 | t[2] = time_sync() 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 | -------------------------------------------------------------------------------- /models/yolo.py: -------------------------------------------------------------------------------- 1 | """YOLOv5-specific modules 2 | 3 | Usage: 4 | $ python path/to/models/yolo.py --cfg yolov5s.yaml 5 | """ 6 | 7 | import argparse 8 | import sys 9 | from copy import deepcopy 10 | from pathlib import Path 11 | 12 | FILE = Path(__file__).absolute() 13 | sys.path.append(FILE.parents[1].as_posix()) # add yolov5/ to path 14 | 15 | from models.common import * 16 | from models.experimental import * 17 | from utils.autoanchor import check_anchor_order 18 | from utils.general import make_divisible, check_file, set_logging 19 | from utils.plots import feature_visualization 20 | from utils.torch_utils import time_sync, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \ 21 | select_device, copy_attr 22 | 23 | try: 24 | import thop # for FLOPs computation 25 | except ImportError: 26 | thop = None 27 | 28 | LOGGER = logging.getLogger(__name__) 29 | 30 | 31 | class Detect(nn.Module): 32 | stride = None # strides computed during build 33 | onnx_dynamic = False # ONNX export parameter 34 | 35 | def __init__(self, nc=80, anchors=(), ch=(), inplace=True): # detection layer 36 | super().__init__() 37 | self.nc = nc # number of classes 38 | self.no = nc + 5 # number of outputs per anchor 39 | self.nl = len(anchors) # number of detection layers 40 | self.na = len(anchors[0]) // 2 # number of anchors 41 | self.grid = [torch.zeros(1)] * self.nl # init grid 42 | a = torch.tensor(anchors).float().view(self.nl, -1, 2) 43 | self.register_buffer('anchors', a) # shape(nl,na,2) 44 | self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2) 45 | self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv 46 | self.inplace = inplace # use in-place ops (e.g. slice assignment) 47 | 48 | def forward(self, x): 49 | # x = x.copy() # for profiling 50 | z = [] # inference output 51 | for i in range(self.nl): 52 | x[i] = self.m[i](x[i]) # conv 53 | bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85) 54 | x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous() 55 | 56 | if not self.training: # inference 57 | if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic: 58 | self.grid[i] = self._make_grid(nx, ny).to(x[i].device) 59 | 60 | y = x[i].sigmoid() 61 | if self.inplace: 62 | y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy 63 | y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh 64 | else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953 65 | xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy 66 | wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.na, 1, 1, 2) # wh 67 | y = torch.cat((xy, wh, y[..., 4:]), -1) 68 | z.append(y.view(bs, -1, self.no)) 69 | 70 | return x if self.training else (torch.cat(z, 1), x) 71 | 72 | @staticmethod 73 | def _make_grid(nx=20, ny=20): 74 | yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)]) 75 | return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float() 76 | 77 | 78 | class Model(nn.Module): 79 | def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None): # model, input channels, number of classes 80 | super().__init__() 81 | if isinstance(cfg, dict): 82 | self.yaml = cfg # model dict 83 | else: # is *.yaml 84 | import yaml # for torch hub 85 | self.yaml_file = Path(cfg).name 86 | with open(cfg) as f: 87 | self.yaml = yaml.safe_load(f) # model dict 88 | 89 | # Define model 90 | ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels 91 | if nc and nc != self.yaml['nc']: 92 | LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") 93 | self.yaml['nc'] = nc # override yaml value 94 | if anchors: 95 | LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}') 96 | self.yaml['anchors'] = round(anchors) # override yaml value 97 | self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist 98 | self.names = [str(i) for i in range(self.yaml['nc'])] # default names 99 | self.inplace = self.yaml.get('inplace', True) 100 | # LOGGER.info([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))]) 101 | 102 | # Build strides, anchors 103 | m = self.model[-1] # Detect() 104 | if isinstance(m, Detect): 105 | s = 256 # 2x min stride 106 | m.inplace = self.inplace 107 | m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward 108 | m.anchors /= m.stride.view(-1, 1, 1) 109 | check_anchor_order(m) 110 | self.stride = m.stride 111 | self._initialize_biases() # only run once 112 | # LOGGER.info('Strides: %s' % m.stride.tolist()) 113 | 114 | # Init weights, biases 115 | initialize_weights(self) 116 | self.info() 117 | LOGGER.info('') 118 | 119 | def forward(self, x, augment=False, profile=False, visualize=False): 120 | if augment: 121 | return self.forward_augment(x) # augmented inference, None 122 | return self.forward_once(x, profile, visualize) # single-scale inference, train 123 | 124 | def forward_augment(self, x): 125 | img_size = x.shape[-2:] # height, width 126 | s = [1, 0.83, 0.67] # scales 127 | f = [None, 3, None] # flips (2-ud, 3-lr) 128 | y = [] # outputs 129 | for si, fi in zip(s, f): 130 | xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) 131 | yi = self.forward_once(xi)[0] # forward 132 | # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save 133 | yi = self._descale_pred(yi, fi, si, img_size) 134 | y.append(yi) 135 | return torch.cat(y, 1), None # augmented inference, train 136 | 137 | def forward_once(self, x, profile=False, visualize=False): 138 | y, dt = [], [] # outputs 139 | for m in self.model: 140 | if m.f != -1: # if not from previous layer 141 | x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers 142 | 143 | if profile: 144 | o = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs 145 | t = time_sync() 146 | for _ in range(10): 147 | _ = m(x) 148 | dt.append((time_sync() - t) * 100) 149 | if m == self.model[0]: 150 | LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}") 151 | LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}') 152 | 153 | x = m(x) # run 154 | y.append(x if m.i in self.save else None) # save output 155 | 156 | if visualize: 157 | feature_visualization(x, m.type, m.i, save_dir=visualize) 158 | 159 | if profile: 160 | LOGGER.info('%.1fms total' % sum(dt)) 161 | return x 162 | 163 | def _descale_pred(self, p, flips, scale, img_size): 164 | # de-scale predictions following augmented inference (inverse operation) 165 | if self.inplace: 166 | p[..., :4] /= scale # de-scale 167 | if flips == 2: 168 | p[..., 1] = img_size[0] - p[..., 1] # de-flip ud 169 | elif flips == 3: 170 | p[..., 0] = img_size[1] - p[..., 0] # de-flip lr 171 | else: 172 | x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale 173 | if flips == 2: 174 | y = img_size[0] - y # de-flip ud 175 | elif flips == 3: 176 | x = img_size[1] - x # de-flip lr 177 | p = torch.cat((x, y, wh, p[..., 4:]), -1) 178 | return p 179 | 180 | def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency 181 | # https://arxiv.org/abs/1708.02002 section 3.3 182 | # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. 183 | m = self.model[-1] # Detect() module 184 | for mi, s in zip(m.m, m.stride): # from 185 | b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) 186 | b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) 187 | b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls 188 | mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) 189 | 190 | def _print_biases(self): 191 | m = self.model[-1] # Detect() module 192 | for mi in m.m: # from 193 | b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) 194 | LOGGER.info( 195 | ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) 196 | 197 | # def _print_weights(self): 198 | # for m in self.model.modules(): 199 | # if type(m) is Bottleneck: 200 | # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights 201 | 202 | def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers 203 | LOGGER.info('Fusing layers... ') 204 | for m in self.model.modules(): 205 | if type(m) is Conv and hasattr(m, 'bn'): 206 | m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv 207 | delattr(m, 'bn') # remove batchnorm 208 | m.forward = m.fuseforward # update forward 209 | self.info() 210 | return self 211 | 212 | def autoshape(self): # add AutoShape module 213 | LOGGER.info('Adding AutoShape... ') 214 | m = AutoShape(self) # wrap model 215 | copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes 216 | return m 217 | 218 | def info(self, verbose=False, img_size=640): # print model information 219 | model_info(self, verbose, img_size) 220 | 221 | 222 | def parse_model(d, ch): # model_dict, input_channels(3) 223 | LOGGER.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments')) 224 | anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple'] 225 | na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors 226 | no = na * (nc + 5) # number of outputs = anchors * (classes + 5) 227 | 228 | layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out 229 | for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args 230 | m = eval(m) if isinstance(m, str) else m # eval strings 231 | for j, a in enumerate(args): 232 | try: 233 | args[j] = eval(a) if isinstance(a, str) else a # eval strings 234 | except: 235 | pass 236 | 237 | n = max(round(n * gd), 1) if n > 1 else n # depth gain 238 | if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, 239 | C3, C3TR, C3SPP]: 240 | c1, c2 = ch[f], args[0] 241 | if c2 != no: # if not output 242 | c2 = make_divisible(c2 * gw, 8) 243 | 244 | args = [c1, c2, *args[1:]] 245 | if m in [BottleneckCSP, C3, C3TR]: 246 | args.insert(2, n) # number of repeats 247 | n = 1 248 | elif m is nn.BatchNorm2d: 249 | args = [ch[f]] 250 | elif m is Concat: 251 | c2 = sum([ch[x] for x in f]) 252 | elif m is Detect: 253 | args.append([ch[x] for x in f]) 254 | if isinstance(args[1], int): # number of anchors 255 | args[1] = [list(range(args[1] * 2))] * len(f) 256 | elif m is Contract: 257 | c2 = ch[f] * args[0] ** 2 258 | elif m is Expand: 259 | c2 = ch[f] // args[0] ** 2 260 | else: 261 | c2 = ch[f] 262 | 263 | m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module 264 | t = str(m)[8:-2].replace('__main__.', '') # module type 265 | np = sum([x.numel() for x in m_.parameters()]) # number params 266 | m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params 267 | LOGGER.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n, np, t, args)) # print 268 | save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist 269 | layers.append(m_) 270 | if i == 0: 271 | ch = [] 272 | ch.append(c2) 273 | return nn.Sequential(*layers), sorted(save) 274 | 275 | 276 | if __name__ == '__main__': 277 | parser = argparse.ArgumentParser() 278 | parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml') 279 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 280 | opt = parser.parse_args() 281 | opt.cfg = check_file(opt.cfg) # check file 282 | set_logging() 283 | device = select_device(opt.device) 284 | 285 | # Create model 286 | model = Model(opt.cfg).to(device) 287 | model.train() 288 | 289 | # Profile 290 | # img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 320, 320).to(device) 291 | # y = model(img, profile=True) 292 | 293 | # Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898) 294 | # from torch.utils.tensorboard import SummaryWriter 295 | # tb_writer = SummaryWriter('.') 296 | # LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/") 297 | # tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph 298 | -------------------------------------------------------------------------------- /utils/metrics.py: -------------------------------------------------------------------------------- 1 | # Model validation metrics 2 | 3 | import warnings 4 | from pathlib import Path 5 | 6 | import math 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | import torch 10 | 11 | 12 | def fitness(x): 13 | # Model fitness as a weighted combination of metrics 14 | w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95] 15 | return (x[:, :4] * w).sum(1) 16 | 17 | 18 | def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()): 19 | """ Compute the average precision, given the recall and precision curves. 20 | Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. 21 | # Arguments 22 | tp: True positives (nparray, nx1 or nx10). 23 | conf: Objectness value from 0-1 (nparray). 24 | pred_cls: Predicted object classes (nparray). 25 | target_cls: True object classes (nparray). 26 | plot: Plot precision-recall curve at mAP@0.5 27 | save_dir: Plot save directory 28 | # Returns 29 | The average precision as computed in py-faster-rcnn. 30 | """ 31 | 32 | # Sort by objectness 33 | i = np.argsort(-conf) 34 | tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] 35 | 36 | # Find unique classes 37 | unique_classes = np.unique(target_cls) 38 | nc = unique_classes.shape[0] # number of classes, number of detections 39 | 40 | # Create Precision-Recall curve and compute AP for each class 41 | px, py = np.linspace(0, 1, 1000), [] # for plotting 42 | ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000)) 43 | for ci, c in enumerate(unique_classes): 44 | i = pred_cls == c 45 | n_l = (target_cls == c).sum() # number of labels 46 | n_p = i.sum() # number of predictions 47 | 48 | if n_p == 0 or n_l == 0: 49 | continue 50 | else: 51 | # Accumulate FPs and TPs 52 | fpc = (1 - tp[i]).cumsum(0) 53 | tpc = tp[i].cumsum(0) 54 | 55 | # Recall 56 | recall = tpc / (n_l + 1e-16) # recall curve 57 | r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases 58 | 59 | # Precision 60 | precision = tpc / (tpc + fpc) # precision curve 61 | p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score 62 | 63 | # AP from recall-precision curve 64 | for j in range(tp.shape[1]): 65 | ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j]) 66 | if plot and j == 0: 67 | py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5 68 | 69 | # Compute F1 (harmonic mean of precision and recall) 70 | f1 = 2 * p * r / (p + r + 1e-16) 71 | if plot: 72 | plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names) 73 | plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1') 74 | plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision') 75 | plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall') 76 | 77 | i = f1.mean(0).argmax() # max F1 index 78 | return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32') 79 | 80 | 81 | def compute_ap(recall, precision): 82 | """ Compute the average precision, given the recall and precision curves 83 | # Arguments 84 | recall: The recall curve (list) 85 | precision: The precision curve (list) 86 | # Returns 87 | Average precision, precision curve, recall curve 88 | """ 89 | 90 | # Append sentinel values to beginning and end 91 | mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01])) 92 | mpre = np.concatenate(([1.], precision, [0.])) 93 | 94 | # Compute the precision envelope 95 | mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) 96 | 97 | # Integrate area under curve 98 | method = 'interp' # methods: 'continuous', 'interp' 99 | if method == 'interp': 100 | x = np.linspace(0, 1, 101) # 101-point interp (COCO) 101 | ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate 102 | else: # 'continuous' 103 | i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes 104 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve 105 | 106 | return ap, mpre, mrec 107 | 108 | 109 | class ConfusionMatrix: 110 | # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix 111 | def __init__(self, nc, conf=0.25, iou_thres=0.45): 112 | self.matrix = np.zeros((nc + 1, nc + 1)) 113 | self.nc = nc # number of classes 114 | self.conf = conf 115 | self.iou_thres = iou_thres 116 | 117 | def process_batch(self, detections, labels): 118 | """ 119 | Return intersection-over-union (Jaccard index) of boxes. 120 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format. 121 | Arguments: 122 | detections (Array[N, 6]), x1, y1, x2, y2, conf, class 123 | labels (Array[M, 5]), class, x1, y1, x2, y2 124 | Returns: 125 | None, updates confusion matrix accordingly 126 | """ 127 | detections = detections[detections[:, 4] > self.conf] 128 | gt_classes = labels[:, 0].int() 129 | detection_classes = detections[:, 5].int() 130 | iou = box_iou(labels[:, 1:], detections[:, :4]) 131 | 132 | x = torch.where(iou > self.iou_thres) 133 | if x[0].shape[0]: 134 | matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() 135 | if x[0].shape[0] > 1: 136 | matches = matches[matches[:, 2].argsort()[::-1]] 137 | matches = matches[np.unique(matches[:, 1], return_index=True)[1]] 138 | matches = matches[matches[:, 2].argsort()[::-1]] 139 | matches = matches[np.unique(matches[:, 0], return_index=True)[1]] 140 | else: 141 | matches = np.zeros((0, 3)) 142 | 143 | n = matches.shape[0] > 0 144 | m0, m1, _ = matches.transpose().astype(np.int16) 145 | for i, gc in enumerate(gt_classes): 146 | j = m0 == i 147 | if n and sum(j) == 1: 148 | self.matrix[detection_classes[m1[j]], gc] += 1 # correct 149 | else: 150 | self.matrix[self.nc, gc] += 1 # background FP 151 | 152 | if n: 153 | for i, dc in enumerate(detection_classes): 154 | if not any(m1 == i): 155 | self.matrix[dc, self.nc] += 1 # background FN 156 | 157 | def matrix(self): 158 | return self.matrix 159 | 160 | def plot(self, normalize=True, save_dir='', names=()): 161 | try: 162 | import seaborn as sn 163 | 164 | array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-6) if normalize else 1) # normalize columns 165 | array[array < 0.005] = np.nan # don't annotate (would appear as 0.00) 166 | 167 | fig = plt.figure(figsize=(12, 9), tight_layout=True) 168 | sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size 169 | labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels 170 | with warnings.catch_warnings(): 171 | warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered 172 | sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True, 173 | xticklabels=names + ['background FP'] if labels else "auto", 174 | yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1)) 175 | fig.axes[0].set_xlabel('True') 176 | fig.axes[0].set_ylabel('Predicted') 177 | fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250) 178 | except Exception as e: 179 | print(f'WARNING: ConfusionMatrix plot failure: {e}') 180 | 181 | def print(self): 182 | for i in range(self.nc + 1): 183 | print(' '.join(map(str, self.matrix[i]))) 184 | 185 | 186 | def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7): 187 | # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4 188 | box2 = box2.T 189 | 190 | # Get the coordinates of bounding boxes 191 | if x1y1x2y2: # x1, y1, x2, y2 = box1 192 | b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] 193 | b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] 194 | else: # transform from xywh to xyxy 195 | b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2 196 | b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2 197 | b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2 198 | b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2 199 | 200 | # Intersection area 201 | inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ 202 | (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) 203 | 204 | # Union Area 205 | w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps 206 | w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps 207 | union = w1 * h1 + w2 * h2 - inter + eps 208 | 209 | iou = inter / union 210 | if GIoU or DIoU or CIoU: 211 | cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width 212 | ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height 213 | if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1 214 | c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared 215 | rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + 216 | (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared 217 | if DIoU: 218 | return iou - rho2 / c2 # DIoU 219 | elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47 220 | v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2) 221 | with torch.no_grad(): 222 | alpha = v / (v - iou + (1 + eps)) 223 | return iou - (rho2 / c2 + v * alpha) # CIoU 224 | else: # GIoU https://arxiv.org/pdf/1902.09630.pdf 225 | c_area = cw * ch + eps # convex area 226 | return iou - (c_area - union) / c_area # GIoU 227 | else: 228 | return iou # IoU 229 | 230 | 231 | def box_iou(box1, box2): 232 | # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py 233 | """ 234 | Return intersection-over-union (Jaccard index) of boxes. 235 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format. 236 | Arguments: 237 | box1 (Tensor[N, 4]) 238 | box2 (Tensor[M, 4]) 239 | Returns: 240 | iou (Tensor[N, M]): the NxM matrix containing the pairwise 241 | IoU values for every element in boxes1 and boxes2 242 | """ 243 | 244 | def box_area(box): 245 | # box = 4xn 246 | return (box[2] - box[0]) * (box[3] - box[1]) 247 | 248 | area1 = box_area(box1.T) 249 | area2 = box_area(box2.T) 250 | 251 | # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2) 252 | inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2) 253 | return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter) 254 | 255 | 256 | def bbox_ioa(box1, box2, eps=1E-7): 257 | """ Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2 258 | box1: np.array of shape(4) 259 | box2: np.array of shape(nx4) 260 | returns: np.array of shape(n) 261 | """ 262 | 263 | box2 = box2.transpose() 264 | 265 | # Get the coordinates of bounding boxes 266 | b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3] 267 | b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3] 268 | 269 | # Intersection area 270 | inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \ 271 | (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0) 272 | 273 | # box2 area 274 | box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps 275 | 276 | # Intersection over box2 area 277 | return inter_area / box2_area 278 | 279 | 280 | def wh_iou(wh1, wh2): 281 | # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2 282 | wh1 = wh1[:, None] # [N,1,2] 283 | wh2 = wh2[None] # [1,M,2] 284 | inter = torch.min(wh1, wh2).prod(2) # [N,M] 285 | return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter) 286 | 287 | 288 | # Plots ---------------------------------------------------------------------------------------------------------------- 289 | 290 | def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()): 291 | # Precision-recall curve 292 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) 293 | py = np.stack(py, axis=1) 294 | 295 | if 0 < len(names) < 21: # display per-class legend if < 21 classes 296 | for i, y in enumerate(py.T): 297 | ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision) 298 | else: 299 | ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision) 300 | 301 | ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean()) 302 | ax.set_xlabel('Recall') 303 | ax.set_ylabel('Precision') 304 | ax.set_xlim(0, 1) 305 | ax.set_ylim(0, 1) 306 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") 307 | fig.savefig(Path(save_dir), dpi=250) 308 | 309 | 310 | def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'): 311 | # Metric-confidence curve 312 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) 313 | 314 | if 0 < len(names) < 21: # display per-class legend if < 21 classes 315 | for i, y in enumerate(py): 316 | ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric) 317 | else: 318 | ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric) 319 | 320 | y = py.mean(0) 321 | ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}') 322 | ax.set_xlabel(xlabel) 323 | ax.set_ylabel(ylabel) 324 | ax.set_xlim(0, 1) 325 | ax.set_ylim(0, 1) 326 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") 327 | fig.savefig(Path(save_dir), dpi=250) 328 | --------------------------------------------------------------------------------