├── .gitignore ├── LICENSE ├── Procfile ├── README.md ├── __pycache__ └── app.cpython-39.pyc ├── app.py ├── data ├── Argoverse.yaml ├── GlobalWheat2020.yaml ├── Objects365.yaml ├── SKU-110K.yaml ├── VOC.yaml ├── VisDrone.yaml ├── coco.yaml ├── coco128.yaml ├── hyps │ ├── hyp.finetune.yaml │ ├── hyp.finetune_objects365.yaml │ ├── hyp.scratch-p6.yaml │ └── hyp.scratch.yaml ├── images │ ├── bus.jpg │ └── zidane.jpg ├── scripts │ ├── download_weights.sh │ ├── get_coco.sh │ └── get_coco128.sh └── xView.yaml ├── detect.py ├── doc.odt ├── instance └── uploads │ └── asmit.jpg ├── models ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-39.pyc │ ├── common.cpython-39.pyc │ ├── experimental.cpython-39.pyc │ └── yolo.cpython-39.pyc ├── common.py ├── experimental.py ├── hub │ ├── anchors.yaml │ ├── yolov3-spp.yaml │ ├── yolov3-tiny.yaml │ ├── yolov3.yaml │ ├── yolov5-bifpn.yaml │ ├── yolov5-fpn.yaml │ ├── yolov5-p2.yaml │ ├── yolov5-p6.yaml │ ├── yolov5-p7.yaml │ ├── yolov5-panet.yaml │ ├── yolov5l6.yaml │ ├── yolov5m6.yaml │ ├── yolov5s-transformer.yaml │ ├── yolov5s6.yaml │ └── yolov5x6.yaml ├── yolo.py ├── yolov5l.yaml ├── yolov5m.yaml ├── yolov5s.yaml └── yolov5x.yaml ├── requirements.txt ├── static ├── asmit.jpg ├── bus.jpg ├── index.css ├── index.js └── zidane.jpg ├── templates ├── download.html └── index.html ├── utils ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-39.pyc │ ├── augmentations.cpython-39.pyc │ ├── autoanchor.cpython-39.pyc │ ├── datasets.cpython-39.pyc │ ├── downloads.cpython-39.pyc │ ├── general.cpython-39.pyc │ ├── metrics.cpython-39.pyc │ ├── plots.cpython-39.pyc │ └── torch_utils.cpython-39.pyc ├── activations.py ├── augmentations.py ├── autoanchor.py ├── aws │ ├── __init__.py │ ├── mime.sh │ ├── resume.py │ └── userdata.sh ├── callbacks.py ├── datasets.py ├── downloads.py ├── flask_rest_api │ ├── README.md │ ├── example_request.py │ └── restapi.py ├── general.py ├── google_app_engine │ ├── Dockerfile │ ├── additional_requirements.txt │ └── app.yaml ├── loggers │ ├── __init__.py │ └── wandb │ │ ├── __init__.py │ │ ├── log_dataset.py │ │ ├── sweep.py │ │ ├── sweep.yaml │ │ └── wandb_utils.py ├── loss.py ├── metrics.py ├── plots.py └── torch_utils.py └── yolov5s.pt /.gitignore: -------------------------------------------------------------------------------- 1 | venv/ 2 | __pycache__/ -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: gunicorn app:app -------------------------------------------------------------------------------- /__pycache__/app.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/__pycache__/app.cpython-39.pyc -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | from re import DEBUG, sub 2 | from flask import Flask, render_template, request, redirect, send_file, url_for 3 | from werkzeug.utils import secure_filename, send_from_directory 4 | import os 5 | import subprocess 6 | 7 | app = Flask(__name__) 8 | 9 | 10 | uploads_dir = os.path.join(app.instance_path, 'uploads') 11 | 12 | os.makedirs(uploads_dir, exist_ok=True) 13 | 14 | @app.route("/") 15 | def hello_world(): 16 | return render_template('index.html') 17 | 18 | 19 | @app.route("/detect", methods=['POST']) 20 | def detect(): 21 | if not request.method == "POST": 22 | return 23 | video = request.files['video'] 24 | video.save(os.path.join(uploads_dir, secure_filename(video.filename))) 25 | print(video) 26 | subprocess.run("ls") 27 | subprocess.run(['python3', 'detect.py', '--source', os.path.join(uploads_dir, secure_filename(video.filename))]) 28 | 29 | # return os.path.join(uploads_dir, secure_filename(video.filename)) 30 | obj = secure_filename(video.filename) 31 | return obj 32 | 33 | @app.route("/opencam", methods=['GET']) 34 | def opencam(): 35 | print("here") 36 | subprocess.run(['python3', 'detect.py', '--source', '0']) 37 | return "done" 38 | 39 | 40 | @app.route('/return-files', methods=['GET']) 41 | def return_file(): 42 | obj = request.args.get('obj') 43 | loc = os.path.join("runs/detect", obj) 44 | print(loc) 45 | try: 46 | return send_file(os.path.join("runs/detect", obj), attachment_filename=obj) 47 | # return send_from_directory(loc, obj) 48 | except Exception as e: 49 | return str(e) 50 | 51 | # @app.route('/display/') 52 | # def display_video(filename): 53 | # #print('display_video filename: ' + filename) 54 | # return redirect(url_for('static/video_1.mp4', code=200)) -------------------------------------------------------------------------------- /data/Argoverse.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ 3 | # Example usage: python train.py --data Argoverse.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── Argoverse ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/Argoverse # dataset root dir 12 | train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images 13 | val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images 14 | test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview 15 | 16 | # Classes 17 | nc: 8 # number of classes 18 | names: ['person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign'] # class names 19 | 20 | 21 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 22 | download: | 23 | import json 24 | 25 | from tqdm import tqdm 26 | from utils.general import download, Path 27 | 28 | 29 | def argoverse2yolo(set): 30 | labels = {} 31 | a = json.load(open(set, "rb")) 32 | for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."): 33 | img_id = annot['image_id'] 34 | img_name = a['images'][img_id]['name'] 35 | img_label_name = img_name[:-3] + "txt" 36 | 37 | cls = annot['category_id'] # instance class id 38 | x_center, y_center, width, height = annot['bbox'] 39 | x_center = (x_center + width / 2) / 1920.0 # offset and scale 40 | y_center = (y_center + height / 2) / 1200.0 # offset and scale 41 | width /= 1920.0 # scale 42 | height /= 1200.0 # scale 43 | 44 | img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']] 45 | if not img_dir.exists(): 46 | img_dir.mkdir(parents=True, exist_ok=True) 47 | 48 | k = str(img_dir / img_label_name) 49 | if k not in labels: 50 | labels[k] = [] 51 | labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n") 52 | 53 | for k in labels: 54 | with open(k, "w") as f: 55 | f.writelines(labels[k]) 56 | 57 | 58 | # Download 59 | dir = Path('../datasets/Argoverse') # dataset root dir 60 | urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip'] 61 | download(urls, dir=dir, delete=False) 62 | 63 | # Convert 64 | annotations_dir = 'Argoverse-HD/annotations/' 65 | (dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images' 66 | for d in "train.json", "val.json": 67 | argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels 68 | -------------------------------------------------------------------------------- /data/GlobalWheat2020.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # Global Wheat 2020 dataset http://www.global-wheat.com/ 3 | # Example usage: python train.py --data GlobalWheat2020.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── GlobalWheat2020 ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/GlobalWheat2020 # dataset root dir 12 | train: # train images (relative to 'path') 3422 images 13 | - images/arvalis_1 14 | - images/arvalis_2 15 | - images/arvalis_3 16 | - images/ethz_1 17 | - images/rres_1 18 | - images/inrae_1 19 | - images/usask_1 20 | val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1) 21 | - images/ethz_1 22 | test: # test images (optional) 1276 images 23 | - images/utokyo_1 24 | - images/utokyo_2 25 | - images/nau_1 26 | - images/uq_1 27 | 28 | # Classes 29 | nc: 1 # number of classes 30 | names: ['wheat_head'] # class names 31 | 32 | 33 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 34 | download: | 35 | from utils.general import download, Path 36 | 37 | # Download 38 | dir = Path(yaml['path']) # dataset root dir 39 | urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip', 40 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip'] 41 | download(urls, dir=dir) 42 | 43 | # Make Directories 44 | for p in 'annotations', 'images', 'labels': 45 | (dir / p).mkdir(parents=True, exist_ok=True) 46 | 47 | # Move 48 | for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \ 49 | 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1': 50 | (dir / p).rename(dir / 'images' / p) # move to /images 51 | f = (dir / p).with_suffix('.json') # json file 52 | if f.exists(): 53 | f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations 54 | -------------------------------------------------------------------------------- /data/Objects365.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # Objects365 dataset https://www.objects365.org/ 3 | # Example usage: python train.py --data Objects365.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── Objects365 ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/Objects365 # dataset root dir 12 | train: images/train # train images (relative to 'path') 1742289 images 13 | val: images/val # val images (relative to 'path') 5570 images 14 | test: # test images (optional) 15 | 16 | # Classes 17 | nc: 365 # number of classes 18 | names: ['Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup', 19 | 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book', 20 | 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag', 21 | 'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV', 22 | 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle', 23 | 'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird', 24 | 'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck', 25 | 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning', 26 | 'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife', 27 | 'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock', 28 | 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish', 29 | 'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan', 30 | 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard', 31 | 'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign', 32 | 'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat', 33 | 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard', 34 | 'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry', 35 | 'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks', 36 | 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors', 37 | 'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape', 38 | 'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck', 39 | 'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette', 40 | 'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket', 41 | 'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine', 42 | 'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine', 43 | 'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon', 44 | 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse', 45 | 'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball', 46 | 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin', 47 | 'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts', 48 | 'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit', 49 | 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD', 50 | 'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder', 51 | 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips', 52 | 'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab', 53 | 'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal', 54 | 'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart', 55 | 'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French', 56 | 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell', 57 | 'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil', 58 | 'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis'] 59 | 60 | 61 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 62 | download: | 63 | from pycocotools.coco import COCO 64 | from tqdm import tqdm 65 | 66 | from utils.general import download, Path 67 | 68 | # Make Directories 69 | dir = Path(yaml['path']) # dataset root dir 70 | for p in 'images', 'labels': 71 | (dir / p).mkdir(parents=True, exist_ok=True) 72 | for q in 'train', 'val': 73 | (dir / p / q).mkdir(parents=True, exist_ok=True) 74 | 75 | # Download 76 | url = "https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/train/" 77 | download([url + 'zhiyuan_objv2_train.tar.gz'], dir=dir, delete=False) # annotations json 78 | download([url + f for f in [f'patch{i}.tar.gz' for i in range(51)]], dir=dir / 'images' / 'train', 79 | curl=True, delete=False, threads=8) 80 | 81 | # Move 82 | train = dir / 'images' / 'train' 83 | for f in tqdm(train.rglob('*.jpg'), desc=f'Moving images'): 84 | f.rename(train / f.name) # move to /images/train 85 | 86 | # Labels 87 | coco = COCO(dir / 'zhiyuan_objv2_train.json') 88 | names = [x["name"] for x in coco.loadCats(coco.getCatIds())] 89 | for cid, cat in enumerate(names): 90 | catIds = coco.getCatIds(catNms=[cat]) 91 | imgIds = coco.getImgIds(catIds=catIds) 92 | for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'): 93 | width, height = im["width"], im["height"] 94 | path = Path(im["file_name"]) # image filename 95 | try: 96 | with open(dir / 'labels' / 'train' / path.with_suffix('.txt').name, 'a') as file: 97 | annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None) 98 | for a in coco.loadAnns(annIds): 99 | x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner) 100 | x, y = x + w / 2, y + h / 2 # xy to center 101 | file.write(f"{cid} {x / width:.5f} {y / height:.5f} {w / width:.5f} {h / height:.5f}\n") 102 | 103 | except Exception as e: 104 | print(e) 105 | -------------------------------------------------------------------------------- /data/SKU-110K.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 3 | # Example usage: python train.py --data SKU-110K.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── SKU-110K ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/SKU-110K # dataset root dir 12 | train: train.txt # train images (relative to 'path') 8219 images 13 | val: val.txt # val images (relative to 'path') 588 images 14 | test: test.txt # test images (optional) 2936 images 15 | 16 | # Classes 17 | nc: 1 # number of classes 18 | names: ['object'] # class names 19 | 20 | 21 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 22 | download: | 23 | import shutil 24 | from tqdm import tqdm 25 | from utils.general import np, pd, Path, download, xyxy2xywh 26 | 27 | # Download 28 | dir = Path(yaml['path']) # dataset root dir 29 | parent = Path(dir.parent) # download dir 30 | urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz'] 31 | download(urls, dir=parent, delete=False) 32 | 33 | # Rename directories 34 | if dir.exists(): 35 | shutil.rmtree(dir) 36 | (parent / 'SKU110K_fixed').rename(dir) # rename dir 37 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir 38 | 39 | # Convert labels 40 | names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names 41 | for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv': 42 | x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations 43 | images, unique_images = x[:, 0], np.unique(x[:, 0]) 44 | with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f: 45 | f.writelines(f'./images/{s}\n' for s in unique_images) 46 | for im in tqdm(unique_images, desc=f'Converting {dir / d}'): 47 | cls = 0 # single-class dataset 48 | with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f: 49 | for r in x[images == im]: 50 | w, h = r[6], r[7] # image width, height 51 | xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance 52 | f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label 53 | -------------------------------------------------------------------------------- /data/VOC.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC 3 | # Example usage: python train.py --data VOC.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── VOC ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/VOC 12 | train: # train images (relative to 'path') 16551 images 13 | - images/train2012 14 | - images/train2007 15 | - images/val2012 16 | - images/val2007 17 | val: # val images (relative to 'path') 4952 images 18 | - images/test2007 19 | test: # test images (optional) 20 | - images/test2007 21 | 22 | # Classes 23 | nc: 20 # number of classes 24 | names: ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 25 | 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'] # class names 26 | 27 | 28 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 29 | download: | 30 | import xml.etree.ElementTree as ET 31 | 32 | from tqdm import tqdm 33 | from utils.general import download, Path 34 | 35 | 36 | def convert_label(path, lb_path, year, image_id): 37 | def convert_box(size, box): 38 | dw, dh = 1. / size[0], 1. / size[1] 39 | x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2] 40 | return x * dw, y * dh, w * dw, h * dh 41 | 42 | in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml') 43 | out_file = open(lb_path, 'w') 44 | tree = ET.parse(in_file) 45 | root = tree.getroot() 46 | size = root.find('size') 47 | w = int(size.find('width').text) 48 | h = int(size.find('height').text) 49 | 50 | for obj in root.iter('object'): 51 | cls = obj.find('name').text 52 | if cls in yaml['names'] and not int(obj.find('difficult').text) == 1: 53 | xmlbox = obj.find('bndbox') 54 | bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')]) 55 | cls_id = yaml['names'].index(cls) # class id 56 | out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n') 57 | 58 | 59 | # Download 60 | dir = Path(yaml['path']) # dataset root dir 61 | url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' 62 | urls = [url + 'VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images 63 | url + 'VOCtest_06-Nov-2007.zip', # 438MB, 4953 images 64 | url + 'VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images 65 | download(urls, dir=dir / 'images', delete=False) 66 | 67 | # Convert 68 | path = dir / f'images/VOCdevkit' 69 | for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'): 70 | imgs_path = dir / 'images' / f'{image_set}{year}' 71 | lbs_path = dir / 'labels' / f'{image_set}{year}' 72 | imgs_path.mkdir(exist_ok=True, parents=True) 73 | lbs_path.mkdir(exist_ok=True, parents=True) 74 | 75 | image_ids = open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt').read().strip().split() 76 | for id in tqdm(image_ids, desc=f'{image_set}{year}'): 77 | f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path 78 | lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path 79 | f.rename(imgs_path / f.name) # move image 80 | convert_label(path, lb_path, year, id) # convert labels to YOLO format 81 | -------------------------------------------------------------------------------- /data/VisDrone.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset 3 | # Example usage: python train.py --data VisDrone.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── VisDrone ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/VisDrone # dataset root dir 12 | train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images 13 | val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images 14 | test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images 15 | 16 | # Classes 17 | nc: 10 # number of classes 18 | names: ['pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor'] 19 | 20 | 21 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 22 | download: | 23 | from utils.general import download, os, Path 24 | 25 | def visdrone2yolo(dir): 26 | from PIL import Image 27 | from tqdm import tqdm 28 | 29 | def convert_box(size, box): 30 | # Convert VisDrone box to YOLO xywh box 31 | dw = 1. / size[0] 32 | dh = 1. / size[1] 33 | return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh 34 | 35 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory 36 | pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}') 37 | for f in pbar: 38 | img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size 39 | lines = [] 40 | with open(f, 'r') as file: # read annotation.txt 41 | for row in [x.split(',') for x in file.read().strip().splitlines()]: 42 | if row[4] == '0': # VisDrone 'ignored regions' class 0 43 | continue 44 | cls = int(row[5]) - 1 45 | box = convert_box(img_size, tuple(map(int, row[:4]))) 46 | lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n") 47 | with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl: 48 | fl.writelines(lines) # write label.txt 49 | 50 | 51 | # Download 52 | dir = Path(yaml['path']) # dataset root dir 53 | urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip', 54 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip', 55 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip', 56 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip'] 57 | download(urls, dir=dir) 58 | 59 | # Convert 60 | for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev': 61 | visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels 62 | -------------------------------------------------------------------------------- /data/coco.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # COCO 2017 dataset http://cocodataset.org 3 | # Example usage: python train.py --data coco.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── coco ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/coco # dataset root dir 12 | train: train2017.txt # train images (relative to 'path') 118287 images 13 | val: val2017.txt # train images (relative to 'path') 5000 images 14 | test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794 15 | 16 | # Classes 17 | nc: 80 # number of classes 18 | names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 19 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 20 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 21 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 22 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 23 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 24 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 25 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 26 | 'hair drier', 'toothbrush'] # class names 27 | 28 | 29 | # Download script/URL (optional) 30 | download: | 31 | from utils.general import download, Path 32 | 33 | # Download labels 34 | segments = False # segment or box labels 35 | dir = Path(yaml['path']) # dataset root dir 36 | url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' 37 | urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels 38 | download(urls, dir=dir.parent) 39 | 40 | # Download data 41 | urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images 42 | 'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images 43 | 'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional) 44 | download(urls, dir=dir / 'images', threads=3) 45 | -------------------------------------------------------------------------------- /data/coco128.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 2 | # COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) 3 | # Example usage: python train.py --data coco128.yaml 4 | # parent 5 | # ├── yolov5 6 | # └── datasets 7 | # └── coco128 ← downloads here 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/coco128 # dataset root dir 12 | train: images/train2017 # train images (relative to 'path') 128 images 13 | val: images/train2017 # val images (relative to 'path') 128 images 14 | test: # test images (optional) 15 | 16 | # Classes 17 | nc: 80 # number of classes 18 | names: ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 19 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 20 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 21 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 22 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 23 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 24 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 25 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 26 | 'hair drier', 'toothbrush'] # class names 27 | 28 | 29 | # Download script/URL (optional) 30 | download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip -------------------------------------------------------------------------------- /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/hyps/hyp.finetune_objects365.yaml: -------------------------------------------------------------------------------- 1 | lr0: 0.00258 2 | lrf: 0.17 3 | momentum: 0.779 4 | weight_decay: 0.00058 5 | warmup_epochs: 1.33 6 | warmup_momentum: 0.86 7 | warmup_bias_lr: 0.0711 8 | box: 0.0539 9 | cls: 0.299 10 | cls_pw: 0.825 11 | obj: 0.632 12 | obj_pw: 1.0 13 | iou_t: 0.2 14 | anchor_t: 3.44 15 | anchors: 3.2 16 | fl_gamma: 0.0 17 | hsv_h: 0.0188 18 | hsv_s: 0.704 19 | hsv_v: 0.36 20 | degrees: 0.0 21 | translate: 0.0902 22 | scale: 0.491 23 | shear: 0.0 24 | perspective: 0.0 25 | flipud: 0.0 26 | fliplr: 0.5 27 | mosaic: 1.0 28 | mixup: 0.0 29 | copy_paste: 0.0 30 | -------------------------------------------------------------------------------- /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/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/images/bus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/data/images/bus.jpg -------------------------------------------------------------------------------- /data/images/zidane.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/data/images/zidane.jpg -------------------------------------------------------------------------------- /data/scripts/download_weights.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # YOLOv5 🚀 by Ultralytics https://ultralytics.com, licensed under GNU GPL v3.0 3 | # Download latest models from https://github.com/ultralytics/yolov5/releases 4 | # Example usage: bash path/to/download_weights.sh 5 | # parent 6 | # └── yolov5 7 | # ├── yolov5s.pt ← downloads here 8 | # ├── yolov5m.pt 9 | # └── ... 10 | 11 | python - <= cls >= 0, f'incorrect class index {cls}' 74 | 75 | # Write YOLO label 76 | if id not in shapes: 77 | shapes[id] = Image.open(file).size 78 | box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True) 79 | with open((labels / id).with_suffix('.txt'), 'a') as f: 80 | f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt 81 | except Exception as e: 82 | print(f'WARNING: skipping one label for {file}: {e}') 83 | 84 | 85 | # Download manually from https://challenge.xviewdataset.org 86 | dir = Path(yaml['path']) # dataset root dir 87 | # urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels 88 | # 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images 89 | # 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels) 90 | # download(urls, dir=dir, delete=False) 91 | 92 | # Convert labels 93 | convert_labels(dir / 'xView_train.geojson') 94 | 95 | # Move images 96 | images = Path(dir / 'images') 97 | images.mkdir(parents=True, exist_ok=True) 98 | Path(dir / 'train_images').rename(dir / 'images' / 'train') 99 | Path(dir / 'val_images').rename(dir / 'images' / 'val') 100 | 101 | # Split 102 | autosplit(dir / 'images' / 'train') 103 | -------------------------------------------------------------------------------- /detect.py: -------------------------------------------------------------------------------- 1 | """Run inference with a YOLOv5 model on images, videos, directories, streams 2 | 3 | Usage: 4 | $ python path/to/detect.py --source path/to/img.jpg --weights yolov5s.pt --img 640 5 | """ 6 | 7 | import argparse 8 | import sys 9 | import time 10 | from pathlib import Path 11 | 12 | import cv2 13 | import torch 14 | import torch.backends.cudnn as cudnn 15 | 16 | FILE = Path(__file__).absolute() 17 | sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path 18 | 19 | from models.experimental import attempt_load 20 | from utils.datasets import LoadStreams, LoadImages 21 | from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \ 22 | apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box 23 | from utils.plots import colors, plot_one_box 24 | from utils.torch_utils import select_device, load_classifier, time_sync 25 | 26 | 27 | @torch.no_grad() 28 | def run(weights='yolov5s.pt', # model.pt path(s) 29 | source='data/images', # file/dir/URL/glob, 0 for webcam 30 | imgsz=640, # inference size (pixels) 31 | conf_thres=0.25, # confidence threshold 32 | iou_thres=0.45, # NMS IOU threshold 33 | max_det=1000, # maximum detections per image 34 | device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu 35 | view_img=False, # show results 36 | save_txt=False, # save results to *.txt 37 | save_conf=False, # save confidences in --save-txt labels 38 | save_crop=False, # save cropped prediction boxes 39 | nosave=False, # do not save images/videos 40 | classes=None, # filter by class: --class 0, or --class 0 2 3 41 | agnostic_nms=False, # class-agnostic NMS 42 | augment=False, # augmented inference 43 | visualize=False, # visualize features 44 | update=False, # update all models 45 | project='static', # save results to project/name 46 | name='', # save results to project/name 47 | exist_ok=True, # existing project/name ok, do not increment 48 | line_thickness=3, # bounding box thickness (pixels) 49 | hide_labels=False, # hide labels 50 | hide_conf=False, # hide confidences 51 | half=False, # use FP16 half-precision inference 52 | ): 53 | save_img = not nosave and not source.endswith('.txt') # save inference images 54 | webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith( 55 | ('rtsp://', 'rtmp://', 'http://', 'https://')) 56 | 57 | # Directories 58 | save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run 59 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir 60 | 61 | # Initialize 62 | set_logging() 63 | device = select_device(device) 64 | half &= device.type != 'cpu' # half precision only supported on CUDA 65 | 66 | # Load model 67 | w = weights[0] if isinstance(weights, list) else weights 68 | classify, pt, onnx = False, w.endswith('.pt'), w.endswith('.onnx') # inference type 69 | stride, names = 64, [f'class{i}' for i in range(1000)] # assign defaults 70 | if pt: 71 | model = attempt_load(weights, map_location=device) # load FP32 model 72 | stride = int(model.stride.max()) # model stride 73 | names = model.module.names if hasattr(model, 'module') else model.names # get class names 74 | if half: 75 | model.half() # to FP16 76 | if classify: # second-stage classifier 77 | modelc = load_classifier(name='resnet50', n=2) # initialize 78 | modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval() 79 | elif onnx: 80 | check_requirements(('onnx', 'onnxruntime')) 81 | import onnxruntime 82 | session = onnxruntime.InferenceSession(w, None) 83 | imgsz = check_img_size(imgsz, s=stride) # check image size 84 | 85 | # Dataloader 86 | if webcam: 87 | view_img = check_imshow() 88 | cudnn.benchmark = True # set True to speed up constant image size inference 89 | dataset = LoadStreams(source, img_size=imgsz, stride=stride) 90 | bs = len(dataset) # batch_size 91 | else: 92 | dataset = LoadImages(source, img_size=imgsz, stride=stride) 93 | bs = 1 # batch_size 94 | vid_path, vid_writer = [None] * bs, [None] * bs 95 | 96 | # Run inference 97 | if pt and device.type != 'cpu': 98 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once 99 | t0 = time.time() 100 | for path, img, im0s, vid_cap in dataset: 101 | if pt: 102 | img = torch.from_numpy(img).to(device) 103 | img = img.half() if half else img.float() # uint8 to fp16/32 104 | elif onnx: 105 | img = img.astype('float32') 106 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 107 | if len(img.shape) == 3: 108 | img = img[None] # expand for batch dim 109 | 110 | # Inference 111 | t1 = time_sync() 112 | if pt: 113 | visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False 114 | pred = model(img, augment=augment, visualize=visualize)[0] 115 | elif onnx: 116 | pred = torch.tensor(session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: img})) 117 | 118 | # NMS 119 | pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) 120 | t2 = time_sync() 121 | 122 | # Second-stage classifier (optional) 123 | if classify: 124 | pred = apply_classifier(pred, modelc, img, im0s) 125 | 126 | # Process predictions 127 | for i, det in enumerate(pred): # detections per image 128 | if webcam: # batch_size >= 1 129 | p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count 130 | else: 131 | p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0) 132 | 133 | p = Path(p) # to Path 134 | save_path = str(save_dir / p.name) # img.jpg 135 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt 136 | s += '%gx%g ' % img.shape[2:] # print string 137 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh 138 | imc = im0.copy() if save_crop else im0 # for save_crop 139 | if len(det): 140 | # Rescale boxes from img_size to im0 size 141 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 142 | 143 | # Print results 144 | for c in det[:, -1].unique(): 145 | n = (det[:, -1] == c).sum() # detections per class 146 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string 147 | 148 | # Write results 149 | for *xyxy, conf, cls in reversed(det): 150 | if save_txt: # Write to file 151 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 152 | line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format 153 | with open(txt_path + '.txt', 'a') as f: 154 | f.write(('%g ' * len(line)).rstrip() % line + '\n') 155 | 156 | if save_img or save_crop or view_img: # Add bbox to image 157 | c = int(cls) # integer class 158 | label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') 159 | plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness) 160 | if save_crop: 161 | save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) 162 | 163 | # Print time (inference + NMS) 164 | print(f'{s}Done. ({t2 - t1:.3f}s)') 165 | 166 | # Stream results 167 | if view_img: 168 | cv2.imshow(str(p), im0) 169 | cv2.waitKey(1) # 1 millisecond 170 | 171 | # Save results (image with detections) 172 | if save_img: 173 | if dataset.mode == 'image': 174 | cv2.imwrite(save_path, im0) 175 | else: # 'video' or 'stream' 176 | if vid_path[i] != save_path: # new video 177 | vid_path[i] = save_path 178 | if isinstance(vid_writer[i], cv2.VideoWriter): 179 | vid_writer[i].release() # release previous video writer 180 | if vid_cap: # video 181 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 182 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 183 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 184 | else: # stream 185 | fps, w, h = 30, im0.shape[1], im0.shape[0] 186 | save_path += '.mp4' 187 | vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) 188 | vid_writer[i].write(im0) 189 | 190 | if save_txt or save_img: 191 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' 192 | print(f"Results saved to {colorstr('bold', save_dir)}{s}") 193 | 194 | if update: 195 | strip_optimizer(weights) # update model (to fix SourceChangeWarning) 196 | 197 | print(f'Done. ({time.time() - t0:.3f}s)') 198 | 199 | 200 | def parse_opt(): 201 | parser = argparse.ArgumentParser() 202 | parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)') 203 | parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam') 204 | parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') 205 | parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold') 206 | parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold') 207 | parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image') 208 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 209 | parser.add_argument('--view-img', action='store_true', help='show results') 210 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 211 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') 212 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes') 213 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos') 214 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') 215 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 216 | parser.add_argument('--augment', action='store_true', help='augmented inference') 217 | parser.add_argument('--visualize', action='store_true', help='visualize features') 218 | parser.add_argument('--update', action='store_true', help='update all models') 219 | parser.add_argument('--project', default='static', help='save results to project/name') 220 | parser.add_argument('--name', default='', help='save results to project/name') 221 | parser.add_argument('--exist-ok', default=True, action='store_true', help='existing project/name ok, do not increment') 222 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') 223 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') 224 | parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') 225 | parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') 226 | opt = parser.parse_args() 227 | return opt 228 | 229 | 230 | def main(opt): 231 | print(colorstr('detect: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) 232 | check_requirements(exclude=('tensorboard', 'thop')) 233 | run(**vars(opt)) 234 | 235 | 236 | if __name__ == "__main__": 237 | opt = parse_opt() 238 | main(opt) 239 | -------------------------------------------------------------------------------- /doc.odt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/doc.odt -------------------------------------------------------------------------------- /instance/uploads/asmit.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/instance/uploads/asmit.jpg -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/models/__init__.py -------------------------------------------------------------------------------- /models/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/models/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /models/__pycache__/common.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/models/__pycache__/common.cpython-39.pyc -------------------------------------------------------------------------------- /models/__pycache__/experimental.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/models/__pycache__/experimental.cpython-39.pyc -------------------------------------------------------------------------------- /models/__pycache__/yolo.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/models/__pycache__/yolo.cpython-39.pyc -------------------------------------------------------------------------------- /models/experimental.py: -------------------------------------------------------------------------------- 1 | # YOLOv5 experimental modules 2 | 3 | import numpy as np 4 | import torch 5 | import torch.nn as nn 6 | 7 | from models.common import Conv, DWConv 8 | from utils.downloads import attempt_download 9 | 10 | 11 | class CrossConv(nn.Module): 12 | # Cross Convolution Downsample 13 | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): 14 | # ch_in, ch_out, kernel, stride, groups, expansion, shortcut 15 | super().__init__() 16 | c_ = int(c2 * e) # hidden channels 17 | self.cv1 = Conv(c1, c_, (1, k), (1, s)) 18 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) 19 | self.add = shortcut and c1 == c2 20 | 21 | def forward(self, x): 22 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) 23 | 24 | 25 | class Sum(nn.Module): 26 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 27 | def __init__(self, n, weight=False): # n: number of inputs 28 | super().__init__() 29 | self.weight = weight # apply weights boolean 30 | self.iter = range(n - 1) # iter object 31 | if weight: 32 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights 33 | 34 | def forward(self, x): 35 | y = x[0] # no weight 36 | if self.weight: 37 | w = torch.sigmoid(self.w) * 2 38 | for i in self.iter: 39 | y = y + x[i + 1] * w[i] 40 | else: 41 | for i in self.iter: 42 | y = y + x[i + 1] 43 | return y 44 | 45 | 46 | class GhostConv(nn.Module): 47 | # Ghost Convolution https://github.com/huawei-noah/ghostnet 48 | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups 49 | super().__init__() 50 | c_ = c2 // 2 # hidden channels 51 | self.cv1 = Conv(c1, c_, k, s, None, g, act) 52 | self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) 53 | 54 | def forward(self, x): 55 | y = self.cv1(x) 56 | return torch.cat([y, self.cv2(y)], 1) 57 | 58 | 59 | class GhostBottleneck(nn.Module): 60 | # Ghost Bottleneck https://github.com/huawei-noah/ghostnet 61 | def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride 62 | super().__init__() 63 | c_ = c2 // 2 64 | self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw 65 | DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw 66 | GhostConv(c_, c2, 1, 1, act=False)) # pw-linear 67 | self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), 68 | Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() 69 | 70 | def forward(self, x): 71 | return self.conv(x) + self.shortcut(x) 72 | 73 | 74 | class MixConv2d(nn.Module): 75 | # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595 76 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): 77 | super().__init__() 78 | groups = len(k) 79 | if equal_ch: # equal c_ per group 80 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices 81 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels 82 | else: # equal weight.numel() per group 83 | b = [c2] + [0] * groups 84 | a = np.eye(groups + 1, groups, k=-1) 85 | a -= np.roll(a, 1, axis=1) 86 | a *= np.array(k) ** 2 87 | a[0] = 1 88 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b 89 | 90 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)]) 91 | self.bn = nn.BatchNorm2d(c2) 92 | self.act = nn.LeakyReLU(0.1, inplace=True) 93 | 94 | def forward(self, x): 95 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) 96 | 97 | 98 | class Ensemble(nn.ModuleList): 99 | # Ensemble of models 100 | def __init__(self): 101 | super().__init__() 102 | 103 | def forward(self, x, augment=False, profile=False, visualize=False): 104 | y = [] 105 | for module in self: 106 | y.append(module(x, augment, profile, visualize)[0]) 107 | # y = torch.stack(y).max(0)[0] # max ensemble 108 | # y = torch.stack(y).mean(0) # mean ensemble 109 | y = torch.cat(y, 1) # nms ensemble 110 | return y, None # inference, train output 111 | 112 | 113 | def attempt_load(weights, map_location=None, inplace=True): 114 | from models.yolo import Detect, Model 115 | 116 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a 117 | model = Ensemble() 118 | for w in weights if isinstance(weights, list) else [weights]: 119 | ckpt = torch.load(attempt_download(w), map_location=map_location) # load 120 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model 121 | 122 | # Compatibility updates 123 | for m in model.modules(): 124 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]: 125 | m.inplace = inplace # pytorch 1.7.0 compatibility 126 | elif type(m) is Conv: 127 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 128 | 129 | if len(model) == 1: 130 | return model[-1] # return model 131 | else: 132 | print(f'Ensemble created with {weights}\n') 133 | for k in ['names']: 134 | setattr(model, k, getattr(model[-1], k)) 135 | model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride 136 | return model # return ensemble 137 | -------------------------------------------------------------------------------- /models/hub/anchors.yaml: -------------------------------------------------------------------------------- 1 | # Default YOLOv5 anchors for COCO data 2 | 3 | 4 | # P5 ------------------------------------------------------------------------------------------------------------------- 5 | # P5-640: 6 | anchors_p5_640: 7 | - [10,13, 16,30, 33,23] # P3/8 8 | - [30,61, 62,45, 59,119] # P4/16 9 | - [116,90, 156,198, 373,326] # P5/32 10 | 11 | 12 | # P6 ------------------------------------------------------------------------------------------------------------------- 13 | # P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387 14 | anchors_p6_640: 15 | - [9,11, 21,19, 17,41] # P3/8 16 | - [43,32, 39,70, 86,64] # P4/16 17 | - [65,131, 134,130, 120,265] # P5/32 18 | - [282,180, 247,354, 512,387] # P6/64 19 | 20 | # P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792 21 | anchors_p6_1280: 22 | - [19,27, 44,40, 38,94] # P3/8 23 | - [96,68, 86,152, 180,137] # P4/16 24 | - [140,301, 303,264, 238,542] # P5/32 25 | - [436,615, 739,380, 925,792] # P6/64 26 | 27 | # P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187 28 | anchors_p6_1920: 29 | - [28,41, 67,59, 57,141] # P3/8 30 | - [144,103, 129,227, 270,205] # P4/16 31 | - [209,452, 455,396, 358,812] # P5/32 32 | - [653,922, 1109,570, 1387,1187] # P6/64 33 | 34 | 35 | # P7 ------------------------------------------------------------------------------------------------------------------- 36 | # P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372 37 | anchors_p7_640: 38 | - [11,11, 13,30, 29,20] # P3/8 39 | - [30,46, 61,38, 39,92] # P4/16 40 | - [78,80, 146,66, 79,163] # P5/32 41 | - [149,150, 321,143, 157,303] # P6/64 42 | - [257,402, 359,290, 524,372] # P7/128 43 | 44 | # P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818 45 | anchors_p7_1280: 46 | - [19,22, 54,36, 32,77] # P3/8 47 | - [70,83, 138,71, 75,173] # P4/16 48 | - [165,159, 148,334, 375,151] # P5/32 49 | - [334,317, 251,626, 499,474] # P6/64 50 | - [750,326, 534,814, 1079,818] # P7/128 51 | 52 | # P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227 53 | anchors_p7_1920: 54 | - [29,34, 81,55, 47,115] # P3/8 55 | - [105,124, 207,107, 113,259] # P4/16 56 | - [247,238, 222,500, 563,227] # P5/32 57 | - [501,476, 376,939, 749,711] # P6/64 58 | - [1126,489, 801,1222, 1618,1227] # P7/128 59 | -------------------------------------------------------------------------------- /models/hub/yolov3-spp.yaml: -------------------------------------------------------------------------------- 1 | # Parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # darknet53 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Conv, [32, 3, 1]], # 0 14 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 15 | [-1, 1, Bottleneck, [64]], 16 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 17 | [-1, 2, Bottleneck, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 19 | [-1, 8, Bottleneck, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 21 | [-1, 8, Bottleneck, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 23 | [-1, 4, Bottleneck, [1024]], # 10 24 | ] 25 | 26 | # YOLOv3-SPP head 27 | head: 28 | [[-1, 1, Bottleneck, [1024, False]], 29 | [-1, 1, SPP, [512, [5, 9, 13]]], 30 | [-1, 1, Conv, [1024, 3, 1]], 31 | [-1, 1, Conv, [512, 1, 1]], 32 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) 33 | 34 | [-2, 1, Conv, [256, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 8], 1, Concat, [1]], # cat backbone P4 37 | [-1, 1, Bottleneck, [512, False]], 38 | [-1, 1, Bottleneck, [512, False]], 39 | [-1, 1, Conv, [256, 1, 1]], 40 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) 41 | 42 | [-2, 1, Conv, [128, 1, 1]], 43 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 44 | [[-1, 6], 1, Concat, [1]], # cat backbone P3 45 | [-1, 1, Bottleneck, [256, False]], 46 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) 47 | 48 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 49 | ] 50 | -------------------------------------------------------------------------------- /models/hub/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/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/yolov5-bifpn.yaml: -------------------------------------------------------------------------------- 1 | # Parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]] 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3, [1024, False]], # 9 23 | ] 24 | 25 | # YOLOv5 BiFPN head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14, 6], 1, Concat, [1]], # cat P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /models/hub/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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/yolov5s-transformer.yaml: -------------------------------------------------------------------------------- 1 | # Parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 0.33 # model depth multiple 4 | width_multiple: 0.50 # layer channel multiple 5 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3TR, [1024, False]], # 9 <-------- C3TR() Transformer module 23 | ] 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14], 1, Concat, [1]], # cat head P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /models/hub/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/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 isinstance(m, (Conv, DWConv)) 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.forward_fuse # 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 | -------------------------------------------------------------------------------- /models/yolov5l.yaml: -------------------------------------------------------------------------------- 1 | # Parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3, [1024, False]], # 9 23 | ] 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14], 1, Concat, [1]], # cat head P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /models/yolov5m.yaml: -------------------------------------------------------------------------------- 1 | # Parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 0.67 # model depth multiple 4 | width_multiple: 0.75 # layer channel multiple 5 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3, [1024, False]], # 9 23 | ] 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14], 1, Concat, [1]], # cat head P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /models/yolov5s.yaml: -------------------------------------------------------------------------------- 1 | # Parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 0.33 # model depth multiple 4 | width_multiple: 0.50 # layer channel multiple 5 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3, [1024, False]], # 9 23 | ] 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14], 1, Concat, [1]], # cat head P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /models/yolov5x.yaml: -------------------------------------------------------------------------------- 1 | # Parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.33 # model depth multiple 4 | width_multiple: 1.25 # layer channel multiple 5 | anchors: 6 | - [10,13, 16,30, 33,23] # P3/8 7 | - [30,61, 62,45, 59,119] # P4/16 8 | - [116,90, 156,198, 373,326] # P5/32 9 | 10 | # YOLOv5 backbone 11 | backbone: 12 | # [from, number, module, args] 13 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 14 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 15 | [-1, 3, C3, [128]], 16 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 17 | [-1, 9, C3, [256]], 18 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 19 | [-1, 9, C3, [512]], 20 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 21 | [-1, 1, SPP, [1024, [5, 9, 13]]], 22 | [-1, 3, C3, [1024, False]], # 9 23 | ] 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [512, 1, 1]], 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 30 | [-1, 3, C3, [512, False]], # 13 31 | 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 34 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 35 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 36 | 37 | [-1, 1, Conv, [256, 3, 2]], 38 | [[-1, 14], 1, Concat, [1]], # cat head P4 39 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 40 | 41 | [-1, 1, Conv, [512, 3, 2]], 42 | [[-1, 10], 1, Concat, [1]], # cat head P5 43 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 44 | 45 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 46 | ] 47 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | absl-py==1.1.0 2 | asttokens==2.0.5 3 | backcall==0.2.0 4 | cachetools==5.2.0 5 | certifi==2022.6.15 6 | charset-normalizer==2.1.0 7 | cycler==0.11.0 8 | decorator==5.1.1 9 | executing==0.8.3 10 | fonttools==4.34.2 11 | google-auth==2.9.0 12 | google-auth-oauthlib==0.4.6 13 | grpcio==1.47.0 14 | idna==3.3 15 | ipython==8.4.0 16 | jedi==0.18.1 17 | kiwisolver==1.4.3 18 | Markdown==3.3.7 19 | matplotlib==3.5.2 20 | matplotlib-inline==0.1.3 21 | numpy==1.23.0 22 | oauthlib==3.2.0 23 | opencv-python==4.6.0.66 24 | packaging==21.3 25 | pandas==1.4.3 26 | parso==0.8.3 27 | pexpect==4.8.0 28 | pickleshare==0.7.5 29 | Pillow==9.2.0 30 | prompt-toolkit==3.0.30 31 | protobuf==3.19.4 32 | psutil==5.9.1 33 | ptyprocess==0.7.0 34 | pure-eval==0.2.2 35 | pyasn1==0.4.8 36 | pyasn1-modules==0.2.8 37 | Pygments==2.12.0 38 | pyparsing==3.0.9 39 | python-dateutil==2.8.2 40 | pytz==2022.1 41 | PyYAML==6.0 42 | requests==2.28.1 43 | requests-oauthlib==1.3.1 44 | rsa==4.8 45 | scipy==1.8.1 46 | seaborn==0.11.2 47 | six==1.16.0 48 | stack-data==0.3.0 49 | tensorboard==2.9.1 50 | tensorboard-data-server==0.6.1 51 | tensorboard-plugin-wit==1.8.1 52 | thop==0.1.0.post2207010342 53 | torch==1.11.0 54 | torchvision==0.12.0 55 | tqdm==4.64.0 56 | traitlets==5.3.0 57 | typing_extensions==4.3.0 58 | urllib3==1.26.9 59 | wcwidth==0.2.5 60 | Werkzeug==2.1.2 61 | -------------------------------------------------------------------------------- /static/asmit.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/static/asmit.jpg -------------------------------------------------------------------------------- /static/bus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/static/bus.jpg -------------------------------------------------------------------------------- /static/index.css: -------------------------------------------------------------------------------- 1 | html { 2 | text-align: center; 3 | background-color: #282c34; 4 | color: white; 5 | } 6 | 7 | .App-header { 8 | background-color: #282c34; 9 | min-height: 100vh; 10 | display: flex; 11 | flex-direction: column; 12 | align-items: center; 13 | justify-content: center; 14 | font-size: calc(10px + 2vmin); 15 | color: white; 16 | } 17 | 18 | .App-link { 19 | color: #61dafb; 20 | } 21 | 22 | .pre_img { 23 | height: 600px; 24 | width: 600px; 25 | /* background-color: white; */ 26 | } 27 | 28 | input[type="file"] { 29 | background-color: #4caf50; 30 | border: none; 31 | color: white; 32 | padding: 15px 32px; 33 | text-align: center; 34 | text-decoration: none; 35 | display: inline-block; 36 | font-size: 16px; 37 | box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); 38 | margin: 40px 40px; 39 | /* display: none; */ 40 | } 41 | 42 | #pre { 43 | background-color: #4caf50; /* Green */ 44 | border: none; 45 | color: white; 46 | padding: 15px 32px; 47 | text-align: center; 48 | text-decoration: none; 49 | display: inline-block; 50 | font-size: 16px; 51 | box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19); 52 | margin: 10px 40px; 53 | } 54 | 55 | p { 56 | margin: 50px; 57 | font-size: 72px; 58 | } 59 | 60 | #link { 61 | visibility: hidden; 62 | } 63 | 64 | 65 | .button { 66 | background-color: #4CAF50; /* Green */ 67 | border: none; 68 | color: white; 69 | padding: 15px 32px; 70 | text-align: center; 71 | text-decoration: none; 72 | display: inline-block; 73 | font-size: 16px; 74 | } 75 | 76 | .line{ 77 | width: 10px; 78 | color: white; 79 | width: 75%; 80 | } -------------------------------------------------------------------------------- /static/index.js: -------------------------------------------------------------------------------- 1 | window.onload = () => { 2 | $("#sendbutton").click(() => { 3 | imagebox = $("#imagebox"); 4 | link = $("#link"); 5 | input = $("#imageinput")[0]; 6 | if (input.files && input.files[0]) { 7 | let formData = new FormData(); 8 | formData.append("video", input.files[0]); 9 | $.ajax({ 10 | url: "/detect", // fix this to your liking 11 | type: "POST", 12 | data: formData, 13 | cache: false, 14 | processData: false, 15 | contentType: false, 16 | error: function (data) { 17 | console.log("upload error", data); 18 | console.log(data.getAllResponseHeaders()); 19 | }, 20 | success: function (data) { 21 | console.log(data); 22 | // bytestring = data["status"]; 23 | // image = bytestring.split("'")[1]; 24 | $("#link").css("visibility", "visible"); 25 | $("#download").attr("href", "static/" + data); 26 | console.log(data); 27 | }, 28 | }); 29 | } 30 | }); 31 | $("#opencam").click(() => { 32 | console.log("evoked openCam"); 33 | $.ajax({ 34 | url: "/opencam", 35 | type: "GET", 36 | error: function (data) { 37 | console.log("upload error", data); 38 | }, 39 | success: function (data) { 40 | console.log(data); 41 | } 42 | }); 43 | }) 44 | }; 45 | 46 | function readUrl(input) { 47 | imagebox = $("#imagebox"); 48 | console.log(imagebox); 49 | console.log("evoked readUrl"); 50 | if (input.files && input.files[0]) { 51 | let reader = new FileReader(); 52 | reader.onload = function (e) { 53 | console.log(e.target); 54 | 55 | imagebox.attr("src", e.target.result); 56 | // imagebox.height(500); 57 | // imagebox.width(800); 58 | }; 59 | reader.readAsDataURL(input.files[0]); 60 | } 61 | } 62 | 63 | 64 | function openCam(e){ 65 | console.log("evoked openCam"); 66 | e.preventDefault(); 67 | console.log("evoked openCam"); 68 | console.log(e); 69 | } -------------------------------------------------------------------------------- /static/zidane.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/static/zidane.jpg -------------------------------------------------------------------------------- /templates/download.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 |
12 | 15 |
16 | 17 | 18 | -------------------------------------------------------------------------------- /templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | YOLO-Object Detection 5 | 6 | 11 | 12 | 13 | 14 |
15 |
16 |

Object Detection - YOLO

17 | 20 | 24 | 25 |
26 |
27 |
28 | 34 |
35 | 36 |
37 | 40 |
41 |
42 | 43 | 44 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/__init__.py -------------------------------------------------------------------------------- /utils/__pycache__/__init__.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/__pycache__/__init__.cpython-39.pyc -------------------------------------------------------------------------------- /utils/__pycache__/augmentations.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/__pycache__/augmentations.cpython-39.pyc -------------------------------------------------------------------------------- /utils/__pycache__/autoanchor.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/__pycache__/autoanchor.cpython-39.pyc -------------------------------------------------------------------------------- /utils/__pycache__/datasets.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/__pycache__/datasets.cpython-39.pyc -------------------------------------------------------------------------------- /utils/__pycache__/downloads.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/__pycache__/downloads.cpython-39.pyc -------------------------------------------------------------------------------- /utils/__pycache__/general.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/__pycache__/general.cpython-39.pyc -------------------------------------------------------------------------------- /utils/__pycache__/metrics.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/__pycache__/metrics.cpython-39.pyc -------------------------------------------------------------------------------- /utils/__pycache__/plots.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/__pycache__/plots.cpython-39.pyc -------------------------------------------------------------------------------- /utils/__pycache__/torch_utils.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/__pycache__/torch_utils.cpython-39.pyc -------------------------------------------------------------------------------- /utils/activations.py: -------------------------------------------------------------------------------- 1 | # Activation functions 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | 8 | # SiLU https://arxiv.org/pdf/1606.08415.pdf ---------------------------------------------------------------------------- 9 | class SiLU(nn.Module): # export-friendly version of nn.SiLU() 10 | @staticmethod 11 | def forward(x): 12 | return x * torch.sigmoid(x) 13 | 14 | 15 | class Hardswish(nn.Module): # export-friendly version of nn.Hardswish() 16 | @staticmethod 17 | def forward(x): 18 | # return x * F.hardsigmoid(x) # for torchscript and CoreML 19 | return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX 20 | 21 | 22 | # Mish https://github.com/digantamisra98/Mish -------------------------------------------------------------------------- 23 | class Mish(nn.Module): 24 | @staticmethod 25 | def forward(x): 26 | return x * F.softplus(x).tanh() 27 | 28 | 29 | class MemoryEfficientMish(nn.Module): 30 | class F(torch.autograd.Function): 31 | @staticmethod 32 | def forward(ctx, x): 33 | ctx.save_for_backward(x) 34 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) 35 | 36 | @staticmethod 37 | def backward(ctx, grad_output): 38 | x = ctx.saved_tensors[0] 39 | sx = torch.sigmoid(x) 40 | fx = F.softplus(x).tanh() 41 | return grad_output * (fx + x * sx * (1 - fx * fx)) 42 | 43 | def forward(self, x): 44 | return self.F.apply(x) 45 | 46 | 47 | # FReLU https://arxiv.org/abs/2007.11824 ------------------------------------------------------------------------------- 48 | class FReLU(nn.Module): 49 | def __init__(self, c1, k=3): # ch_in, kernel 50 | super().__init__() 51 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) 52 | self.bn = nn.BatchNorm2d(c1) 53 | 54 | def forward(self, x): 55 | return torch.max(x, self.bn(self.conv(x))) 56 | 57 | 58 | # ACON https://arxiv.org/pdf/2009.04759.pdf ---------------------------------------------------------------------------- 59 | class AconC(nn.Module): 60 | r""" ACON activation (activate or not). 61 | AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter 62 | according to "Activate or Not: Learning Customized Activation" . 63 | """ 64 | 65 | def __init__(self, c1): 66 | super().__init__() 67 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) 68 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) 69 | self.beta = nn.Parameter(torch.ones(1, c1, 1, 1)) 70 | 71 | def forward(self, x): 72 | dpx = (self.p1 - self.p2) * x 73 | return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x 74 | 75 | 76 | class MetaAconC(nn.Module): 77 | r""" ACON activation (activate or not). 78 | MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network 79 | according to "Activate or Not: Learning Customized Activation" . 80 | """ 81 | 82 | def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r 83 | super().__init__() 84 | c2 = max(r, c1 // r) 85 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) 86 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) 87 | self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True) 88 | self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True) 89 | # self.bn1 = nn.BatchNorm2d(c2) 90 | # self.bn2 = nn.BatchNorm2d(c1) 91 | 92 | def forward(self, x): 93 | y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True) 94 | # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891 95 | # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable 96 | beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed 97 | dpx = (self.p1 - self.p2) * x 98 | return dpx * torch.sigmoid(beta * dpx) + self.p2 * x 99 | -------------------------------------------------------------------------------- /utils/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 | -------------------------------------------------------------------------------- /utils/autoanchor.py: -------------------------------------------------------------------------------- 1 | # Auto-anchor utils 2 | 3 | import random 4 | 5 | import numpy as np 6 | import torch 7 | import yaml 8 | from tqdm import tqdm 9 | 10 | from utils.general import colorstr 11 | 12 | 13 | def check_anchor_order(m): 14 | # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary 15 | a = m.anchor_grid.prod(-1).view(-1) # anchor area 16 | da = a[-1] - a[0] # delta a 17 | ds = m.stride[-1] - m.stride[0] # delta s 18 | if da.sign() != ds.sign(): # same order 19 | print('Reversing anchor order') 20 | m.anchors[:] = m.anchors.flip(0) 21 | m.anchor_grid[:] = m.anchor_grid.flip(0) 22 | 23 | 24 | def check_anchors(dataset, model, thr=4.0, imgsz=640): 25 | # Check anchor fit to data, recompute if necessary 26 | prefix = colorstr('autoanchor: ') 27 | print(f'\n{prefix}Analyzing anchors... ', end='') 28 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() 29 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) 30 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale 31 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh 32 | 33 | def metric(k): # compute metric 34 | r = wh[:, None] / k[None] 35 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric 36 | best = x.max(1)[0] # best_x 37 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold 38 | bpr = (best > 1. / thr).float().mean() # best possible recall 39 | return bpr, aat 40 | 41 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors 42 | bpr, aat = metric(anchors) 43 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='') 44 | if bpr < 0.98: # threshold to recompute 45 | print('. Attempting to improve anchors, please wait...') 46 | na = m.anchor_grid.numel() // 2 # number of anchors 47 | try: 48 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) 49 | except Exception as e: 50 | print(f'{prefix}ERROR: {e}') 51 | new_bpr = metric(anchors)[0] 52 | if new_bpr > bpr: # replace anchors 53 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors) 54 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference 55 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss 56 | check_anchor_order(m) 57 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.') 58 | else: 59 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.') 60 | print('') # newline 61 | 62 | 63 | def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): 64 | """ Creates kmeans-evolved anchors from training dataset 65 | 66 | Arguments: 67 | dataset: path to data.yaml, or a loaded dataset 68 | n: number of anchors 69 | img_size: image size used for training 70 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 71 | gen: generations to evolve anchors using genetic algorithm 72 | verbose: print all results 73 | 74 | Return: 75 | k: kmeans evolved anchors 76 | 77 | Usage: 78 | from utils.autoanchor import *; _ = kmean_anchors() 79 | """ 80 | from scipy.cluster.vq import kmeans 81 | 82 | thr = 1. / thr 83 | prefix = colorstr('autoanchor: ') 84 | 85 | def metric(k, wh): # compute metrics 86 | r = wh[:, None] / k[None] 87 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric 88 | # x = wh_iou(wh, torch.tensor(k)) # iou metric 89 | return x, x.max(1)[0] # x, best_x 90 | 91 | def anchor_fitness(k): # mutation fitness 92 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh) 93 | return (best * (best > thr).float()).mean() # fitness 94 | 95 | def print_results(k): 96 | k = k[np.argsort(k.prod(1))] # sort small to large 97 | x, best = metric(k, wh0) 98 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr 99 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr') 100 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' 101 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='') 102 | for i, x in enumerate(k): 103 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg 104 | return k 105 | 106 | if isinstance(dataset, str): # *.yaml file 107 | with open(dataset, encoding='ascii', errors='ignore') as f: 108 | data_dict = yaml.safe_load(f) # model dict 109 | from utils.datasets import LoadImagesAndLabels 110 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) 111 | 112 | # Get label wh 113 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) 114 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh 115 | 116 | # Filter 117 | i = (wh0 < 3.0).any(1).sum() 118 | if i: 119 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.') 120 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels 121 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 122 | 123 | # Kmeans calculation 124 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...') 125 | s = wh.std(0) # sigmas for whitening 126 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance 127 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}') 128 | k *= s 129 | wh = torch.tensor(wh, dtype=torch.float32) # filtered 130 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered 131 | k = print_results(k) 132 | 133 | # Plot 134 | # k, d = [None] * 20, [None] * 20 135 | # for i in tqdm(range(1, 21)): 136 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance 137 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) 138 | # ax = ax.ravel() 139 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') 140 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh 141 | # ax[0].hist(wh[wh[:, 0]<100, 0],400) 142 | # ax[1].hist(wh[wh[:, 1]<100, 1],400) 143 | # fig.savefig('wh.png', dpi=200) 144 | 145 | # Evolve 146 | npr = np.random 147 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma 148 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar 149 | for _ in pbar: 150 | v = np.ones(sh) 151 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates) 152 | v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) 153 | kg = (k.copy() * v).clip(min=2.0) 154 | fg = anchor_fitness(kg) 155 | if fg > f: 156 | f, k = fg, kg.copy() 157 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' 158 | if verbose: 159 | print_results(k) 160 | 161 | return print_results(k) 162 | -------------------------------------------------------------------------------- /utils/aws/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/aws/__init__.py -------------------------------------------------------------------------------- /utils/aws/mime.sh: -------------------------------------------------------------------------------- 1 | # AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/ 2 | # This script will run on every instance restart, not only on first start 3 | # --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA --- 4 | 5 | Content-Type: multipart/mixed; boundary="//" 6 | MIME-Version: 1.0 7 | 8 | --// 9 | Content-Type: text/cloud-config; charset="us-ascii" 10 | MIME-Version: 1.0 11 | Content-Transfer-Encoding: 7bit 12 | Content-Disposition: attachment; filename="cloud-config.txt" 13 | 14 | #cloud-config 15 | cloud_final_modules: 16 | - [scripts-user, always] 17 | 18 | --// 19 | Content-Type: text/x-shellscript; charset="us-ascii" 20 | MIME-Version: 1.0 21 | Content-Transfer-Encoding: 7bit 22 | Content-Disposition: attachment; filename="userdata.txt" 23 | 24 | #!/bin/bash 25 | # --- paste contents of userdata.sh here --- 26 | --// 27 | -------------------------------------------------------------------------------- /utils/aws/resume.py: -------------------------------------------------------------------------------- 1 | # Resume all interrupted trainings in yolov5/ dir including DDP trainings 2 | # Usage: $ python utils/aws/resume.py 3 | 4 | import os 5 | import sys 6 | from pathlib import Path 7 | 8 | import torch 9 | import yaml 10 | 11 | sys.path.append('./') # to run '$ python *.py' files in subdirectories 12 | 13 | port = 0 # --master_port 14 | path = Path('').resolve() 15 | for last in path.rglob('*/**/last.pt'): 16 | ckpt = torch.load(last) 17 | if ckpt['optimizer'] is None: 18 | continue 19 | 20 | # Load opt.yaml 21 | with open(last.parent.parent / 'opt.yaml') as f: 22 | opt = yaml.safe_load(f) 23 | 24 | # Get device count 25 | d = opt['device'].split(',') # devices 26 | nd = len(d) # number of devices 27 | ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel 28 | 29 | if ddp: # multi-GPU 30 | port += 1 31 | cmd = f'python -m torch.distributed.run --nproc_per_node {nd} --master_port {port} train.py --resume {last}' 32 | else: # single-GPU 33 | cmd = f'python train.py --resume {last}' 34 | 35 | cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread 36 | print(cmd) 37 | os.system(cmd) 38 | -------------------------------------------------------------------------------- /utils/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 | -------------------------------------------------------------------------------- /utils/callbacks.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | class Callbacks: 4 | """" 5 | Handles all registered callbacks for YOLOv5 Hooks 6 | """ 7 | 8 | _callbacks = { 9 | 'on_pretrain_routine_start': [], 10 | 'on_pretrain_routine_end': [], 11 | 12 | 'on_train_start': [], 13 | 'on_train_epoch_start': [], 14 | 'on_train_batch_start': [], 15 | 'optimizer_step': [], 16 | 'on_before_zero_grad': [], 17 | 'on_train_batch_end': [], 18 | 'on_train_epoch_end': [], 19 | 20 | 'on_val_start': [], 21 | 'on_val_batch_start': [], 22 | 'on_val_image_end': [], 23 | 'on_val_batch_end': [], 24 | 'on_val_end': [], 25 | 26 | 'on_fit_epoch_end': [], # fit = train + val 27 | 'on_model_save': [], 28 | 'on_train_end': [], 29 | 30 | 'teardown': [], 31 | } 32 | 33 | def __init__(self): 34 | return 35 | 36 | def register_action(self, hook, name='', callback=None): 37 | """ 38 | Register a new action to a callback hook 39 | 40 | Args: 41 | hook The callback hook name to register the action to 42 | name The name of the action 43 | callback The callback to fire 44 | """ 45 | assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}" 46 | assert callable(callback), f"callback '{callback}' is not callable" 47 | self._callbacks[hook].append({'name': name, 'callback': callback}) 48 | 49 | def get_registered_actions(self, hook=None): 50 | """" 51 | Returns all the registered actions by callback hook 52 | 53 | Args: 54 | hook The name of the hook to check, defaults to all 55 | """ 56 | if hook: 57 | return self._callbacks[hook] 58 | else: 59 | return self._callbacks 60 | 61 | def run_callbacks(self, hook, *args, **kwargs): 62 | """ 63 | Loop through the registered actions and fire all callbacks 64 | """ 65 | for logger in self._callbacks[hook]: 66 | # print(f"Running callbacks.{logger['callback'].__name__}()") 67 | logger['callback'](*args, **kwargs) 68 | 69 | def on_pretrain_routine_start(self, *args, **kwargs): 70 | """ 71 | Fires all registered callbacks at the start of each pretraining routine 72 | """ 73 | self.run_callbacks('on_pretrain_routine_start', *args, **kwargs) 74 | 75 | def on_pretrain_routine_end(self, *args, **kwargs): 76 | """ 77 | Fires all registered callbacks at the end of each pretraining routine 78 | """ 79 | self.run_callbacks('on_pretrain_routine_end', *args, **kwargs) 80 | 81 | def on_train_start(self, *args, **kwargs): 82 | """ 83 | Fires all registered callbacks at the start of each training 84 | """ 85 | self.run_callbacks('on_train_start', *args, **kwargs) 86 | 87 | def on_train_epoch_start(self, *args, **kwargs): 88 | """ 89 | Fires all registered callbacks at the start of each training epoch 90 | """ 91 | self.run_callbacks('on_train_epoch_start', *args, **kwargs) 92 | 93 | def on_train_batch_start(self, *args, **kwargs): 94 | """ 95 | Fires all registered callbacks at the start of each training batch 96 | """ 97 | self.run_callbacks('on_train_batch_start', *args, **kwargs) 98 | 99 | def optimizer_step(self, *args, **kwargs): 100 | """ 101 | Fires all registered callbacks on each optimizer step 102 | """ 103 | self.run_callbacks('optimizer_step', *args, **kwargs) 104 | 105 | def on_before_zero_grad(self, *args, **kwargs): 106 | """ 107 | Fires all registered callbacks before zero grad 108 | """ 109 | self.run_callbacks('on_before_zero_grad', *args, **kwargs) 110 | 111 | def on_train_batch_end(self, *args, **kwargs): 112 | """ 113 | Fires all registered callbacks at the end of each training batch 114 | """ 115 | self.run_callbacks('on_train_batch_end', *args, **kwargs) 116 | 117 | def on_train_epoch_end(self, *args, **kwargs): 118 | """ 119 | Fires all registered callbacks at the end of each training epoch 120 | """ 121 | self.run_callbacks('on_train_epoch_end', *args, **kwargs) 122 | 123 | def on_val_start(self, *args, **kwargs): 124 | """ 125 | Fires all registered callbacks at the start of the validation 126 | """ 127 | self.run_callbacks('on_val_start', *args, **kwargs) 128 | 129 | def on_val_batch_start(self, *args, **kwargs): 130 | """ 131 | Fires all registered callbacks at the start of each validation batch 132 | """ 133 | self.run_callbacks('on_val_batch_start', *args, **kwargs) 134 | 135 | def on_val_image_end(self, *args, **kwargs): 136 | """ 137 | Fires all registered callbacks at the end of each val image 138 | """ 139 | self.run_callbacks('on_val_image_end', *args, **kwargs) 140 | 141 | def on_val_batch_end(self, *args, **kwargs): 142 | """ 143 | Fires all registered callbacks at the end of each validation batch 144 | """ 145 | self.run_callbacks('on_val_batch_end', *args, **kwargs) 146 | 147 | def on_val_end(self, *args, **kwargs): 148 | """ 149 | Fires all registered callbacks at the end of the validation 150 | """ 151 | self.run_callbacks('on_val_end', *args, **kwargs) 152 | 153 | def on_fit_epoch_end(self, *args, **kwargs): 154 | """ 155 | Fires all registered callbacks at the end of each fit (train+val) epoch 156 | """ 157 | self.run_callbacks('on_fit_epoch_end', *args, **kwargs) 158 | 159 | def on_model_save(self, *args, **kwargs): 160 | """ 161 | Fires all registered callbacks after each model save 162 | """ 163 | self.run_callbacks('on_model_save', *args, **kwargs) 164 | 165 | def on_train_end(self, *args, **kwargs): 166 | """ 167 | Fires all registered callbacks at the end of training 168 | """ 169 | self.run_callbacks('on_train_end', *args, **kwargs) 170 | 171 | def teardown(self, *args, **kwargs): 172 | """ 173 | Fires all registered callbacks before teardown 174 | """ 175 | self.run_callbacks('teardown', *args, **kwargs) 176 | -------------------------------------------------------------------------------- /utils/downloads.py: -------------------------------------------------------------------------------- 1 | # Download utils 2 | 3 | import os 4 | import platform 5 | import subprocess 6 | import time 7 | import urllib 8 | from pathlib import Path 9 | 10 | import requests 11 | import torch 12 | 13 | 14 | def gsutil_getsize(url=''): 15 | # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du 16 | s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8') 17 | return eval(s.split(' ')[0]) if len(s) else 0 # bytes 18 | 19 | 20 | def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''): 21 | # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes 22 | file = Path(file) 23 | assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}" 24 | try: # url1 25 | print(f'Downloading {url} to {file}...') 26 | torch.hub.download_url_to_file(url, str(file)) 27 | assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check 28 | except Exception as e: # url2 29 | file.unlink(missing_ok=True) # remove partial downloads 30 | print(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...') 31 | os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail 32 | finally: 33 | if not file.exists() or file.stat().st_size < min_bytes: # check 34 | file.unlink(missing_ok=True) # remove partial downloads 35 | print(f"ERROR: {assert_msg}\n{error_msg}") 36 | print('') 37 | 38 | 39 | def attempt_download(file, repo='ultralytics/yolov5'): # from utils.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 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries ---------------------------------------------- 119 | # 120 | # 121 | # def upload_blob(bucket_name, source_file_name, destination_blob_name): 122 | # # Uploads a file to a bucket 123 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python 124 | # 125 | # storage_client = storage.Client() 126 | # bucket = storage_client.get_bucket(bucket_name) 127 | # blob = bucket.blob(destination_blob_name) 128 | # 129 | # blob.upload_from_filename(source_file_name) 130 | # 131 | # print('File {} uploaded to {}.'.format( 132 | # source_file_name, 133 | # destination_blob_name)) 134 | # 135 | # 136 | # def download_blob(bucket_name, source_blob_name, destination_file_name): 137 | # # Uploads a blob from a bucket 138 | # storage_client = storage.Client() 139 | # bucket = storage_client.get_bucket(bucket_name) 140 | # blob = bucket.blob(source_blob_name) 141 | # 142 | # blob.download_to_filename(destination_file_name) 143 | # 144 | # print('Blob {} downloaded to {}.'.format( 145 | # source_blob_name, 146 | # destination_file_name)) 147 | -------------------------------------------------------------------------------- /utils/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 | -------------------------------------------------------------------------------- /utils/flask_rest_api/example_request.py: -------------------------------------------------------------------------------- 1 | """Perform test request""" 2 | import pprint 3 | 4 | import requests 5 | 6 | DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s" 7 | TEST_IMAGE = "zidane.jpg" 8 | 9 | image_data = open(TEST_IMAGE, "rb").read() 10 | 11 | response = requests.post(DETECTION_URL, files={"image": image_data}).json() 12 | 13 | pprint.pprint(response) 14 | -------------------------------------------------------------------------------- /utils/flask_rest_api/restapi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Run a rest API exposing the yolov5s object detection model 3 | """ 4 | import argparse 5 | import io 6 | 7 | import torch 8 | from PIL import Image 9 | from flask import Flask, request 10 | 11 | app = Flask(__name__) 12 | 13 | DETECTION_URL = "/v1/object-detection/yolov5s" 14 | 15 | 16 | @app.route(DETECTION_URL, methods=["POST"]) 17 | def predict(): 18 | if not request.method == "POST": 19 | return 20 | 21 | if request.files.get("image"): 22 | image_file = request.files["image"] 23 | image_bytes = image_file.read() 24 | 25 | img = Image.open(io.BytesIO(image_bytes)) 26 | 27 | results = model(img, size=640) # reduce size=320 for faster inference 28 | return results.pandas().xyxy[0].to_json(orient="records") 29 | 30 | 31 | if __name__ == "__main__": 32 | parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model") 33 | parser.add_argument("--port", default=5000, type=int, help="port number") 34 | args = parser.parse_args() 35 | 36 | model = torch.hub.load("ultralytics/yolov5", "yolov5s", force_reload=True) # force_reload to recache 37 | app.run(host="0.0.0.0", port=args.port) # debug=True causes Restarting with stat 38 | -------------------------------------------------------------------------------- /utils/google_app_engine/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gcr.io/google-appengine/python 2 | 3 | # Create a virtualenv for dependencies. This isolates these packages from 4 | # system-level packages. 5 | # Use -p python3 or -p python3.7 to select python version. Default is version 2. 6 | RUN virtualenv /env -p python3 7 | 8 | # Setting these environment variables are the same as running 9 | # source /env/bin/activate. 10 | ENV VIRTUAL_ENV /env 11 | ENV PATH /env/bin:$PATH 12 | 13 | RUN apt-get update && apt-get install -y python-opencv 14 | 15 | # Copy the application's requirements.txt and run pip to install all 16 | # dependencies into the virtualenv. 17 | ADD requirements.txt /app/requirements.txt 18 | RUN pip install -r /app/requirements.txt 19 | 20 | # Add the application source code. 21 | ADD . /app 22 | 23 | # Run a WSGI server to serve the application. gunicorn must be declared as 24 | # a dependency in requirements.txt. 25 | CMD gunicorn -b :$PORT main:app 26 | -------------------------------------------------------------------------------- /utils/google_app_engine/additional_requirements.txt: -------------------------------------------------------------------------------- 1 | # add these requirements in your app on top of the existing ones 2 | pip==19.2 3 | Flask==1.0.2 4 | gunicorn==19.9.0 5 | -------------------------------------------------------------------------------- /utils/google_app_engine/app.yaml: -------------------------------------------------------------------------------- 1 | runtime: custom 2 | env: flex 3 | 4 | service: yolov5app 5 | 6 | liveness_check: 7 | initial_delay_sec: 600 8 | 9 | manual_scaling: 10 | instances: 1 11 | resources: 12 | cpu: 1 13 | memory_gb: 4 14 | disk_size_gb: 20 -------------------------------------------------------------------------------- /utils/loggers/__init__.py: -------------------------------------------------------------------------------- 1 | # YOLOv5 experiment logging utils 2 | import warnings 3 | from threading import Thread 4 | 5 | import torch 6 | from torch.utils.tensorboard import SummaryWriter 7 | 8 | from utils.general import colorstr, emojis 9 | from utils.loggers.wandb.wandb_utils import WandbLogger 10 | from utils.plots import plot_images, plot_results 11 | from utils.torch_utils import de_parallel 12 | 13 | LOGGERS = ('csv', 'tb', 'wandb') # text-file, TensorBoard, Weights & Biases 14 | 15 | try: 16 | import wandb 17 | 18 | assert hasattr(wandb, '__version__') # verify package import not local dir 19 | except (ImportError, AssertionError): 20 | wandb = None 21 | 22 | 23 | class Loggers(): 24 | # YOLOv5 Loggers class 25 | def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS): 26 | self.save_dir = save_dir 27 | self.weights = weights 28 | self.opt = opt 29 | self.hyp = hyp 30 | self.logger = logger # for printing results to console 31 | self.include = include 32 | self.keys = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss 33 | 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', # metrics 34 | 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss 35 | 'x/lr0', 'x/lr1', 'x/lr2'] # params 36 | for k in LOGGERS: 37 | setattr(self, k, None) # init empty logger dictionary 38 | self.csv = True # always log to csv 39 | 40 | # Message 41 | if not wandb: 42 | prefix = colorstr('Weights & Biases: ') 43 | s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)" 44 | print(emojis(s)) 45 | 46 | # TensorBoard 47 | s = self.save_dir 48 | if 'tb' in self.include and not self.opt.evolve: 49 | prefix = colorstr('TensorBoard: ') 50 | self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/") 51 | self.tb = SummaryWriter(str(s)) 52 | 53 | # W&B 54 | if wandb and 'wandb' in self.include: 55 | wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://') 56 | run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None 57 | self.opt.hyp = self.hyp # add hyperparameters 58 | self.wandb = WandbLogger(self.opt, run_id) 59 | else: 60 | self.wandb = None 61 | 62 | def on_pretrain_routine_end(self): 63 | # Callback runs on pre-train routine end 64 | paths = self.save_dir.glob('*labels*.jpg') # training labels 65 | if self.wandb: 66 | self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]}) 67 | 68 | def on_train_batch_end(self, ni, model, imgs, targets, paths, plots): 69 | # Callback runs on train batch end 70 | if plots: 71 | if ni == 0: 72 | with warnings.catch_warnings(): 73 | warnings.simplefilter('ignore') # suppress jit trace warning 74 | self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), []) 75 | if ni < 3: 76 | f = self.save_dir / f'train_batch{ni}.jpg' # filename 77 | Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start() 78 | if self.wandb and ni == 10: 79 | files = sorted(self.save_dir.glob('train*.jpg')) 80 | self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]}) 81 | 82 | def on_train_epoch_end(self, epoch): 83 | # Callback runs on train epoch end 84 | if self.wandb: 85 | self.wandb.current_epoch = epoch + 1 86 | 87 | def on_val_image_end(self, pred, predn, path, names, im): 88 | # Callback runs on val image end 89 | if self.wandb: 90 | self.wandb.val_one_image(pred, predn, path, names, im) 91 | 92 | def on_val_end(self): 93 | # Callback runs on val end 94 | if self.wandb: 95 | files = sorted(self.save_dir.glob('val*.jpg')) 96 | self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]}) 97 | 98 | def on_fit_epoch_end(self, vals, epoch, best_fitness, fi): 99 | # Callback runs at the end of each fit (train+val) epoch 100 | x = {k: v for k, v in zip(self.keys, vals)} # dict 101 | if self.csv: 102 | file = self.save_dir / 'results.csv' 103 | n = len(x) + 1 # number of cols 104 | s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header 105 | with open(file, 'a') as f: 106 | f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n') 107 | 108 | if self.tb: 109 | for k, v in x.items(): 110 | self.tb.add_scalar(k, v, epoch) 111 | 112 | if self.wandb: 113 | self.wandb.log(x) 114 | self.wandb.end_epoch(best_result=best_fitness == fi) 115 | 116 | def on_model_save(self, last, epoch, final_epoch, best_fitness, fi): 117 | # Callback runs on model save event 118 | if self.wandb: 119 | if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1: 120 | self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi) 121 | 122 | def on_train_end(self, last, best, plots, epoch): 123 | # Callback runs on training end 124 | if plots: 125 | plot_results(file=self.save_dir / 'results.csv') # save results.png 126 | files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]] 127 | files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter 128 | 129 | if self.tb: 130 | from PIL import Image 131 | import numpy as np 132 | for f in files: 133 | self.tb.add_image(f.stem, np.asarray(Image.open(f)), epoch, dataformats='HWC') 134 | 135 | if self.wandb: 136 | self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]}) 137 | # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model 138 | wandb.log_artifact(str(best if best.exists() else last), type='model', 139 | name='run_' + self.wandb.wandb_run.id + '_model', 140 | aliases=['latest', 'best', 'stripped']) 141 | self.wandb.finish_run() 142 | -------------------------------------------------------------------------------- /utils/loggers/wandb/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/utils/loggers/wandb/__init__.py -------------------------------------------------------------------------------- /utils/loggers/wandb/log_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | from wandb_utils import WandbLogger 4 | 5 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' 6 | 7 | 8 | def create_dataset_artifact(opt): 9 | logger = WandbLogger(opt, None, job_type='Dataset Creation') # TODO: return value unused 10 | 11 | 12 | if __name__ == '__main__': 13 | parser = argparse.ArgumentParser() 14 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') 15 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') 16 | parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project') 17 | parser.add_argument('--entity', default=None, help='W&B entity') 18 | parser.add_argument('--name', type=str, default='log dataset', help='name of W&B run') 19 | 20 | opt = parser.parse_args() 21 | opt.resume = False # Explicitly disallow resume check for dataset upload job 22 | 23 | create_dataset_artifact(opt) 24 | -------------------------------------------------------------------------------- /utils/loggers/wandb/sweep.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from pathlib import Path 3 | 4 | import wandb 5 | 6 | FILE = Path(__file__).absolute() 7 | sys.path.append(FILE.parents[3].as_posix()) # add utils/ to path 8 | 9 | from train import train, parse_opt 10 | from utils.general import increment_path 11 | from utils.torch_utils import select_device 12 | 13 | 14 | def sweep(): 15 | wandb.init() 16 | # Get hyp dict from sweep agent 17 | hyp_dict = vars(wandb.config).get("_items") 18 | 19 | # Workaround: get necessary opt args 20 | opt = parse_opt(known=True) 21 | opt.batch_size = hyp_dict.get("batch_size") 22 | opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve)) 23 | opt.epochs = hyp_dict.get("epochs") 24 | opt.nosave = True 25 | opt.data = hyp_dict.get("data") 26 | device = select_device(opt.device, batch_size=opt.batch_size) 27 | 28 | # train 29 | train(hyp_dict, opt, device) 30 | 31 | 32 | if __name__ == "__main__": 33 | sweep() 34 | -------------------------------------------------------------------------------- /utils/loggers/wandb/sweep.yaml: -------------------------------------------------------------------------------- 1 | # Hyperparameters for training 2 | # To set range- 3 | # Provide min and max values as: 4 | # parameter: 5 | # 6 | # min: scalar 7 | # max: scalar 8 | # OR 9 | # 10 | # Set a specific list of search space- 11 | # parameter: 12 | # values: [scalar1, scalar2, scalar3...] 13 | # 14 | # You can use grid, bayesian and hyperopt search strategy 15 | # For more info on configuring sweeps visit - https://docs.wandb.ai/guides/sweeps/configuration 16 | 17 | program: utils/loggers/wandb/sweep.py 18 | method: random 19 | metric: 20 | name: metrics/mAP_0.5 21 | goal: maximize 22 | 23 | parameters: 24 | # hyperparameters: set either min, max range or values list 25 | data: 26 | value: "data/coco128.yaml" 27 | batch_size: 28 | values: [64] 29 | epochs: 30 | values: [10] 31 | 32 | lr0: 33 | distribution: uniform 34 | min: 1e-5 35 | max: 1e-1 36 | lrf: 37 | distribution: uniform 38 | min: 0.01 39 | max: 1.0 40 | momentum: 41 | distribution: uniform 42 | min: 0.6 43 | max: 0.98 44 | weight_decay: 45 | distribution: uniform 46 | min: 0.0 47 | max: 0.001 48 | warmup_epochs: 49 | distribution: uniform 50 | min: 0.0 51 | max: 5.0 52 | warmup_momentum: 53 | distribution: uniform 54 | min: 0.0 55 | max: 0.95 56 | warmup_bias_lr: 57 | distribution: uniform 58 | min: 0.0 59 | max: 0.2 60 | box: 61 | distribution: uniform 62 | min: 0.02 63 | max: 0.2 64 | cls: 65 | distribution: uniform 66 | min: 0.2 67 | max: 4.0 68 | cls_pw: 69 | distribution: uniform 70 | min: 0.5 71 | max: 2.0 72 | obj: 73 | distribution: uniform 74 | min: 0.2 75 | max: 4.0 76 | obj_pw: 77 | distribution: uniform 78 | min: 0.5 79 | max: 2.0 80 | iou_t: 81 | distribution: uniform 82 | min: 0.1 83 | max: 0.7 84 | anchor_t: 85 | distribution: uniform 86 | min: 2.0 87 | max: 8.0 88 | fl_gamma: 89 | distribution: uniform 90 | min: 0.0 91 | max: 0.1 92 | hsv_h: 93 | distribution: uniform 94 | min: 0.0 95 | max: 0.1 96 | hsv_s: 97 | distribution: uniform 98 | min: 0.0 99 | max: 0.9 100 | hsv_v: 101 | distribution: uniform 102 | min: 0.0 103 | max: 0.9 104 | degrees: 105 | distribution: uniform 106 | min: 0.0 107 | max: 45.0 108 | translate: 109 | distribution: uniform 110 | min: 0.0 111 | max: 0.9 112 | scale: 113 | distribution: uniform 114 | min: 0.0 115 | max: 0.9 116 | shear: 117 | distribution: uniform 118 | min: 0.0 119 | max: 10.0 120 | perspective: 121 | distribution: uniform 122 | min: 0.0 123 | max: 0.001 124 | flipud: 125 | distribution: uniform 126 | min: 0.0 127 | max: 1.0 128 | fliplr: 129 | distribution: uniform 130 | min: 0.0 131 | max: 1.0 132 | mosaic: 133 | distribution: uniform 134 | min: 0.0 135 | max: 1.0 136 | mixup: 137 | distribution: uniform 138 | min: 0.0 139 | max: 1.0 140 | copy_paste: 141 | distribution: uniform 142 | min: 0.0 143 | max: 1.0 144 | -------------------------------------------------------------------------------- /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, 1.0, 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 | return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach() 166 | 167 | def build_targets(self, p, targets): 168 | # Build targets for compute_loss(), input targets(image,class,x,y,w,h) 169 | na, nt = self.na, targets.shape[0] # number of anchors, targets 170 | tcls, tbox, indices, anch = [], [], [], [] 171 | gain = torch.ones(7, device=targets.device) # normalized to gridspace gain 172 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) 173 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices 174 | 175 | g = 0.5 # bias 176 | off = torch.tensor([[0, 0], 177 | [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m 178 | # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm 179 | ], device=targets.device).float() * g # offsets 180 | 181 | for i in range(self.nl): 182 | anchors = self.anchors[i] 183 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain 184 | 185 | # Match targets to anchors 186 | t = targets * gain 187 | if nt: 188 | # Matches 189 | r = t[:, :, 4:6] / anchors[:, None] # wh ratio 190 | j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare 191 | # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) 192 | t = t[j] # filter 193 | 194 | # Offsets 195 | gxy = t[:, 2:4] # grid xy 196 | gxi = gain[[2, 3]] - gxy # inverse 197 | j, k = ((gxy % 1. < g) & (gxy > 1.)).T 198 | l, m = ((gxi % 1. < g) & (gxi > 1.)).T 199 | j = torch.stack((torch.ones_like(j), j, k, l, m)) 200 | t = t.repeat((5, 1, 1))[j] 201 | offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] 202 | else: 203 | t = targets[0] 204 | offsets = 0 205 | 206 | # Define 207 | b, c = t[:, :2].long().T # image, class 208 | gxy = t[:, 2:4] # grid xy 209 | gwh = t[:, 4:6] # grid wh 210 | gij = (gxy - offsets).long() 211 | gi, gj = gij.T # grid xy indices 212 | 213 | # Append 214 | a = t[:, 6].long() # anchor indices 215 | indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices 216 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box 217 | anch.append(anchors[a]) # anchors 218 | tcls.append(c) # class 219 | 220 | return tcls, tbox, indices, anch 221 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | 26 | LOGGER = logging.getLogger(__name__) 27 | 28 | 29 | @contextmanager 30 | def torch_distributed_zero_first(local_rank: int): 31 | """ 32 | Decorator to make all processes in distributed training wait for each local_master to do something. 33 | """ 34 | if local_rank not in [-1, 0]: 35 | dist.barrier() 36 | yield 37 | if local_rank == 0: 38 | dist.barrier() 39 | 40 | 41 | def init_torch_seeds(seed=0): 42 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html 43 | torch.manual_seed(seed) 44 | if seed == 0: # slower, more reproducible 45 | cudnn.benchmark, cudnn.deterministic = False, True 46 | else: # faster, less reproducible 47 | cudnn.benchmark, cudnn.deterministic = True, False 48 | 49 | 50 | def date_modified(path=__file__): 51 | # return human-readable file modification date, i.e. '2021-3-26' 52 | t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime) 53 | return f'{t.year}-{t.month}-{t.day}' 54 | 55 | 56 | def git_describe(path=Path(__file__).parent): # path must be a directory 57 | # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe 58 | s = f'git -C {path} describe --tags --long --always' 59 | try: 60 | return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1] 61 | except subprocess.CalledProcessError as e: 62 | return '' # not a git repository 63 | 64 | 65 | def select_device(device='', batch_size=None): 66 | # device = 'cpu' or '0' or '0,1,2,3' 67 | s = f'YOLOv5 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string 68 | device = str(device).strip().lower().replace('cuda:', '') # to string, 'cuda:0' to '0' 69 | cpu = device == 'cpu' 70 | if cpu: 71 | os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False 72 | elif device: # non-cpu device requested 73 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable 74 | assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability 75 | 76 | cuda = not cpu and torch.cuda.is_available() 77 | if cuda: 78 | devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7 79 | n = len(devices) # device count 80 | if n > 1 and batch_size: # check batch_size is divisible by device_count 81 | assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' 82 | space = ' ' * (len(s) + 1) 83 | for i, d in enumerate(devices): 84 | p = torch.cuda.get_device_properties(i) 85 | s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB 86 | else: 87 | s += 'CPU\n' 88 | 89 | LOGGER.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe 90 | return torch.device('cuda:0' if cuda else 'cpu') 91 | 92 | 93 | def time_sync(): 94 | # pytorch-accurate time 95 | if torch.cuda.is_available(): 96 | torch.cuda.synchronize() 97 | return time.time() 98 | 99 | 100 | def profile(input, ops, n=10, device=None): 101 | # YOLOv5 speed/memory/FLOPs profiler 102 | # 103 | # Usage: 104 | # input = torch.randn(16, 3, 640, 640) 105 | # m1 = lambda x: x * torch.sigmoid(x) 106 | # m2 = nn.SiLU() 107 | # profile(input, [m1, m2], n=100) # profile over 100 iterations 108 | 109 | results = [] 110 | logging.basicConfig(format="%(message)s", level=logging.INFO) 111 | device = device or select_device() 112 | print(f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}" 113 | f"{'input':>24s}{'output':>24s}") 114 | 115 | for x in input if isinstance(input, list) else [input]: 116 | x = x.to(device) 117 | x.requires_grad = True 118 | for m in ops if isinstance(ops, list) else [ops]: 119 | m = m.to(device) if hasattr(m, 'to') else m # device 120 | m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m 121 | tf, tb, t = 0., 0., [0., 0., 0.] # dt forward, backward 122 | try: 123 | flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs 124 | except: 125 | flops = 0 126 | 127 | try: 128 | for _ in range(n): 129 | t[0] = time_sync() 130 | y = m(x) 131 | t[1] = time_sync() 132 | try: 133 | _ = (sum([yi.sum() for yi in y]) if isinstance(y, list) else y).sum().backward() 134 | t[2] = time_sync() 135 | except Exception as e: # no backward method 136 | print(e) 137 | t[2] = float('nan') 138 | tf += (t[1] - t[0]) * 1000 / n # ms per op forward 139 | tb += (t[2] - t[1]) * 1000 / n # ms per op backward 140 | mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0 # (GB) 141 | s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' 142 | s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list' 143 | p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters 144 | print(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}') 145 | results.append([p, flops, mem, tf, tb, s_in, s_out]) 146 | except Exception as e: 147 | print(e) 148 | results.append(None) 149 | torch.cuda.empty_cache() 150 | return results 151 | 152 | 153 | def is_parallel(model): 154 | # Returns True if model is of type DP or DDP 155 | return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) 156 | 157 | 158 | def de_parallel(model): 159 | # De-parallelize a model: returns single-GPU model if model is of type DP or DDP 160 | return model.module if is_parallel(model) else model 161 | 162 | 163 | def intersect_dicts(da, db, exclude=()): 164 | # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values 165 | 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} 166 | 167 | 168 | def initialize_weights(model): 169 | for m in model.modules(): 170 | t = type(m) 171 | if t is nn.Conv2d: 172 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 173 | elif t is nn.BatchNorm2d: 174 | m.eps = 1e-3 175 | m.momentum = 0.03 176 | elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]: 177 | m.inplace = True 178 | 179 | 180 | def find_modules(model, mclass=nn.Conv2d): 181 | # Finds layer indices matching module class 'mclass' 182 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] 183 | 184 | 185 | def sparsity(model): 186 | # Return global model sparsity 187 | a, b = 0., 0. 188 | for p in model.parameters(): 189 | a += p.numel() 190 | b += (p == 0).sum() 191 | return b / a 192 | 193 | 194 | def prune(model, amount=0.3): 195 | # Prune model to requested global sparsity 196 | import torch.nn.utils.prune as prune 197 | print('Pruning model... ', end='') 198 | for name, m in model.named_modules(): 199 | if isinstance(m, nn.Conv2d): 200 | prune.l1_unstructured(m, name='weight', amount=amount) # prune 201 | prune.remove(m, 'weight') # make permanent 202 | print(' %.3g global sparsity' % sparsity(model)) 203 | 204 | 205 | def fuse_conv_and_bn(conv, bn): 206 | # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ 207 | fusedconv = nn.Conv2d(conv.in_channels, 208 | conv.out_channels, 209 | kernel_size=conv.kernel_size, 210 | stride=conv.stride, 211 | padding=conv.padding, 212 | groups=conv.groups, 213 | bias=True).requires_grad_(False).to(conv.weight.device) 214 | 215 | # prepare filters 216 | w_conv = conv.weight.clone().view(conv.out_channels, -1) 217 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) 218 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape)) 219 | 220 | # prepare spatial bias 221 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias 222 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) 223 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) 224 | 225 | return fusedconv 226 | 227 | 228 | def model_info(model, verbose=False, img_size=640): 229 | # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320] 230 | n_p = sum(x.numel() for x in model.parameters()) # number parameters 231 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients 232 | if verbose: 233 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma')) 234 | for i, (name, p) in enumerate(model.named_parameters()): 235 | name = name.replace('module_list.', '') 236 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' % 237 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) 238 | 239 | try: # FLOPs 240 | from thop import profile 241 | stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32 242 | img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input 243 | flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPs 244 | img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float 245 | fs = ', %.1f GFLOPs' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPs 246 | except (ImportError, Exception): 247 | fs = '' 248 | 249 | LOGGER.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") 250 | 251 | 252 | def load_classifier(name='resnet101', n=2): 253 | # Loads a pretrained model reshaped to n-class output 254 | model = torchvision.models.__dict__[name](pretrained=True) 255 | 256 | # ResNet model properties 257 | # input_size = [3, 224, 224] 258 | # input_space = 'RGB' 259 | # input_range = [0, 1] 260 | # mean = [0.485, 0.456, 0.406] 261 | # std = [0.229, 0.224, 0.225] 262 | 263 | # Reshape output to n classes 264 | filters = model.fc.weight.shape[1] 265 | model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True) 266 | model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True) 267 | model.fc.out_features = n 268 | return model 269 | 270 | 271 | def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) 272 | # scales img(bs,3,y,x) by ratio constrained to gs-multiple 273 | if ratio == 1.0: 274 | return img 275 | else: 276 | h, w = img.shape[2:] 277 | s = (int(h * ratio), int(w * ratio)) # new size 278 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize 279 | if not same_shape: # pad/crop img 280 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)] 281 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean 282 | 283 | 284 | def copy_attr(a, b, include=(), exclude=()): 285 | # Copy attributes from b to a, options to only include [...] and to exclude [...] 286 | for k, v in b.__dict__.items(): 287 | if (len(include) and k not in include) or k.startswith('_') or k in exclude: 288 | continue 289 | else: 290 | setattr(a, k, v) 291 | 292 | 293 | class ModelEMA: 294 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models 295 | Keep a moving average of everything in the model state_dict (parameters and buffers). 296 | This is intended to allow functionality like 297 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage 298 | A smoothed version of the weights is necessary for some training schemes to perform well. 299 | This class is sensitive where it is initialized in the sequence of model init, 300 | GPU assignment and distributed training wrappers. 301 | """ 302 | 303 | def __init__(self, model, decay=0.9999, updates=0): 304 | # Create EMA 305 | self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA 306 | # if next(model.parameters()).device.type != 'cpu': 307 | # self.ema.half() # FP16 EMA 308 | self.updates = updates # number of EMA updates 309 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs) 310 | for p in self.ema.parameters(): 311 | p.requires_grad_(False) 312 | 313 | def update(self, model): 314 | # Update EMA parameters 315 | with torch.no_grad(): 316 | self.updates += 1 317 | d = self.decay(self.updates) 318 | 319 | msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict 320 | for k, v in self.ema.state_dict().items(): 321 | if v.dtype.is_floating_point: 322 | v *= d 323 | v += (1. - d) * msd[k].detach() 324 | 325 | def update_attr(self, model, include=(), exclude=('process_group', 'reducer')): 326 | # Update EMA attributes 327 | copy_attr(self.ema, model, include, exclude) 328 | -------------------------------------------------------------------------------- /yolov5s.pt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ViAsmit/YOLOv5-Flask/df428374e365f72f054be29063f26f69f749a454/yolov5s.pt --------------------------------------------------------------------------------