├── README.md ├── data ├── Argoverse_HD.yaml ├── GlobalWheat2020.yaml ├── IndusDefect.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 ├── pest.yaml ├── scripts │ ├── download_weights.sh │ ├── get_coco.sh │ └── get_coco128.sh └── xView.yaml ├── detect.py ├── models ├── activations.py ├── common.py ├── experimental.py ├── export.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-cbam.yaml │ ├── yolov5s-ghost.yaml │ ├── yolov5s-transformer.yaml │ ├── yolov5s6.yaml │ ├── yolov5x6.yaml │ └── yolov5x_se.yaml ├── yolo.py ├── yolov5l.yaml ├── yolov5m.yaml ├── yolov5s.yaml └── yolov5x.yaml ├── others ├── Bottleneck.png ├── BottleneckCSP.png ├── C3.png ├── CA.png ├── CAM.png ├── CBAM.png ├── Conv.png ├── Focus.png ├── SAM.png ├── SE.png ├── SPP.png ├── Transformer.png ├── formula.png └── yolov5s.png ├── requirements.txt ├── runs └── 这里存放训练、验证结果.txt ├── train.py ├── utils ├── autoanchor.py ├── aws │ ├── mime.sh │ ├── resume.py │ └── userdata.sh ├── datasets.py ├── flask_rest_api │ ├── README.md │ ├── example_request.py │ └── restapi.py ├── general.py ├── google_app_engine │ ├── Dockerfile │ ├── additional_requirements.txt │ └── app.yaml ├── google_utils.py ├── loss.py ├── metrics.py ├── plots.py ├── torch_utils.py └── wandb_logging │ ├── log_dataset.py │ └── wandb_utils.py ├── val.py └── weights └── 这里存放权重文件.txt /README.md: -------------------------------------------------------------------------------- 1 | # yolov5-5.x-annotations 2 | 一个基于yolov5-5.0的中文注释版本,供大家参考学习! 3 | 4 | A Chinese annotated version of yolov5-5.0 5 | 6 | # CSDN源码讲解导航 7 | [CSDN:YOLOV5-U](https://blog.csdn.net/qq_38253797/article/details/119043919) 8 | 9 | - data 10 | * [hyp.scratch.yaml](https://blog.csdn.net/qq_38253797/article/details/119759746) 11 | * [coco128.yaml](https://blog.csdn.net/qq_38253797/article/details/119763327) 12 | 13 | - models 14 | * [activations.py](https://blog.csdn.net/qq_38253797/article/details/119030643) 15 | * [common.py](https://blog.csdn.net/qq_38253797/article/details/119684388) 16 | * [experimental.py](https://blog.csdn.net/qq_38253797/article/details/119854460) 17 | * [yolo.py](https://blog.csdn.net/qq_38253797/article/details/119869762) 18 | * [export.py](https://blog.csdn.net/qq_38253797/article/details/119887013) 19 | * [yolov5s.yaml](https://blog.csdn.net/qq_38253797/article/details/119754854) 20 | 21 | - utils 22 | * [autoanchor.py](https://blog.csdn.net/qq_38253797/article/details/119713706) 23 | * [datasets.py](https://blog.csdn.net/qq_38253797/article/details/119904518) 24 | * [general.py](https://blog.csdn.net/qq_38253797/article/details/119348092) 25 | * [google_utils.py](https://blog.csdn.net/qq_38253797/article/details/119274587) 26 | * [loss.py](https://blog.csdn.net/qq_38253797/article/details/119444854) 27 | * [metrics.py](https://blog.csdn.net/qq_38253797/article/details/119547084) 28 | * [plots.py](https://blog.csdn.net/qq_38253797/article/details/119324328) 29 | * [torch_utils.py](https://blog.csdn.net/qq_38253797/article/details/119214728) 30 | - [train.py](https://blog.csdn.net/qq_38253797/article/details/119733964) 31 | - [val(test).py](https://blog.csdn.net/qq_38253797/article/details/119577291) 32 | - [detect.py](https://blog.csdn.net/qq_38253797/article/details/119382661) 33 | - 其他功能 34 | * [head解耦](https://blog.csdn.net/qq_38253797/article/details/124848744) 35 | * [yolov5+shufflenetv2轻量化](https://blog.csdn.net/qq_38253797/article/details/124803531) 36 | -------------------------------------------------------------------------------- /data/Argoverse_HD.yaml: -------------------------------------------------------------------------------- 1 | # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ 2 | # Train command: python train.py --data Argoverse_HD.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/Argoverse 6 | # /yolov5 7 | 8 | 9 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 10 | path: ../datasets/Argoverse # dataset root dir 11 | train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images 12 | val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images 13 | test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview 14 | 15 | # Classes 16 | nc: 8 # number of classes 17 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign' ] # class names 18 | 19 | 20 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 21 | download: | 22 | import json 23 | 24 | from tqdm import tqdm 25 | from utils.general import download, Path 26 | 27 | 28 | def argoverse2yolo(set): 29 | labels = {} 30 | a = json.load(open(set, "rb")) 31 | for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."): 32 | img_id = annot['image_id'] 33 | img_name = a['images'][img_id]['name'] 34 | img_label_name = img_name[:-3] + "txt" 35 | 36 | cls = annot['category_id'] # instance class id 37 | x_center, y_center, width, height = annot['bbox'] 38 | x_center = (x_center + width / 2) / 1920.0 # offset and scale 39 | y_center = (y_center + height / 2) / 1200.0 # offset and scale 40 | width /= 1920.0 # scale 41 | height /= 1200.0 # scale 42 | 43 | img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']] 44 | if not img_dir.exists(): 45 | img_dir.mkdir(parents=True, exist_ok=True) 46 | 47 | k = str(img_dir / img_label_name) 48 | if k not in labels: 49 | labels[k] = [] 50 | labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n") 51 | 52 | for k in labels: 53 | with open(k, "w") as f: 54 | f.writelines(labels[k]) 55 | 56 | 57 | # Download 58 | dir = Path('../datasets/Argoverse') # dataset root dir 59 | urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip'] 60 | download(urls, dir=dir, delete=False) 61 | 62 | # Convert 63 | annotations_dir = 'Argoverse-HD/annotations/' 64 | (dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images' 65 | for d in "train.json", "val.json": 66 | argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels 67 | -------------------------------------------------------------------------------- /data/GlobalWheat2020.yaml: -------------------------------------------------------------------------------- 1 | # Global Wheat 2020 dataset http://www.global-wheat.com/ 2 | # Train command: python train.py --data GlobalWheat2020.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/GlobalWheat2020 6 | # /yolov5 7 | 8 | 9 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 10 | path: ../datasets/GlobalWheat2020 # dataset root dir 11 | train: # train images (relative to 'path') 3422 images 12 | - images/arvalis_1 13 | - images/arvalis_2 14 | - images/arvalis_3 15 | - images/ethz_1 16 | - images/rres_1 17 | - images/inrae_1 18 | - images/usask_1 19 | val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1) 20 | - images/ethz_1 21 | test: # test images (optional) 1276 images 22 | - images/utokyo_1 23 | - images/utokyo_2 24 | - images/nau_1 25 | - images/uq_1 26 | 27 | # Classes 28 | nc: 1 # number of classes 29 | names: [ 'wheat_head' ] # class names 30 | 31 | 32 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 33 | download: | 34 | from utils.general import download, Path 35 | 36 | # Download 37 | dir = Path(yaml['path']) # dataset root dir 38 | urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip', 39 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip'] 40 | download(urls, dir=dir) 41 | 42 | # Make Directories 43 | for p in 'annotations', 'images', 'labels': 44 | (dir / p).mkdir(parents=True, exist_ok=True) 45 | 46 | # Move 47 | for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \ 48 | 'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1': 49 | (dir / p).rename(dir / 'images' / p) # move to /images 50 | f = (dir / p).with_suffix('.json') # json file 51 | if f.exists(): 52 | f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations 53 | -------------------------------------------------------------------------------- /data/IndusDefect.yaml: -------------------------------------------------------------------------------- 1 | path: ../datasets/IndusDefect 2 | train: # train images (relative to 'path') 1354 images 3 | - images/train 4 | val: # val images (relative to 'path') 339 images 5 | - images/val 6 | test: # test images (optional) 7 | # - images/val 8 | 9 | # Classes 10 | nc: 1 # number of classes 11 | names: [ 'defect'] # class names 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /data/Objects365.yaml: -------------------------------------------------------------------------------- 1 | # Objects365 dataset https://www.objects365.org/ 2 | # Train command: python train.py --data Objects365.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/Objects365 6 | # /yolov5 7 | 8 | 9 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 10 | path: ../datasets/Objects365 # dataset root dir 11 | train: images/train # train images (relative to 'path') 1742289 images 12 | val: images/val # val images (relative to 'path') 5570 images 13 | test: # test images (optional) 14 | 15 | # Classes 16 | nc: 365 # number of classes 17 | names: [ 'Person', 'Sneakers', 'Chair', 'Other Shoes', 'Hat', 'Car', 'Lamp', 'Glasses', 'Bottle', 'Desk', 'Cup', 18 | 'Street Lights', 'Cabinet/shelf', 'Handbag/Satchel', 'Bracelet', 'Plate', 'Picture/Frame', 'Helmet', 'Book', 19 | 'Gloves', 'Storage box', 'Boat', 'Leather Shoes', 'Flower', 'Bench', 'Potted Plant', 'Bowl/Basin', 'Flag', 20 | 'Pillow', 'Boots', 'Vase', 'Microphone', 'Necklace', 'Ring', 'SUV', 'Wine Glass', 'Belt', 'Monitor/TV', 21 | 'Backpack', 'Umbrella', 'Traffic Light', 'Speaker', 'Watch', 'Tie', 'Trash bin Can', 'Slippers', 'Bicycle', 22 | 'Stool', 'Barrel/bucket', 'Van', 'Couch', 'Sandals', 'Basket', 'Drum', 'Pen/Pencil', 'Bus', 'Wild Bird', 23 | 'High Heels', 'Motorcycle', 'Guitar', 'Carpet', 'Cell Phone', 'Bread', 'Camera', 'Canned', 'Truck', 24 | 'Traffic cone', 'Cymbal', 'Lifesaver', 'Towel', 'Stuffed Toy', 'Candle', 'Sailboat', 'Laptop', 'Awning', 25 | 'Bed', 'Faucet', 'Tent', 'Horse', 'Mirror', 'Power outlet', 'Sink', 'Apple', 'Air Conditioner', 'Knife', 26 | 'Hockey Stick', 'Paddle', 'Pickup Truck', 'Fork', 'Traffic Sign', 'Balloon', 'Tripod', 'Dog', 'Spoon', 'Clock', 27 | 'Pot', 'Cow', 'Cake', 'Dinning Table', 'Sheep', 'Hanger', 'Blackboard/Whiteboard', 'Napkin', 'Other Fish', 28 | 'Orange/Tangerine', 'Toiletry', 'Keyboard', 'Tomato', 'Lantern', 'Machinery Vehicle', 'Fan', 29 | 'Green Vegetables', 'Banana', 'Baseball Glove', 'Airplane', 'Mouse', 'Train', 'Pumpkin', 'Soccer', 'Skiboard', 30 | 'Luggage', 'Nightstand', 'Tea pot', 'Telephone', 'Trolley', 'Head Phone', 'Sports Car', 'Stop Sign', 31 | 'Dessert', 'Scooter', 'Stroller', 'Crane', 'Remote', 'Refrigerator', 'Oven', 'Lemon', 'Duck', 'Baseball Bat', 32 | 'Surveillance Camera', 'Cat', 'Jug', 'Broccoli', 'Piano', 'Pizza', 'Elephant', 'Skateboard', 'Surfboard', 33 | 'Gun', 'Skating and Skiing shoes', 'Gas stove', 'Donut', 'Bow Tie', 'Carrot', 'Toilet', 'Kite', 'Strawberry', 34 | 'Other Balls', 'Shovel', 'Pepper', 'Computer Box', 'Toilet Paper', 'Cleaning Products', 'Chopsticks', 35 | 'Microwave', 'Pigeon', 'Baseball', 'Cutting/chopping Board', 'Coffee Table', 'Side Table', 'Scissors', 36 | 'Marker', 'Pie', 'Ladder', 'Snowboard', 'Cookies', 'Radiator', 'Fire Hydrant', 'Basketball', 'Zebra', 'Grape', 37 | 'Giraffe', 'Potato', 'Sausage', 'Tricycle', 'Violin', 'Egg', 'Fire Extinguisher', 'Candy', 'Fire Truck', 38 | 'Billiards', 'Converter', 'Bathtub', 'Wheelchair', 'Golf Club', 'Briefcase', 'Cucumber', 'Cigar/Cigarette', 39 | 'Paint Brush', 'Pear', 'Heavy Truck', 'Hamburger', 'Extractor', 'Extension Cord', 'Tong', 'Tennis Racket', 40 | 'Folder', 'American Football', 'earphone', 'Mask', 'Kettle', 'Tennis', 'Ship', 'Swing', 'Coffee Machine', 41 | 'Slide', 'Carriage', 'Onion', 'Green beans', 'Projector', 'Frisbee', 'Washing Machine/Drying Machine', 42 | 'Chicken', 'Printer', 'Watermelon', 'Saxophone', 'Tissue', 'Toothbrush', 'Ice cream', 'Hot-air balloon', 43 | 'Cello', 'French Fries', 'Scale', 'Trophy', 'Cabbage', 'Hot dog', 'Blender', 'Peach', 'Rice', 'Wallet/Purse', 44 | 'Volleyball', 'Deer', 'Goose', 'Tape', 'Tablet', 'Cosmetics', 'Trumpet', 'Pineapple', 'Golf Ball', 45 | 'Ambulance', 'Parking meter', 'Mango', 'Key', 'Hurdle', 'Fishing Rod', 'Medal', 'Flute', 'Brush', 'Penguin', 46 | 'Megaphone', 'Corn', 'Lettuce', 'Garlic', 'Swan', 'Helicopter', 'Green Onion', 'Sandwich', 'Nuts', 47 | 'Speed Limit Sign', 'Induction Cooker', 'Broom', 'Trombone', 'Plum', 'Rickshaw', 'Goldfish', 'Kiwi fruit', 48 | 'Router/modem', 'Poker Card', 'Toaster', 'Shrimp', 'Sushi', 'Cheese', 'Notepaper', 'Cherry', 'Pliers', 'CD', 49 | 'Pasta', 'Hammer', 'Cue', 'Avocado', 'Hamimelon', 'Flask', 'Mushroom', 'Screwdriver', 'Soap', 'Recorder', 50 | 'Bear', 'Eggplant', 'Board Eraser', 'Coconut', 'Tape Measure/Ruler', 'Pig', 'Showerhead', 'Globe', 'Chips', 51 | 'Steak', 'Crosswalk Sign', 'Stapler', 'Camel', 'Formula 1', 'Pomegranate', 'Dishwasher', 'Crab', 52 | 'Hoverboard', 'Meat ball', 'Rice Cooker', 'Tuba', 'Calculator', 'Papaya', 'Antelope', 'Parrot', 'Seal', 53 | 'Butterfly', 'Dumbbell', 'Donkey', 'Lion', 'Urinal', 'Dolphin', 'Electric Drill', 'Hair Dryer', 'Egg tart', 54 | 'Jellyfish', 'Treadmill', 'Lighter', 'Grapefruit', 'Game board', 'Mop', 'Radish', 'Baozi', 'Target', 'French', 55 | 'Spring Rolls', 'Monkey', 'Rabbit', 'Pencil Case', 'Yak', 'Red Cabbage', 'Binoculars', 'Asparagus', 'Barbell', 56 | 'Scallop', 'Noddles', 'Comb', 'Dumpling', 'Oyster', 'Table Tennis paddle', 'Cosmetics Brush/Eyeliner Pencil', 57 | 'Chainsaw', 'Eraser', 'Lobster', 'Durian', 'Okra', 'Lipstick', 'Cosmetics Mirror', 'Curling', 'Table Tennis' ] 58 | 59 | 60 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 61 | download: | 62 | from pycocotools.coco import COCO 63 | from tqdm import tqdm 64 | 65 | from utils.general import download, Path 66 | 67 | # Make Directories 68 | dir = Path(yaml['path']) # dataset root dir 69 | for p in 'images', 'labels': 70 | (dir / p).mkdir(parents=True, exist_ok=True) 71 | for q in 'train', 'val': 72 | (dir / p / q).mkdir(parents=True, exist_ok=True) 73 | 74 | # Download 75 | url = "https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/train/" 76 | download([url + 'zhiyuan_objv2_train.tar.gz'], dir=dir, delete=False) # annotations json 77 | download([url + f for f in [f'patch{i}.tar.gz' for i in range(51)]], dir=dir / 'images' / 'train', 78 | curl=True, delete=False, threads=8) 79 | 80 | # Move 81 | train = dir / 'images' / 'train' 82 | for f in tqdm(train.rglob('*.jpg'), desc=f'Moving images'): 83 | f.rename(train / f.name) # move to /images/train 84 | 85 | # Labels 86 | coco = COCO(dir / 'zhiyuan_objv2_train.json') 87 | names = [x["name"] for x in coco.loadCats(coco.getCatIds())] 88 | for cid, cat in enumerate(names): 89 | catIds = coco.getCatIds(catNms=[cat]) 90 | imgIds = coco.getImgIds(catIds=catIds) 91 | for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'): 92 | width, height = im["width"], im["height"] 93 | path = Path(im["file_name"]) # image filename 94 | try: 95 | with open(dir / 'labels' / 'train' / path.with_suffix('.txt').name, 'a') as file: 96 | annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None) 97 | for a in coco.loadAnns(annIds): 98 | x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner) 99 | x, y = x + w / 2, y + h / 2 # xy to center 100 | file.write(f"{cid} {x / width:.5f} {y / height:.5f} {w / width:.5f} {h / height:.5f}\n") 101 | 102 | except Exception as e: 103 | print(e) 104 | -------------------------------------------------------------------------------- /data/SKU-110K.yaml: -------------------------------------------------------------------------------- 1 | # SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 2 | # Train command: python train.py --data SKU-110K.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/SKU-110K 6 | # /yolov5 7 | 8 | 9 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 10 | path: ../datasets/SKU-110K # dataset root dir 11 | train: train.txt # train images (relative to 'path') 8219 images 12 | val: val.txt # val images (relative to 'path') 588 images 13 | test: test.txt # test images (optional) 2936 images 14 | 15 | # Classes 16 | nc: 1 # number of classes 17 | names: [ 'object' ] # class names 18 | 19 | 20 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 21 | download: | 22 | import shutil 23 | from tqdm import tqdm 24 | from utils.general import np, pd, Path, download, xyxy2xywh 25 | 26 | # Download 27 | dir = Path(yaml['path']) # dataset root dir 28 | parent = Path(dir.parent) # download dir 29 | urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz'] 30 | download(urls, dir=parent, delete=False) 31 | 32 | # Rename directories 33 | if dir.exists(): 34 | shutil.rmtree(dir) 35 | (parent / 'SKU110K_fixed').rename(dir) # rename dir 36 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir 37 | 38 | # Convert labels 39 | names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names 40 | for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv': 41 | x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations 42 | images, unique_images = x[:, 0], np.unique(x[:, 0]) 43 | with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f: 44 | f.writelines(f'./images/{s}\n' for s in unique_images) 45 | for im in tqdm(unique_images, desc=f'Converting {dir / d}'): 46 | cls = 0 # single-class dataset 47 | with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f: 48 | for r in x[images == im]: 49 | w, h = r[6], r[7] # image width, height 50 | xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance 51 | f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label 52 | -------------------------------------------------------------------------------- /data/VOC.yaml: -------------------------------------------------------------------------------- 1 | # PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC/ 2 | # Train command: python train.py --data VOC.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/VOC 6 | # /yolov5 7 | 8 | 9 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 10 | path: ../datasets/VOC 11 | train: # train images (relative to 'path') 16551 images 12 | - images/train2007 13 | # - images/train2007 14 | # - images/val2012 15 | # - images/val2007 16 | val: # val images (relative to 'path') 4952 images 17 | - images/test2007 18 | test: # test images (optional) 19 | - images/test2007 20 | 21 | # Classes 22 | nc: 20 # number of classes 23 | names: [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 24 | 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' ] # class names 25 | 26 | 27 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 28 | download: | 29 | import xml.etree.ElementTree as ET 30 | 31 | from tqdm import tqdm 32 | from utils.general import download, Path 33 | 34 | 35 | def convert_label(path, lb_path, year, image_id): 36 | def convert_box(size, box): 37 | dw, dh = 1. / size[0], 1. / size[1] 38 | x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2] 39 | return x * dw, y * dh, w * dw, h * dh 40 | 41 | in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml') 42 | out_file = open(lb_path, 'w') 43 | tree = ET.parse(in_file) 44 | root = tree.getroot() 45 | size = root.find('size') 46 | w = int(size.find('width').text) 47 | h = int(size.find('height').text) 48 | 49 | for obj in root.iter('object'): 50 | cls = obj.find('name').text 51 | if cls in yaml['names'] and not int(obj.find('difficult').text) == 1: 52 | xmlbox = obj.find('bndbox') 53 | bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')]) 54 | cls_id = yaml['names'].index(cls) # class id 55 | out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n') 56 | 57 | 58 | # Download 59 | dir = Path(yaml['path']) # dataset root dir 60 | url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' 61 | urls = [url + 'VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images 62 | url + 'VOCtest_06-Nov-2007.zip', # 438MB, 4953 images 63 | url + 'VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images 64 | download(urls, dir=dir / 'images', delete=False) 65 | 66 | # Convert 67 | path = dir / f'images/VOCdevkit' 68 | for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'): 69 | imgs_path = dir / 'images' / f'{image_set}{year}' 70 | lbs_path = dir / 'labels' / f'{image_set}{year}' 71 | imgs_path.mkdir(exist_ok=True, parents=True) 72 | lbs_path.mkdir(exist_ok=True, parents=True) 73 | 74 | image_ids = open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt').read().strip().split() 75 | for id in tqdm(image_ids, desc=f'{image_set}{year}'): 76 | f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path 77 | lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path 78 | f.rename(imgs_path / f.name) # move image 79 | convert_label(path, lb_path, year, id) # convert labels to YOLO format 80 | -------------------------------------------------------------------------------- /data/VisDrone.yaml: -------------------------------------------------------------------------------- 1 | # VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset 2 | # Train command: python train.py --data VisDrone.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/VisDrone 6 | # /yolov5 7 | 8 | 9 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 10 | path: ../datasets/VisDrone # dataset root dir 11 | train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images 12 | val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images 13 | test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images 14 | 15 | # Classes 16 | nc: 10 # number of classes 17 | names: [ 'pedestrian', 'people', 'bicycle', 'car', 'van', 'truck', 'tricycle', 'awning-tricycle', 'bus', 'motor' ] 18 | 19 | 20 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 21 | download: | 22 | from utils.general import download, os, Path 23 | 24 | def visdrone2yolo(dir): 25 | from PIL import Image 26 | from tqdm import tqdm 27 | 28 | def convert_box(size, box): 29 | # Convert VisDrone box to YOLO xywh box 30 | dw = 1. / size[0] 31 | dh = 1. / size[1] 32 | return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh 33 | 34 | (dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory 35 | pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}') 36 | for f in pbar: 37 | img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size 38 | lines = [] 39 | with open(f, 'r') as file: # read annotation.txt 40 | for row in [x.split(',') for x in file.read().strip().splitlines()]: 41 | if row[4] == '0': # VisDrone 'ignored regions' class 0 42 | continue 43 | cls = int(row[5]) - 1 44 | box = convert_box(img_size, tuple(map(int, row[:4]))) 45 | lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n") 46 | with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl: 47 | fl.writelines(lines) # write label.txt 48 | 49 | 50 | # Download 51 | dir = Path(yaml['path']) # dataset root dir 52 | urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip', 53 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip', 54 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip', 55 | 'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip'] 56 | download(urls, dir=dir) 57 | 58 | # Convert 59 | for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev': 60 | visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels 61 | -------------------------------------------------------------------------------- /data/coco.yaml: -------------------------------------------------------------------------------- 1 | # COCO 2017 dataset http://cocodataset.org 2 | # Train command: python train.py --data coco.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/coco 6 | # /yolov5 7 | 8 | 9 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 10 | path: ../datasets/coco # dataset root dir 11 | train: train2017.txt # train images (relative to 'path') 118287 images 12 | val: val2017.txt # train images (relative to 'path') 5000 images 13 | test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794 14 | 15 | # Classes 16 | nc: 80 # number of classes 17 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 18 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 19 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 20 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 21 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 22 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 23 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 24 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 25 | 'hair drier', 'toothbrush' ] # class names 26 | 27 | 28 | # Download script/URL (optional) 29 | download: | 30 | from utils.general import download, Path 31 | 32 | # Download labels 33 | segments = False # segment or box labels 34 | dir = Path(yaml['path']) # dataset root dir 35 | url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/' 36 | urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels 37 | download(urls, dir=dir.parent) 38 | 39 | # Download data 40 | urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images 41 | 'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images 42 | 'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional) 43 | download(urls, dir=dir / 'images', threads=3) 44 | -------------------------------------------------------------------------------- /data/coco128.yaml: -------------------------------------------------------------------------------- 1 | # COCO 2017 dataset http://cocodataset.org - first 128 training images 2 | # Train command: python train.py --data coco128.yaml 3 | # Default dataset location is next to YOLOv5: 4 | # /parent 5 | # /datasets/coco128 6 | # /yolov5 7 | 8 | 9 | # 数据集源路径root、训练集、验证集、测试集地址 10 | path: ../datasets/coco128 # 数据集源路径root dir 11 | train: images/train2017 # root下的训练集地址 128 images 12 | val: images/train2017 # root下的验证集地址 128 images 13 | test: # root下的验证集地址 128 images 14 | 15 | # 数据集类别信息 16 | nc: 80 # 数据集类别数量 17 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 18 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 19 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 20 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 21 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 22 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 23 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 24 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 25 | 'hair drier', 'toothbrush' ] # 数据集类别名 26 | 27 | # 数据集下载地址 28 | 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | # 1、训练相关参数 6 | lr0: 0.01 # 初始学习率(SGD=1E-2, Adam=1E-3) 7 | lrf: 0.2 # 最终学习率, 以one_cycle形式或者线性从lr0衰减至lr0 * lrf 8 | momentum: 0.937 # SGD momentum/Adam beta1 9 | weight_decay: 0.0005 # optimizer权重衰减系数 5e-4 10 | warmup_epochs: 3.0 # 前3个epoch进行warmup 11 | warmup_momentum: 0.8 # warmup初始化动量 12 | warmup_bias_lr: 0.1 # warmup初始bias学习率 13 | # 2、损失函数相关参数 14 | box: 0.05 # box iou损失系数 15 | cls: 0.5 # cls分类损失系数 16 | cls_pw: 1.0 # cls BCELoss正样本权重 17 | obj: 1.0 # obj loss gain (scale with pixels) 18 | obj_pw: 1.0 # obj BCELoss正样本权重 19 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) 20 | # 3、其他几个参数 21 | iou_t: 0.20 # IoU training threshold? 22 | anchor_t: 4.0 # anchor的长宽比阈值(长:宽 = 4:1) 用于k-means中计算 bpr和aat 23 | #anchors: 3 # 每个输出层的anchors数量 (0 to ignore) 24 | # 4、数据增强相关参数 25 | hsv_h: 0.015 # hsv增强系数 色调 26 | hsv_s: 0.7 # hsv增强系数 饱和度 27 | hsv_v: 0.4 # hsv增强系数 亮度 28 | degrees: 0.0 # random_perspective增强系数 旋转角度 (+/- deg) 29 | translate: 0.1 # random_perspective增强系数 平移 (+/- fraction) 30 | scale: 0.5 # random_perspective增强系数 图像缩放 (+/- gain) 31 | shear: 0.0 # random_perspective增强系数 图像剪切 (+/- deg) 32 | perspective: 0.0 # random_perspective增强系数 透明度 (+/- fraction), range 0-0.001 33 | flipud: 0.0 # 上下翻转数据增强(probability) 34 | fliplr: 0.5 # 左右翻转数据增强(probability) 35 | mosaic: 1.0 # mosaic数据增强(probability) 36 | mixup: 0.0 # mixup数据增强(probability) 37 | cutout: 0.0 # cutout数据增强(probability) 38 | -------------------------------------------------------------------------------- /data/images/bus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/data/images/bus.jpg -------------------------------------------------------------------------------- /data/images/zidane.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/data/images/zidane.jpg -------------------------------------------------------------------------------- /data/pest.yaml: -------------------------------------------------------------------------------- 1 | path: ../datasets/pest 2 | train: # train images (relative to 'path') 1354 images 3 | - images/train 4 | val: # val images (relative to 'path') 339 images 5 | - images/val 6 | test: # test images (optional) 7 | - images/val 8 | 9 | # Classes 10 | nc: 7 # number of classes 11 | names: [ 'Boerner', 'Leconte', 'Linnaeus', 'acuminatus', 'armandie', 'coleoptera', 'linnaeus'] # class names 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /data/scripts/download_weights.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Download latest models from https://github.com/ultralytics/yolov5/releases 3 | # Usage: 4 | # $ bash path/to/download_weights.sh 5 | 6 | python - < NOTE: DOWNLOAD DATA MANUALLY from URL above and unzip to /datasets/xView before running train command below 3 | # Train command: python train.py --data xView.yaml 4 | # Default dataset location is next to YOLOv5: 5 | # /parent 6 | # /datasets/xView 7 | # /yolov5 8 | 9 | 10 | # Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..] 11 | path: ../datasets/xView # dataset root dir 12 | train: images/autosplit_train.txt # train images (relative to 'path') 90% of 847 train images 13 | val: images/autosplit_val.txt # train images (relative to 'path') 10% of 847 train images 14 | 15 | # Classes 16 | nc: 60 # number of classes 17 | names: [ 'Fixed-wing Aircraft', 'Small Aircraft', 'Cargo Plane', 'Helicopter', 'Passenger Vehicle', 'Small Car', 'Bus', 18 | 'Pickup Truck', 'Utility Truck', 'Truck', 'Cargo Truck', 'Truck w/Box', 'Truck Tractor', 'Trailer', 19 | 'Truck w/Flatbed', 'Truck w/Liquid', 'Crane Truck', 'Railway Vehicle', 'Passenger Car', 'Cargo Car', 20 | 'Flat Car', 'Tank car', 'Locomotive', 'Maritime Vessel', 'Motorboat', 'Sailboat', 'Tugboat', 'Barge', 21 | 'Fishing Vessel', 'Ferry', 'Yacht', 'Container Ship', 'Oil Tanker', 'Engineering Vehicle', 'Tower crane', 22 | 'Container Crane', 'Reach Stacker', 'Straddle Carrier', 'Mobile Crane', 'Dump Truck', 'Haul Truck', 23 | 'Scraper/Tractor', 'Front loader/Bulldozer', 'Excavator', 'Cement Mixer', 'Ground Grader', 'Hut/Tent', 'Shed', 24 | 'Building', 'Aircraft Hangar', 'Damaged Building', 'Facility', 'Construction Site', 'Vehicle Lot', 'Helipad', 25 | 'Storage Tank', 'Shipping container lot', 'Shipping Container', 'Pylon', 'Tower' ] # class names 26 | 27 | 28 | # Download script/URL (optional) --------------------------------------------------------------------------------------- 29 | download: | 30 | import json 31 | import os 32 | from pathlib import Path 33 | 34 | import numpy as np 35 | from PIL import Image 36 | from tqdm import tqdm 37 | 38 | from utils.datasets import autosplit 39 | from utils.general import download, xyxy2xywhn 40 | 41 | 42 | def convert_labels(fname=Path('xView/xView_train.geojson')): 43 | # Convert xView geoJSON labels to YOLO format 44 | path = fname.parent 45 | with open(fname) as f: 46 | print(f'Loading {fname}...') 47 | data = json.load(f) 48 | 49 | # Make dirs 50 | labels = Path(path / 'labels' / 'train') 51 | os.system(f'rm -rf {labels}') 52 | labels.mkdir(parents=True, exist_ok=True) 53 | 54 | # xView classes 11-94 to 0-59 55 | xview_class2index = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, -1, 9, 10, 11, 56 | 12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1, 57 | 29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46, 58 | 47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59] 59 | 60 | shapes = {} 61 | for feature in tqdm(data['features'], desc=f'Converting {fname}'): 62 | p = feature['properties'] 63 | if p['bounds_imcoords']: 64 | id = p['image_id'] 65 | file = path / 'train_images' / id 66 | if file.exists(): # 1395.tif missing 67 | try: 68 | box = np.array([int(num) for num in p['bounds_imcoords'].split(",")]) 69 | assert box.shape[0] == 4, f'incorrect box shape {box.shape[0]}' 70 | cls = p['type_id'] 71 | cls = xview_class2index[int(cls)] # xView class to 0-60 72 | assert 59 >= cls >= 0, f'incorrect class index {cls}' 73 | 74 | # Write YOLO label 75 | if id not in shapes: 76 | shapes[id] = Image.open(file).size 77 | box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True) 78 | with open((labels / id).with_suffix('.txt'), 'a') as f: 79 | f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt 80 | except Exception as e: 81 | print(f'WARNING: skipping one label for {file}: {e}') 82 | 83 | 84 | # Download manually from https://challenge.xviewdataset.org 85 | dir = Path(yaml['path']) # dataset root dir 86 | # urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels 87 | # 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images 88 | # 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels) 89 | # download(urls, dir=dir, delete=False) 90 | 91 | # Convert labels 92 | convert_labels(dir / 'xView_train.geojson') 93 | 94 | # Move images 95 | images = Path(dir / 'images') 96 | images.mkdir(parents=True, exist_ok=True) 97 | Path(dir / 'train_images').rename(dir / 'images' / 'train') 98 | Path(dir / 'val_images').rename(dir / 'images' / 'val') 99 | 100 | # Split 101 | autosplit(dir / 'images' / 'train') 102 | -------------------------------------------------------------------------------- /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 # python的命令行解析的标准模块 可以让我们直接在命令行中就可以向程序中传入参数并让程序运行 8 | import sys # sys系统模块 包含了与Python解释器和它的环境有关的函数 9 | import time # 时间模块 更底层 10 | from pathlib import Path # Path将str转换为Path对象 使字符串路径易于操作的模块 11 | 12 | import cv2 # opencv模块 13 | import torch # pytorch模块 14 | import torch.backends.cudnn as cudnn # cuda模块 15 | 16 | FILE = Path(__file__).absolute() # FILE = WindowsPath 'F:\yolo_v5\yolov5-U\detect.py' 17 | # 将'F:/yolo_v5/yolov5-U'加入系统的环境变量 该脚本结束后失效 18 | sys.path.append(FILE.parents[0].as_posix()) # add yolov5-U/ to path 19 | 20 | # ----------------- 导入自定义的其他包 ------------------- 21 | from models.experimental import attempt_load 22 | from utils.datasets import LoadStreams, LoadImages 23 | from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \ 24 | apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box 25 | from utils.plots import colors, plot_one_box 26 | from utils.torch_utils import select_device, load_classifier, time_synchronized, model_info, prune 27 | 28 | 29 | @torch.no_grad() 30 | def run(weights='weights/yolov5s.pt', # 权重文件地址 默认 weights/best.pt 31 | source='data/images', # 测试数据文件(图片或视频)的保存路径 默认data/images 32 | imgsz=640, # 输入图片的大小 默认640(pixels) 33 | conf_thres=0.25, # object置信度阈值 默认0.25 用在nms中 34 | iou_thres=0.45, # 做nms的iou阈值 默认0.45 用在nms中 35 | max_det=1000, # 每张图片最多的目标数量 用在nms中 36 | device='', # 设置代码执行的设备 cuda device, i.e. 0 or 0,1,2,3 or cpu 37 | view_img=False, # 是否展示预测之后的图片或视频 默认False 38 | save_txt=False, # 是否将预测的框坐标以txt文件格式保存 默认True 会在runs/detect/expn/labels下生成每张图片预测的txt文件 39 | save_conf=False, # 是否保存预测每个目标的置信度到预测tx文件中 默认True 40 | save_crop=False, # 是否需要将预测到的目标从原图中扣出来 剪切好 并保存 会在runs/detect/expn下生成crops文件,将剪切的图片保存在里面 默认False 41 | nosave=False, # 是否不要保存预测后的图片 默认False 就是默认要保存预测后的图片 42 | classes=None, # 在nms中是否是只保留某些特定的类 默认是None 就是所有类只要满足条件都可以保留 43 | agnostic_nms=False, # 进行nms是否也除去不同类别之间的框 默认False 44 | augment=False, # 预测是否也要采用数据增强 TTA 默认False 45 | update=False, # 是否将optimizer从ckpt中删除 更新模型 默认False 46 | project='runs/detect', # 当前测试结果放在哪个主文件夹下 默认runs/detect 47 | name='exp', # 当前测试结果放在run/detect下的文件名 默认是exp => run/detect/exp 48 | exist_ok=False, # 是否存在当前文件 默认False 一般是 no exist-ok 连用 所以一般都要重新创建文件夹 49 | line_thickness=3, # bounding box thickness (pixels) 画框的框框的线宽 默认是 3 50 | hide_labels=False, # 画出的框框是否需要隐藏label信息 默认False 51 | hide_conf=False, # 画出的框框是否需要隐藏conf信息 默认False 52 | half=False, # 是否使用半精度 Float16 推理 可以缩短推理时间 但是默认是False 53 | prune_model=False, # 是否使用模型剪枝 进行推理加速 54 | fuse=False, # 是否使用conv + bn融合技术 进行推理加速 55 | ): 56 | 57 | # ===================================== 1、初始化一些配置 ===================================== 58 | # 是否保存预测后的图片 默认nosave=False 所以只要传入的文件地址不是以.txt结尾 就都是要保存预测后的图片的 59 | save_img = not nosave and not source.endswith('.txt') # save inference images True 60 | 61 | # 是否是使用webcam 网页数据 一般是Fasle 因为我们一般是使用图片流LoadImages(可以处理图片/视频流文件) 62 | webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith( 63 | ('rtsp://', 'rtmp://', 'http://', 'https://')) 64 | 65 | # 检查当前Path(project) / name是否存在 如果存在就新建新的save_dir 默认exist_ok=False 需要重建 66 | # 将原先传入的名字扩展成新的save_dir 如runs/detect/exp存在 就扩展成 runs/detect/exp1 67 | save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run 68 | # 如果需要save txt就新建save_dir / 'labels' 否则就新建save_dir 69 | # 默认save_txt=False 所以这里一般都是新建一个 save_dir(runs/detect/expn) 70 | (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir 71 | 72 | # Initialize 初始化日志信息 73 | set_logging() 74 | 75 | # 获取当前主机可用的设备 76 | device = select_device(device) 77 | 78 | # 如果设配是GPU 就使用half(float16) 包括模型半精度和输入图片半精度 79 | half &= device.type != 'cpu' # half precision only supported on CUDA 80 | 81 | 82 | # ===================================== 2、载入模型和模型参数并调整模型 ===================================== 83 | # 2.1、加载Float32模型 84 | model = attempt_load(weights, map_location=device) 85 | 86 | # 是否使用模型剪枝技术 加速推理 87 | if prune_model: 88 | model_info(model) # 打印模型信息 89 | prune(model, 0.3) # 对模型进行剪枝 加速推理 90 | model_info(model) # 再打印模型信息 观察剪枝后模型变化 91 | 92 | # 是否使用模型的conv+bn融合技术 加速推理 93 | if fuse: 94 | model = model.fuse() # 将模型的conv+bn融合 可以加速推理 95 | 96 | # 2.2、载入一些模型参数 97 | # stride: 模型最大的下采样率 [8, 16, 32] 所有stride一般为32 98 | stride = int(model.stride.max()) # model stride 99 | 100 | # 确保输入图片的尺寸imgsz能整除stride=32 如果不能则调整为能被整除并返回 101 | imgsz = check_img_size(imgsz, s=stride) # check image size 保证img size必须是32的倍数 102 | 103 | # 得到数据集的所有类的类名 104 | names = model.module.names if hasattr(model, 'module') else model.names # get class names 105 | 106 | # 2.3、调整模型 107 | # 是否将模型从float32 -> float16 加速推理 108 | if half: 109 | model.half() # to float16 110 | 111 | # 是否加载二次分类模型 112 | # 这里考虑到目标检测完是否需要第二次分类,自己可以考虑自己的任务自己加上 但是这里默认是False的 我们默认不使用 113 | classify = False 114 | if classify: 115 | modelc = load_classifier(name='resnet50', n=2) # initialize 116 | modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval() 117 | 118 | 119 | # ===================================== 3、加载推理数据 ===================================== 120 | # Set Dataloader 121 | # 通过不同的输入源来设置不同的数据加载方式 122 | vid_path, vid_writer = None, None 123 | if webcam: 124 | # 一般不会使用webcam模式从网页中获取数据 125 | view_img = check_imshow() 126 | cudnn.benchmark = True # set True to speed up constant image size inference 127 | dataset = LoadStreams(source, img_size=imgsz, stride=stride) 128 | else: 129 | # 一般是直接从source文件目录下直接读取图片或者视频数据 130 | dataset = LoadImages(source, img_size=imgsz, stride=stride) 131 | 132 | 133 | # ===================================== 4、推理前测试 ===================================== 134 | # 这里先设置一个全零的Tensor进行一次前向推理 判断程序是否正常 135 | if device.type != 'cpu': 136 | model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once 137 | 138 | # ===================================== 5、正式推理 ===================================== 139 | t0 = time.time() 140 | # path: 图片/视频的路径 141 | # img: 进行resize + pad之后的图片 142 | # img0s: 原尺寸的图片 143 | # vid_cap: 当读取图片时为None, 读取视频时为视频源 144 | for path, img, im0s, vid_cap in dataset: 145 | # 5.1、处理每一张图片的格式 146 | img = torch.from_numpy(img).to(device) # numpy array to tensor and device 147 | img = img.half() if half else img.float() # 半精度训练 uint8 to fp16/32 148 | img /= 255.0 # 归一化 0 - 255 to 0.0 - 1.0 149 | # 如果图片是3维(RGB) 就在前面添加一个维度1当中batch_size=1 150 | # 因为输入网络的图片需要是4为的 [batch_size, channel, w, h] 151 | if img.ndimension() == 3: 152 | img = img.unsqueeze(0) 153 | 154 | # 5.2、对每张图片/视频进行前向推理 155 | t1 = time_synchronized() 156 | # pred shape=[1, num_boxes, xywh+obj_conf+classes] = [1, 18900, 25] 157 | pred = model(img, augment=augment)[0] 158 | 159 | # 5.3、nms除去多余的框 160 | # Apply NMS 进行NMS 161 | # conf_thres: 置信度阈值 162 | # iou_thres: iou阈值 163 | # classes: 是否只保留特定的类别 默认为None 164 | # agnostic_nms: 进行nms是否也去除不同类别之间的框 默认False 165 | # max_det: 每张图片的最大目标个数 默认1000 166 | # pred: [num_obj, 6] = [5, 6] 这里的预测信息pred还是相对于 img_size(640) 的 167 | pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det) 168 | t2 = time_synchronized() 169 | 170 | # 5.4、考虑进行二次分类 171 | # Apply Classifier 如果需要二次分类 就进行二次分类 一般是不需要的 172 | if classify: 173 | pred = apply_classifier(pred, modelc, img, im0s) 174 | 175 | # 5.5、后续保存或者打印预测信息 176 | # 对每张图片进行处理 将pred(相对img_size 640)映射回原图img0 size 177 | for i, det in enumerate(pred): # detections per image 178 | 179 | if webcam: 180 | # 如果输入源是webcam(网页)则batch_size>=1 取出dataset中的一张图片 181 | p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count 182 | else: 183 | # 但是大部分我们一般都是从LoadImages流读取本都文件中的照片或者视频 所以batch_size=1 184 | # p: 当前图片/视频的绝对路径 如 F:\yolo_v5\yolov5-U\data\images\bus.jpg 185 | # s: 输出信息 初始为 '' 186 | # im0: 原始图片 letterbox + pad 之前的图片 187 | # frame: 初始为0 可能是当前图片属于视频中的第几帧? 188 | p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0) 189 | 190 | # 当前图片路径 如 F:\yolo_v5\yolov5-U\data\images\bus.jpg 191 | p = Path(p) # to Path 192 | # 图片/视频的保存路径save_path 如 runs\\detect\\exp8\\bus.jpg 193 | save_path = str(save_dir / p.name) # img.jpg 194 | # txt文件(保存预测框坐标)保存路径 如 runs\\detect\\exp8\\labels\\bus 195 | txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt 196 | 197 | # print string 输出信息 图片shape (w, h) 198 | s += '%gx%g ' % img.shape[2:] 199 | 200 | # normalization gain gn = [w, h, w, h] 用于后面的归一化 201 | gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] 202 | 203 | # imc: for save_crop 在save_crop中使用 204 | imc = im0.copy() if save_crop else im0 205 | 206 | if len(det): 207 | # Rescale boxes from img_size to im0 size 208 | # 将预测信息(相对img_size 640)映射回原图 img0 size 209 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 210 | 211 | # Print results 212 | # 输出信息s + 检测到的各个类别的目标个数 213 | for c in det[:, -1].unique(): 214 | n = (det[:, -1] == c).sum() # detections per class 215 | s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string 216 | 217 | # Write results 218 | # 保存预测信息: txt、img0上画框、crop_img 219 | for *xyxy, conf, cls in reversed(det): 220 | # 将每个图片的预测信息分别存入save_dir/labels下的xxx.txt中 每行: class_id+score+xywh 221 | if save_txt: # Write to file(txt) 222 | # 将xyxy(左上角 + 右下角)格式转换为xywh(中心的 + 宽高)格式 并除以gn(whwh)做归一化 转为list再保存 223 | xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh 224 | line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format 225 | with open(txt_path + '.txt', 'a') as f: 226 | f.write(('%g ' * len(line)).rstrip() % line + '\n') 227 | 228 | # 在原图上画框 + 将预测到的目标剪切出来 保存成图片 保存在save_dir/crops下 229 | if save_img or save_crop or view_img: 230 | c = int(cls) # integer class 231 | label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') 232 | plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness) 233 | if save_crop: 234 | # 如果需要就将预测到的目标剪切出来 保存成图片 保存在save_dir/crops下 235 | save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True) 236 | 237 | # 打印前向传播 + NMS 花费的时间 238 | print(f'{s}Done. ({t2 - t1:.3f}s)') 239 | 240 | # Stream results 241 | # 是否需要显示我们预测后的结果 img0(此时已将pred结果可视化到了img0中) 242 | if view_img: 243 | cv2.imshow(str(p), im0) 244 | cv2.waitKey(1) # 1 millisecond 245 | 246 | # Save results (image with detections) 247 | # 是否需要保存图片或视频(检测后的图片/视频 里面已经被我们画好了框的) img0 248 | if save_img: 249 | if dataset.mode == 'image': 250 | cv2.imwrite(save_path, im0) 251 | else: # 'video' or 'stream' 252 | if vid_path != save_path: # new video 253 | vid_path = save_path 254 | if isinstance(vid_writer, cv2.VideoWriter): 255 | vid_writer.release() # release previous video writer 256 | if vid_cap: # video 257 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 258 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 259 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 260 | else: # stream 261 | fps, w, h = 30, im0.shape[1], im0.shape[0] 262 | save_path += '.mp4' 263 | vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) 264 | vid_writer.write(im0) 265 | 266 | 267 | 268 | # ===================================== 6、推理结束, 保存结果, 打印信息 ===================================== 269 | # 保存预测的label信息 xywh等 save_txt 270 | if save_txt or save_img: 271 | s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else '' 272 | print(f"Results saved to {save_dir}{s}") 273 | 274 | if update: 275 | # strip_optimizer函数将optimizer从ckpt中删除 更新模型 276 | strip_optimizer(weights) # update model (to fix SourceChangeWarning) 277 | 278 | # 打印预测的总时间 279 | print(f'Done. ({time.time() - t0:.3f}s)') 280 | 281 | 282 | def parse_opt(): 283 | """ 284 | opt参数解析 285 | weights: 模型的权重地址 默认 weights/best.pt 286 | source: 测试数据文件(图片或视频)的保存路径 默认data/images 287 | imgsz: 网络输入图片的大小 默认640 288 | conf-thres: object置信度阈值 默认0.25 289 | iou-thres: 做nms的iou阈值 默认0.45 290 | max-det: 每张图片最大的目标个数 默认1000 291 | device: 设置代码执行的设备 cuda device, i.e. 0 or 0,1,2,3 or cpu 292 | view-img: 是否展示预测之后的图片或视频 默认False 293 | save-txt: 是否将预测的框坐标以txt文件格式保存 默认True 会在runs/detect/expn/labels下生成每张图片预测的txt文件 294 | save-conf: 是否保存预测每个目标的置信度到预测tx文件中 默认True 295 | save-crop: 是否需要将预测到的目标从原图中扣出来 剪切好 并保存 会在runs/detect/expn下生成crops文件,将剪切的图片保存在里面 默认False 296 | nosave: 是否不要保存预测后的图片 默认False 就是默认要保存预测后的图片 297 | classes: 在nms中是否是只保留某些特定的类 默认是None 就是所有类只要满足条件都可以保留 298 | agnostic-nms: 进行nms是否也除去不同类别之间的框 默认False 299 | augment: 预测是否也要采用数据增强 TTA 300 | update: 是否将optimizer从ckpt中删除 更新模型 默认False 301 | project: 当前测试结果放在哪个主文件夹下 默认runs/detect 302 | name: 当前测试结果放在run/detect下的文件名 默认是exp 303 | exist-ok: 是否存在当前文件 默认False 一般是 no exist-ok 连用 所以一般都要重新创建文件夹 304 | line-thickness: 画框的框框的线宽 默认是 3 305 | hide-labels: 画出的框框是否需要隐藏label信息 默认False 306 | hide-conf: 画出的框框是否需要隐藏conf信息 默认False 307 | half: 是否使用半精度 Float16 推理 可以缩短推理时间 但是默认是False 308 | """ 309 | parser = argparse.ArgumentParser() 310 | parser.add_argument('--weights', nargs='+', type=str, default='weights/best.pt', help='model.pt path(s)') 311 | parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam') 312 | parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)') 313 | parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold') 314 | parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold') 315 | parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image') 316 | parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 317 | parser.add_argument('--view-img', action='store_true', help='show results') 318 | parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') 319 | parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') 320 | parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes') 321 | parser.add_argument('--nosave', action='store_true', help='do not save images/videos') 322 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') 323 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 324 | parser.add_argument('--augment', action='store_true', help='augmented inference') 325 | parser.add_argument('--update', action='store_true', help='update all models') 326 | parser.add_argument('--project', default='runs/detect', help='save results to project/name') 327 | parser.add_argument('--name', default='exp', help='save results to project/name') 328 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') 329 | parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)') 330 | parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels') 331 | parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences') 332 | parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference') 333 | parser.add_argument('--prune-model', default=False, action='store_true', help='model prune') 334 | parser.add_argument('--fuse', default=False, action='store_true', help='fuse conv and bn') 335 | opt = parser.parse_args() 336 | return opt 337 | 338 | 339 | def main(opt): 340 | # 调用colorstr函数彩色打印选择的opt参数 341 | print(colorstr('detect: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) 342 | # 检查已经安装的包是否满足requirements对应txt文件的要求 343 | check_requirements(exclude=('tensorboard', 'thop')) 344 | # 执行run 开始推理 345 | run(**vars(opt)) 346 | 347 | 348 | if __name__ == "__main__": 349 | opt = parse_opt() 350 | main(opt) 351 | -------------------------------------------------------------------------------- /models/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 | class SiLU(nn.Module): 9 | # SiLU/Swish 10 | # https://arxiv.org/pdf/1606.08415.pdf 11 | @staticmethod 12 | def forward(x): 13 | return x * torch.sigmoid(x) # 默认参数 = 1 14 | 15 | class MemoryEfficientSwish(nn.Module): 16 | # 节省内存的Swish 不采用自动求导(自己写前向传播和反向传播) 更高效 17 | class F(torch.autograd.Function): 18 | @staticmethod 19 | def forward(ctx, x): 20 | # save_for_backward会保留x的全部信息(一个完整的外挂Autograd Function的Variable), 21 | # 并提供避免in-place操作导致的input在backward被修改的情况. 22 | # in-place操作指不通过中间变量计算的变量间的操作。 23 | ctx.save_for_backward(x) 24 | return x * torch.sigmoid(x) 25 | 26 | @staticmethod 27 | def backward(ctx, grad_output): 28 | # 此处saved_tensors[0] 作用同上文 save_for_backward 29 | x = ctx.saved_tensors[0] 30 | sx = torch.sigmoid(x) 31 | # 返回该激活函数求导之后的结果 求导过程见上文 32 | return grad_output * (sx * (1 + x * (1 - sx))) 33 | 34 | def forward(self, x): # 应用前向传播方法 35 | return self.F.apply(x) 36 | 37 | class Hardswish(nn.Module): 38 | """ 39 | hard-swish 图形和Swish很相似 在mobilenet v3中提出 40 | https://arxiv.org/pdf/1905.02244.pdf 41 | """ 42 | @staticmethod 43 | def forward(x): 44 | # return x * F.hardsigmoid(x) # for torchscript and CoreML 45 | return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX 46 | 47 | class Mish(nn.Module): 48 | """ 49 | Mish 激活函数 50 | https://arxiv.org/pdf/1908.08681.pdf 51 | https://github.com/digantamisra98/Mish/blob/master/Mish/Torch/mish.py 52 | """ 53 | @staticmethod 54 | def forward(x): 55 | return x * F.softplus(x).tanh() # softplus(x) = ln(1 + exp(x) 56 | 57 | class MemoryEfficientMish(nn.Module): 58 | """ 59 | 一种高效的Mish激活函数 不采用自动求导(自己写前向传播和反向传播) 更高效 60 | """ 61 | class F(torch.autograd.Function): 62 | @staticmethod 63 | def forward(ctx, x): 64 | # 前向传播 65 | # save_for_backward函数可以将对象保存起来,用于后续的backward函数 66 | # 会保留此input的全部信息,并提供避免in_place操作导致的input在backward中被修改的情况 67 | ctx.save_for_backward(x) 68 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) 69 | 70 | @staticmethod 71 | def backward(ctx, grad_output): 72 | # 反向传播 73 | x = ctx.saved_tensors[0] 74 | sx = torch.sigmoid(x) 75 | fx = F.softplus(x).tanh() 76 | return grad_output * (fx + x * sx * (1 - fx * fx)) 77 | 78 | def forward(self, x): 79 | return self.F.apply(x) 80 | 81 | class FReLU(nn.Module): 82 | """ 83 | FReLU https://arxiv.org/abs/2007.11824 84 | """ 85 | def __init__(self, c1, k=3): # ch_in, kernel 86 | super().__init__() 87 | # 定义漏斗条件T(x) 参数池窗口(Parametric Pooling Window )来创建空间依赖 88 | # nn.Con2d(in_channels, out_channels, kernel_size, stride, padding, dilation=1, bias=True) 89 | # 使用 深度可分离卷积 DepthWise Separable Conv + BN 实现T(x) 90 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) 91 | self.bn = nn.BatchNorm2d(c1) 92 | 93 | def forward(self, x): 94 | # f(x)=max(x, T(x)) 95 | return torch.max(x, self.bn(self.conv(x))) 96 | 97 | class AconC(nn.Module): 98 | """ 99 | ACON https://arxiv.org/pdf/2009.04759.pdf 100 | ACON activation (activate or not). 101 | AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter 102 | according to "Activate or Not: Learning Customized Activation" . 103 | """ 104 | 105 | def __init__(self, c1): 106 | super().__init__() 107 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) 108 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) 109 | self.beta = nn.Parameter(torch.ones(1, c1, 1, 1)) 110 | 111 | def forward(self, x): 112 | dpx = (self.p1 - self.p2) * x 113 | return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x 114 | 115 | class MetaAconC(nn.Module): 116 | r""" ACON activation (activate or not). 117 | MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network 118 | according to "Activate or Not: Learning Customized Activation" . 119 | """ 120 | 121 | def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r 122 | super().__init__() 123 | c2 = max(r, c1 // r) 124 | self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1)) 125 | self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1)) 126 | self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True) 127 | self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True) 128 | # self.bn1 = nn.BatchNorm2d(c2) 129 | # self.bn2 = nn.BatchNorm2d(c1) 130 | 131 | def forward(self, x): 132 | y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True) 133 | # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891 134 | # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable 135 | beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed 136 | dpx = (self.p1 - self.p2) * x 137 | return dpx * torch.sigmoid(beta * dpx) + self.p2 * x 138 | 139 | class DyReLU(nn.Module): 140 | def __init__(self, channels, reduction=4, k=2, conv_type='2d'): 141 | super(DyReLU, self).__init__() 142 | self.channels = channels 143 | self.k = k 144 | self.conv_type = conv_type 145 | assert self.conv_type in ['1d', '2d'] 146 | 147 | self.fc1 = nn.Linear(channels, channels // reduction) 148 | self.relu = nn.ReLU(inplace=True) 149 | self.fc2 = nn.Linear(channels // reduction, 2*k) 150 | self.sigmoid = nn.Sigmoid() 151 | 152 | self.register_buffer('lambdas', torch.Tensor([1.]*k + [0.5]*k).float()) 153 | self.register_buffer('init_v', torch.Tensor([1.] + [0.]*(2*k - 1)).float()) 154 | 155 | def get_relu_coefs(self, x): 156 | theta = torch.mean(x, dim=-1) 157 | if self.conv_type == '2d': 158 | theta = torch.mean(theta, dim=-1) 159 | theta = self.fc1(theta) 160 | theta = self.relu(theta) 161 | theta = self.fc2(theta) 162 | theta = 2 * self.sigmoid(theta) - 1 163 | return theta 164 | 165 | def forward(self, x): 166 | raise NotImplementedError 167 | 168 | class DyReLUA(DyReLU): 169 | """ 170 | 调用: self.relu = DyReLUB(64, conv_type='2d') 64=本层channels 171 | """ 172 | def __init__(self, channels, reduction=4, k=2, conv_type='2d'): 173 | super(DyReLUA, self).__init__(channels, reduction, k, conv_type) 174 | self.fc2 = nn.Linear(channels // reduction, 2*k) 175 | 176 | def forward(self, x): 177 | assert x.shape[1] == self.channels 178 | theta = self.get_relu_coefs(x) # 这里是执行到normalize 179 | relu_coefs = theta.view(-1, 2*self.k) * self.lambdas + self.init_v # 这里是执行完 theta(x) 180 | 181 | # BxCxL -> LxCxBx1 182 | x_perm = x.transpose(0, -1).unsqueeze(-1) 183 | # a^k_c=relu_coefs[:, :self.k] b^k_c=relu_coefs[:, self.k:] 184 | # a^k_c(x) * x_c + b^k_c(x) 185 | output = x_perm * relu_coefs[:, :self.k] + relu_coefs[:, self.k:] 186 | # LxCxBx2 -> BxCxL 187 | # y_c = max{a^k_c(x) * x_c + b^k_c(x)} 188 | result = torch.max(output, dim=-1)[0].transpose(0, -1) 189 | 190 | return result 191 | 192 | class DyReLUB(DyReLU): 193 | def __init__(self, channels, reduction=4, k=2, conv_type='2d'): 194 | super(DyReLUB, self).__init__(channels, reduction, k, conv_type) 195 | self.fc2 = nn.Linear(channels // reduction, 2*k*channels) 196 | 197 | def forward(self, x): 198 | assert x.shape[1] == self.channels 199 | theta = self.get_relu_coefs(x) 200 | 201 | relu_coefs = theta.view(-1, self.channels, 2*self.k) * self.lambdas + self.init_v 202 | 203 | if self.conv_type == '1d': 204 | # BxCxL -> LxBxCx1 205 | x_perm = x.permute(2, 0, 1).unsqueeze(-1) 206 | output = x_perm * relu_coefs[:, :, :self.k] + relu_coefs[:, :, self.k:] 207 | # LxBxCx2 -> BxCxL 208 | result = torch.max(output, dim=-1)[0].permute(1, 2, 0) 209 | 210 | elif self.conv_type == '2d': 211 | # BxCxHxW -> HxWxBxCx1 212 | x_perm = x.permute(2, 3, 0, 1).unsqueeze(-1) 213 | output = x_perm * relu_coefs[:, :, :self.k] + relu_coefs[:, :, self.k:] 214 | # HxWxBxCx2 -> BxCxHxW 215 | result = torch.max(output, dim=-1)[0].permute(2, 3, 0, 1) 216 | 217 | return result 218 | 219 | 220 | -------------------------------------------------------------------------------- /models/experimental.py: -------------------------------------------------------------------------------- 1 | # YOLOv5 experimental modules 2 | 3 | import numpy as np # numpy矩阵操作模块 4 | import torch # PyTorch深度学习模块 5 | import torch.nn as nn # PYTorch模块函数库 6 | 7 | from models.common import Conv, DWConv 8 | from utils.google_utils import attempt_download 9 | 10 | 11 | class GhostConv(nn.Module): 12 | """ 13 | Ghost Convolution 幻象卷积 轻量化网络卷积模块 14 | 论文: https://arxiv.org/abs/1911.11907 15 | 源码: https://github.com/huawei-noah/ghostnet 16 | 常见的几种使用方式: https://github.com/ultralytics/yolov5/issues/2905 17 | """ 18 | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups 19 | super(GhostConv, self).__init__() 20 | c_ = c2 // 2 # hidden channels 21 | # 第一步卷积: 少量卷积, 一般是一半的计算量 22 | self.cv1 = Conv(c1, c_, k, s, None, g, act) 23 | # 第二步卷积: cheap operations 使用3x3或5x5的卷积, 并且是逐个特征图的进行卷积(Depth-wise convolutional) 24 | self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) 25 | 26 | def forward(self, x): 27 | y = self.cv1(x) 28 | return torch.cat([y, self.cv2(y)], 1) 29 | class GhostBottleneck(nn.Module): 30 | """ 31 | Ghost Convolution 幻象卷积 轻量化网络卷积模块 32 | 论文: https://arxiv.org/abs/1911.11907 33 | 源码: https://github.com/huawei-noah/ghostnet 34 | """ 35 | def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride 36 | super(GhostBottleneck, self).__init__() 37 | c_ = c2 // 2 38 | self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw 39 | DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw 40 | GhostConv(c_, c2, 1, 1, act=False)) # pw-linear 41 | # 注意, 源码中并不是直接Identity连接, 而是先经过一个DWConv + Conv, 再进行shortcut连接的。 42 | self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), 43 | Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() 44 | 45 | def forward(self, x): 46 | return self.conv(x) + self.shortcut(x) 47 | 48 | class MixConv2d(nn.Module): 49 | """ 50 | Mixed Depthwise Conv 混合深度卷积 就是使用不同大小的卷积核对深度卷积的不同channel分组处理 也可以看作是分组深度卷积 + Inception结构的多种卷积核混用 51 | 论文: https://arxiv.org/abs/1907.09595. 52 | 源码: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet/mixnet. 53 | """ 54 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): 55 | """ 56 | :params c1: 输入feature map的通道数 57 | :params c2: 输出的feature map的通道数(这个函数的关键点就是对c2进行分组) 58 | :params k: 混合的卷积核大小 其实论文里是[3, 5, 7...]用的比较多的 59 | :params s: 步长 stride 60 | :params equal_ch: 通道划分方式 有均等划分和指数划分两种方式 默认是均等划分 61 | """ 62 | super(MixConv2d, self).__init__() 63 | groups = len(k) 64 | if equal_ch: # 均等划分通道 65 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices 66 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels 67 | else: # 指数划分通道 68 | b = [c2] + [0] * groups 69 | a = np.eye(groups + 1, groups, k=-1) 70 | a -= np.roll(a, 1, axis=1) 71 | a *= np.array(k) ** 2 72 | a[0] = 1 73 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b 74 | 75 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)]) 76 | self.bn = nn.BatchNorm2d(c2) 77 | self.act = nn.LeakyReLU(0.1, inplace=True) 78 | 79 | def forward(self, x): 80 | # 这里和原论文略有出入,这里加了一个shortcut操作 81 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) 82 | 83 | class Ensemble(nn.ModuleList): 84 | """ 85 | 模型集成 Ensemble of models 86 | 动机: 减少模型的泛化误差 87 | https://github.com/ultralytics/yolov5/issues/318 88 | 来源: https://www.sciencedirect.com/topics/computer-science/ensemble-modeling 89 | """ 90 | def __init__(self): 91 | super(Ensemble, self).__init__() 92 | 93 | def forward(self, x, augment=False): 94 | y = [] 95 | # 集成模型为多个模型时, 在每一层forward运算时, 都要运行多个模型在该层的结果append进y中 96 | for module in self: 97 | y.append(module(x, augment)[0]) # 添加module 98 | # y = torch.stack(y).max(0)[0] # 求两个模型结果的最大值 max ensemble 99 | y = torch.stack(y).mean(0) # 求两个模型结果的均值 mean ensemble 100 | # y = torch.cat(y, 1) # 将两个模型结果concat 后面做nms(等于翻了一倍的pred) nms ensemble 101 | return y, None # inference, train output 102 | 103 | def attempt_load(weights, map_location=None, inplace=True): 104 | """用在val.py、detect.py、train.py等文件中 一般用在测试、验证阶段 105 | 加载模型权重文件并构建模型(可以构造普通模型或者集成模型) 106 | Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a 107 | :params weights: 模型的权重文件地址 默认weights/yolov5s.pt 108 | 可以是[a]也可以是list格式[a, b] 如果是list格式将调用上面的模型集成函数 多模型运算 提高最终模型的泛化误差 109 | :params map_location: attempt_download函数参数 表示模型运行设备device 110 | :params inplace: pytorch 1.7.0 compatibility设置 111 | """ 112 | from models.yolo import Detect, Model 113 | 114 | model = Ensemble() 115 | for w in weights if isinstance(weights, list) else [weights]: 116 | ckpt = torch.load(attempt_download(w), map_location=map_location) # load model weights 117 | model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model->fuse融合->验证模式 118 | 119 | # Compatibility updates(关于版本兼容的设置) 120 | for m in model.modules(): 121 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]: 122 | m.inplace = inplace # pytorch 1.7.0 compatibility 123 | elif type(m) is Conv: 124 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 125 | 126 | if len(model) == 1: # 单个模型 正常返回 127 | return model[-1] # return model 128 | else: # 多个模型 使用模型集成 并对模型先进行一些必要的设置 129 | print(f'Ensemble created with {weights}\n') 130 | # 给每个模型一个name属性 131 | for k in ['names']: 132 | setattr(model, k, getattr(model[-1], k)) 133 | # 给每个模型分配stride属性 134 | model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride 135 | return model # return ensemble 返回集成模型 136 | 137 | class CrossConv(nn.Module): 138 | """可以用在C3模块中(实验) 139 | Cross Convolution Downsample 3x3 -> 1x9 + 9x1 140 | https://github.com/ultralytics/yolov5/issues/4030 141 | """ 142 | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): 143 | # ch_in, ch_out, kernel, stride, groups, expansion, shortcut 144 | super(CrossConv, self).__init__() 145 | c_ = int(c2 * e) # hidden channels 146 | # 1x5+5x1 或1x3+3x1 可以多多尝试 147 | self.cv1 = Conv(c1, c_, (1, k), (1, s)) 148 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) 149 | self.add = shortcut and c1 == c2 150 | 151 | def forward(self, x): 152 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) 153 | 154 | class Sum(nn.Module): 155 | """ 156 | 加权特征融合: 学习不同输入特征的重要性,对不同输入特征有区分的融合 Weighted sum of 2 or more layers 157 | 思想: 传统的特征融合往往只是简单的feature map叠加/相加 (sum them up), 比如使用concat或者shortcut连接, 而不对同时加进来的 158 | feature map进行区分。然而,不同的输入feature map具有不同的分辨率, 它们对融合输入feature map的贡献也是不同的, 因此简单 159 | 的对他们进行相加或叠加处理并不是最佳的操作, 所以这里我们提出了一种简单而高效的加权特融合的机制。 160 | from: https://arxiv.org/abs/1911.09070 161 | """ 162 | def __init__(self, n, weight=False): # n: number of inputs 163 | super(Sum, self).__init__() 164 | self.weight = weight # 是否使用加权权重融合 165 | self.iter = range(n - 1) # 加权 iter 166 | if weight: 167 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # 初始化可学习权重 168 | 169 | def forward(self, x): 170 | y = x[0] # no weight 171 | if self.weight: 172 | w = torch.sigmoid(self.w) * 2 # 得到每一个layer的可学习权重 173 | for i in self.iter: 174 | y = y + x[i + 1] * w[i] # 加权特征融合 175 | else: 176 | for i in self.iter: 177 | y = y + x[i + 1] # 特征融合 178 | return y 179 | -------------------------------------------------------------------------------- /models/export.py: -------------------------------------------------------------------------------- 1 | """Export a YOLOv5 *.pt model to TorchScript, ONNX, CoreML formats 2 | 3 | Usage: 4 | $ python path/to/export.py --weights yolov5s.pt --img 640 --batch 1 5 | """ 6 | 7 | import argparse # 解析命令行参数模块 8 | import sys # sys系统模块 包含了与Python解释器和它的环境有关的函数 9 | import time # 时间模块 更底层 10 | from pathlib import Path # Path将str转换为Path对象 使字符串路径易于操作的模块 11 | 12 | import torch # PyTorch深度学习模块 13 | import torch.nn as nn # 对torch.nn.functional的类的封装 有很多和torch.nn.functional相同的函数 14 | from torch.utils.mobile_optimizer import optimize_for_mobile # 对模型进行移动端优化模块 15 | 16 | FILE = Path(__file__).absolute() # FILE = WindowsPath 'F:\yolo_v5\yolov5-U\export.py' 17 | # 将'F:/yolo_v5/yolov5-U'加入系统的环境变量 该脚本结束后失效 18 | sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path 19 | 20 | from models.common import Conv 21 | from models.yolo import Detect 22 | from models.experimental import attempt_load 23 | from models.activations import Hardswish, SiLU 24 | from utils.general import colorstr, check_img_size, check_requirements, file_size, set_logging 25 | from utils.torch_utils import select_device 26 | 27 | 28 | def run(weights='../weights/yolov5s.pt', img_size=(640, 640), batch_size=1, device='cpu', 29 | include=('torchscript', 'onnx', 'coreml'), half=False, inplace=False, train=False, 30 | optimize=False, dynamic=False, simplify=False, opset_version=12,): 31 | """ 32 | weights: 要转换的权重文件pt地址 默认='../weights/best.pt' 33 | img-size: 输入模型的图片size=(height, width) 默认=[640, 640] 34 | batch-size: batch大小 默认=1 35 | device: 模型运行设备 cuda device, i.e. 0 or 0,1,2,3 or cpu 默认=cpu 36 | include: 要将pt文件转为什么格式 可以为单个原始也可以为list 默认=['torchscript', 'onnx', 'coreml'] 37 | half: 是否使用半精度FP16export转换 默认=False 38 | inplace: 是否set YOLOv5 Detect() inplace=True 默认=False 39 | train: 是否开启model.train() mode 默认=True coreml转换必须为True 40 | optimize: TorchScript转化参数 是否进行移动端优化 默认=False 41 | dynamic: ONNX转换参数 dynamic_axes ONNX转换是否要进行批处理变量 默认=False 42 | simplify: ONNX转换参数 是否简化onnx模型 默认=False 43 | opset-version: ONNX转换参数 设置版本 默认=10 44 | """ 45 | t = time.time() # 获取当前时间 46 | include = [x.lower() for x in include] # pt文件要转化的格式包括哪些 47 | img_size *= 2 if len(img_size) == 1 else 1 # expand 48 | 49 | # Load PyTorch model 50 | device = select_device(device) # 选择设备 51 | assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0' 52 | model = attempt_load(weights, map_location=device) # load FP32 model 53 | labels = model.names # 载入数据集name 54 | 55 | # Input 56 | gs = int(max(model.stride)) # grid size (max stride) 57 | img_size = [check_img_size(x, gs) for x in img_size] # verify img_size are gs-multiples 58 | img = torch.zeros(batch_size, 3, *img_size).to(device) # 自定义一张图片 输入model 59 | 60 | # Update model 61 | # 是否采样半精度FP16训练or推理 62 | if half: 63 | img, model = img.half(), model.half() # to FP16 64 | # 是否开启train模式 65 | model.train() if train else model.eval() # training mode = no Detect() layer grid construction 66 | # 调整模型配置 67 | for k, m in model.named_modules(): 68 | # pytorch 1.6.0 compatibility(关于版本兼容的设置) 使模型兼容pytorch 1.6.0 69 | m._non_persistent_buffers_set = set() 70 | # assign export-friendly activations(有些导出的格式是不兼容系统自带的nn.Hardswish、nn.SiLU的) 71 | if isinstance(m, Conv): 72 | if isinstance(m.act, nn.Hardswish): 73 | m.act = Hardswish() 74 | elif isinstance(m.act, nn.SiLU): 75 | m.act = SiLU() 76 | # 模型相关设置: Detect类的inplace参数和onnx_dynamic参数 77 | elif isinstance(m, Detect): 78 | m.inplace = inplace 79 | m.onnx_dynamic = dynamic # 设置Detect的onnx_dynamic参数为dynamic 80 | # m.forward = m.forward_export # assign forward (optional) 81 | 82 | for _ in range(2): 83 | y = model(img) # dry runs 前向推理2次 84 | print(f"\n{colorstr('PyTorch:')} starting from {weights} ({file_size(weights):.1f} MB)") 85 | 86 | # ================================ 转换模型 ==================================== 87 | # TorchScript export ----------------------------------------------------------------------------------------------- 88 | if 'torchscript' in include or 'coreml' in include: 89 | prefix = colorstr('TorchScript:') 90 | try: 91 | print(f'\n{prefix} starting export with torch {torch.__version__}...') 92 | f = weights.replace('.pt', '.torchscript.pt') # export torchscript filename 93 | ts = torch.jit.trace(model, img, strict=False) # convert 94 | # optimize_for_mobile: 移动端优化 95 | (optimize_for_mobile(ts) if optimize else ts).save(f) # save 96 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 97 | except Exception as e: 98 | print(f'{prefix} export failure: {e}') 99 | 100 | # ONNX export ------------------------------------------------------------------------------------------------------ 101 | if 'onnx' in include: 102 | prefix = colorstr('ONNX:') 103 | try: 104 | import onnx 105 | 106 | print(f'{prefix} starting export with onnx {onnx.__version__}...') # 日志 107 | f = weights.replace('.pt', '.onnx') # export filename 108 | # convert 109 | torch.onnx.export(model, img, f, verbose=False, opset_version=opset_version, 110 | training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL, 111 | do_constant_folding=not train, # 是否执行常量折叠优化 112 | input_names=['images'], # 输入名 113 | output_names=['output'], # 输出名 114 | # 批处理变量 若不想支持批处理或固定批处理大小,移除dynamic_axes字段即可 115 | dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640) 116 | 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85) 117 | } if dynamic else None) 118 | 119 | # Checks 120 | model_onnx = onnx.load(f) # load onnx model 121 | onnx.checker.check_model(model_onnx) # check onnx model 122 | # print(onnx.helper.printable_graph(model_onnx.graph)) # print 123 | 124 | # Simplify 125 | if simplify: 126 | try: 127 | check_requirements(['onnx-simplifier']) 128 | import onnxsim 129 | 130 | print(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...') 131 | # simplify 简化 132 | model_onnx, check = onnxsim.simplify( 133 | model_onnx, 134 | dynamic_input_shape=dynamic, 135 | input_shapes={'images': list(img.shape)} if dynamic else None) 136 | assert check, 'assert check failed' 137 | onnx.save(model_onnx, f) # save 138 | except Exception as e: 139 | print(f'{prefix} simplifier failure: {e}') 140 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 141 | except Exception as e: 142 | print(f'{prefix} export failure: {e}') 143 | 144 | # CoreML export ---------------------------------------------------------------------------------------------------- 145 | # 注意: 转换CoreML时必须设置model.train 即opt参数train为True 146 | if 'coreml' in include: 147 | prefix = colorstr('CoreML:') 148 | try: 149 | import coremltools as ct 150 | 151 | print(f'{prefix} starting export with coremltools {ct.__version__}...') 152 | assert train, 'CoreML exports should be placed in model.train() mode with `python export.py --train`' 153 | model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])]) # convert 154 | f = weights.replace('.pt', '.mlmodel') # export coreml filename 155 | model.save(f) # save 156 | print(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)') 157 | except Exception as e: 158 | print(f'{prefix} export failure: {e}') 159 | 160 | # Finish 161 | print(f'\nExport complete ({time.time() - t:.2f}s). Visualize with https://github.com/lutzroeder/netron.') 162 | 163 | 164 | def parse_opt(): 165 | """ 166 | weights: 要转换的权重文件pt地址 默认='../weights/best.pt' 167 | img-size: 输入模型的图片size=(height, width) 默认=[640, 640] 168 | batch-size: batch大小 默认=1 169 | device: 模型运行设备 cuda device, i.e. 0 or 0,1,2,3 or cpu 默认=cpu 170 | include: 要将pt文件转为什么格式 可以为单个原始也可以为list 默认=['torchscript', 'onnx', 'coreml'] 171 | half: 是否使用半精度FP16export转换 默认=False 172 | inplace: 是否set YOLOv5 Detect() inplace=True 默认=False 173 | train: 是否开启model.train() mode 默认=True coreml转换必须为True 174 | optimize: TorchScript转化参数 是否进行移动端优化 默认=False 175 | dynamic: ONNX转换参数 dynamic_axes ONNX转换是否要进行批处理变量 默认=False 176 | simplify: ONNX转换参数 是否简化onnx模型 默认=False 177 | opset-version: ONNX转换参数 设置版本 默认=10 178 | """ 179 | parser = argparse.ArgumentParser() 180 | parser.add_argument('--weights', type=str, default='../weights/best.pt', help='weights path') 181 | parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image (height, width)') 182 | parser.add_argument('--batch-size', type=int, default=1, help='batch size') 183 | parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 184 | parser.add_argument('--include', nargs='+', default=['torchscript', 'onnx', 'coreml'], help='include formats') 185 | parser.add_argument('--half', action='store_true', help='FP16 half-precision export') 186 | parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True') 187 | parser.add_argument('--train', default="True", action='store_true', help='model.train() mode') 188 | parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile') 189 | parser.add_argument('--dynamic', action='store_true', help='ONNX: dynamic axes') 190 | parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model') 191 | parser.add_argument('--opset-version', type=int, default=10, help='ONNX: opset version') 192 | opt = parser.parse_args() 193 | return opt 194 | 195 | 196 | def main(opt): 197 | # 初始化日志 198 | set_logging() 199 | print(colorstr('export: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items())) # 彩色打印 200 | # 脚本主体 201 | run(**vars(opt)) 202 | 203 | 204 | if __name__ == "__main__": 205 | opt = parse_opt() 206 | main(opt) 207 | -------------------------------------------------------------------------------- /models/hub/anchors.yaml: -------------------------------------------------------------------------------- 1 | # Default YOLOv5 anchors for COCO data 2 | 3 | 4 | # P5 ------------------------------------------------------------------------------------------------------------------- 5 | # P5-640: 6 | anchors_p5_640: 7 | - [ 10,13, 16,30, 33,23 ] # P3/8 8 | - [ 30,61, 62,45, 59,119 ] # P4/16 9 | - [ 116,90, 156,198, 373,326 ] # P5/32 10 | 11 | 12 | # P6 ------------------------------------------------------------------------------------------------------------------- 13 | # P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387 14 | anchors_p6_640: 15 | - [ 9,11, 21,19, 17,41 ] # P3/8 16 | - [ 43,32, 39,70, 86,64 ] # P4/16 17 | - [ 65,131, 134,130, 120,265 ] # P5/32 18 | - [ 282,180, 247,354, 512,387 ] # P6/64 19 | 20 | # P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792 21 | anchors_p6_1280: 22 | - [ 19,27, 44,40, 38,94 ] # P3/8 23 | - [ 96,68, 86,152, 180,137 ] # P4/16 24 | - [ 140,301, 303,264, 238,542 ] # P5/32 25 | - [ 436,615, 739,380, 925,792 ] # P6/64 26 | 27 | # P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187 28 | anchors_p6_1920: 29 | - [ 28,41, 67,59, 57,141 ] # P3/8 30 | - [ 144,103, 129,227, 270,205 ] # P4/16 31 | - [ 209,452, 455,396, 358,812 ] # P5/32 32 | - [ 653,922, 1109,570, 1387,1187 ] # P6/64 33 | 34 | 35 | # P7 ------------------------------------------------------------------------------------------------------------------- 36 | # P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372 37 | anchors_p7_640: 38 | - [ 11,11, 13,30, 29,20 ] # P3/8 39 | - [ 30,46, 61,38, 39,92 ] # P4/16 40 | - [ 78,80, 146,66, 79,163 ] # P5/32 41 | - [ 149,150, 321,143, 157,303 ] # P6/64 42 | - [ 257,402, 359,290, 524,372 ] # P7/128 43 | 44 | # P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818 45 | anchors_p7_1280: 46 | - [ 19,22, 54,36, 32,77 ] # P3/8 47 | - [ 70,83, 138,71, 75,173 ] # P4/16 48 | - [ 165,159, 148,334, 375,151 ] # P5/32 49 | - [ 334,317, 251,626, 499,474 ] # P6/64 50 | - [ 750,326, 534,814, 1079,818 ] # P7/128 51 | 52 | # P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227 53 | anchors_p7_1920: 54 | - [ 29,34, 81,55, 47,115 ] # P3/8 55 | - [ 105,124, 207,107, 113,259 ] # P4/16 56 | - [ 247,238, 222,500, 563,227 ] # P5/32 57 | - [ 501,476, 376,939, 749,711 ] # P6/64 58 | - [ 1126,489, 801,1222, 1618,1227 ] # P7/128 59 | -------------------------------------------------------------------------------- /models/hub/yolov3-spp.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # darknet53 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Conv, [32, 3, 1]], # 0 16 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 17 | [-1, 1, Bottleneck, [64]], 18 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 19 | [-1, 2, Bottleneck, [128]], 20 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 21 | [-1, 8, Bottleneck, [256]], 22 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 23 | [-1, 8, Bottleneck, [512]], 24 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 25 | [-1, 4, Bottleneck, [1024]], # 10 26 | ] 27 | 28 | # YOLOv3-SPP head 29 | head: 30 | [[-1, 1, Bottleneck, [1024, False]], 31 | [-1, 1, SPP, [512, [5, 9, 13]]], 32 | [-1, 1, Conv, [1024, 3, 1]], 33 | [-1, 1, Conv, [512, 1, 1]], 34 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) 35 | 36 | [-2, 1, Conv, [256, 1, 1]], 37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 38 | [[-1, 8], 1, Concat, [1]], # cat backbone P4 39 | [-1, 1, Bottleneck, [512, False]], 40 | [-1, 1, Bottleneck, [512, False]], 41 | [-1, 1, Conv, [256, 1, 1]], 42 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) 43 | 44 | [-2, 1, Conv, [128, 1, 1]], 45 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 46 | [[-1, 6], 1, Concat, [1]], # cat backbone P3 47 | [-1, 1, Bottleneck, [256, False]], 48 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) 49 | 50 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 51 | ] 52 | -------------------------------------------------------------------------------- /models/hub/yolov3-tiny.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [10,14, 23,27, 37,58] # P4/16 9 | - [81,82, 135,169, 344,319] # P5/32 10 | 11 | # YOLOv3-tiny backbone 12 | backbone: 13 | # [from, number, module, args] 14 | [[-1, 1, Conv, [16, 3, 1]], # 0 15 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2 16 | [-1, 1, Conv, [32, 3, 1]], 17 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4 18 | [-1, 1, Conv, [64, 3, 1]], 19 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8 20 | [-1, 1, Conv, [128, 3, 1]], 21 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16 22 | [-1, 1, Conv, [256, 3, 1]], 23 | [-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32 24 | [-1, 1, Conv, [512, 3, 1]], 25 | [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11 26 | [-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12 27 | ] 28 | 29 | # YOLOv3-tiny head 30 | head: 31 | [[-1, 1, Conv, [1024, 3, 1]], 32 | [-1, 1, Conv, [256, 1, 1]], 33 | [-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large) 34 | 35 | [-2, 1, Conv, [128, 1, 1]], 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 8], 1, Concat, [1]], # cat backbone P4 38 | [-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium) 39 | 40 | [[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5) 41 | ] 42 | -------------------------------------------------------------------------------- /models/hub/yolov3.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # darknet53 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Conv, [32, 3, 1]], # 0 16 | [-1, 1, Conv, [64, 3, 2]], # 1-P1/2 17 | [-1, 1, Bottleneck, [64]], 18 | [-1, 1, Conv, [128, 3, 2]], # 3-P2/4 19 | [-1, 2, Bottleneck, [128]], 20 | [-1, 1, Conv, [256, 3, 2]], # 5-P3/8 21 | [-1, 8, Bottleneck, [256]], 22 | [-1, 1, Conv, [512, 3, 2]], # 7-P4/16 23 | [-1, 8, Bottleneck, [512]], 24 | [-1, 1, Conv, [1024, 3, 2]], # 9-P5/32 25 | [-1, 4, Bottleneck, [1024]], # 10 26 | ] 27 | 28 | # YOLOv3 head 29 | head: 30 | [[-1, 1, Bottleneck, [1024, False]], 31 | [-1, 1, Conv, [512, [1, 1]]], 32 | [-1, 1, Conv, [1024, 3, 1]], 33 | [-1, 1, Conv, [512, 1, 1]], 34 | [-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large) 35 | 36 | [-2, 1, Conv, [256, 1, 1]], 37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 38 | [[-1, 8], 1, Concat, [1]], # cat backbone P4 39 | [-1, 1, Bottleneck, [512, False]], 40 | [-1, 1, Bottleneck, [512, False]], 41 | [-1, 1, Conv, [256, 1, 1]], 42 | [-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium) 43 | 44 | [-2, 1, Conv, [128, 1, 1]], 45 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 46 | [[-1, 6], 1, Concat, [1]], # cat backbone P3 47 | [-1, 1, Bottleneck, [256, False]], 48 | [-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small) 49 | 50 | [[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 51 | ] 52 | -------------------------------------------------------------------------------- /models/hub/yolov5-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 | ] -------------------------------------------------------------------------------- /models/hub/yolov5-fpn.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 17 | [-1, 3, Bottleneck, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 19 | [-1, 9, BottleneckCSP, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 21 | [-1, 9, BottleneckCSP, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 6, BottleneckCSP, [1024]], # 9 25 | ] 26 | 27 | # YOLOv5 FPN head 28 | head: 29 | [[-1, 3, BottleneckCSP, [1024, False]], # 10 (P5/32-large) 30 | 31 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 32 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 33 | [-1, 1, Conv, [512, 1, 1]], 34 | [-1, 3, BottleneckCSP, [512, False]], # 14 (P4/16-medium) 35 | 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 38 | [-1, 1, Conv, [256, 1, 1]], 39 | [-1, 3, BottleneckCSP, [256, False]], # 18 (P3/8-small) 40 | 41 | [[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 42 | ] 43 | -------------------------------------------------------------------------------- /models/hub/yolov5-p2.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 3 8 | 9 | # YOLOv5 backbone 10 | backbone: 11 | # [from, number, module, args] 12 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 13 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 14 | [ -1, 3, C3, [ 128 ] ], 15 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 16 | [ -1, 9, C3, [ 256 ] ], 17 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 18 | [ -1, 9, C3, [ 512 ] ], 19 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 7-P5/32 20 | [ -1, 1, SPP, [ 1024, [ 5, 9, 13 ] ] ], 21 | [ -1, 3, C3, [ 1024, False ] ], # 9 22 | ] 23 | 24 | # YOLOv5 head 25 | head: 26 | [ [ -1, 1, Conv, [ 512, 1, 1 ] ], 27 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 28 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 29 | [ -1, 3, C3, [ 512, False ] ], # 13 30 | 31 | [ -1, 1, Conv, [ 256, 1, 1 ] ], 32 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 33 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 34 | [ -1, 3, C3, [ 256, False ] ], # 17 (P3/8-small) 35 | 36 | [ -1, 1, Conv, [ 128, 1, 1 ] ], 37 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 38 | [ [ -1, 2 ], 1, Concat, [ 1 ] ], # cat backbone P2 39 | [ -1, 1, C3, [ 128, False ] ], # 21 (P2/4-xsmall) 40 | 41 | [ -1, 1, Conv, [ 128, 3, 2 ] ], 42 | [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P3 43 | [ -1, 3, C3, [ 256, False ] ], # 24 (P3/8-small) 44 | 45 | [ -1, 1, Conv, [ 256, 3, 2 ] ], 46 | [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P4 47 | [ -1, 3, C3, [ 512, False ] ], # 27 (P4/16-medium) 48 | 49 | [ -1, 1, Conv, [ 512, 3, 2 ] ], 50 | [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat head P5 51 | [ -1, 3, C3, [ 1024, False ] ], # 30 (P5/32-large) 52 | 53 | [ [ 24, 27, 30 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5) 54 | ] 55 | -------------------------------------------------------------------------------- /models/hub/yolov5-p6.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 3 8 | 9 | # YOLOv5 backbone 10 | backbone: 11 | # [from, number, module, args] 12 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 13 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 14 | [ -1, 3, C3, [ 128 ] ], 15 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 16 | [ -1, 9, C3, [ 256 ] ], 17 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 18 | [ -1, 9, C3, [ 512 ] ], 19 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 20 | [ -1, 3, C3, [ 768 ] ], 21 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 22 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], 23 | [ -1, 3, C3, [ 1024, False ] ], # 11 24 | ] 25 | 26 | # YOLOv5 head 27 | head: 28 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ], 29 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 30 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 31 | [ -1, 3, C3, [ 768, False ] ], # 15 32 | 33 | [ -1, 1, Conv, [ 512, 1, 1 ] ], 34 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 35 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 36 | [ -1, 3, C3, [ 512, False ] ], # 19 37 | 38 | [ -1, 1, Conv, [ 256, 1, 1 ] ], 39 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 40 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 41 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) 42 | 43 | [ -1, 1, Conv, [ 256, 3, 2 ] ], 44 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 45 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) 46 | 47 | [ -1, 1, Conv, [ 512, 3, 2 ] ], 48 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 49 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) 50 | 51 | [ -1, 1, Conv, [ 768, 3, 2 ] ], 52 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 53 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P5/64-xlarge) 54 | 55 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) 56 | ] 57 | -------------------------------------------------------------------------------- /models/hub/yolov5-p7.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 3 8 | 9 | # YOLOv5 backbone 10 | backbone: 11 | # [from, number, module, args] 12 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 13 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 14 | [ -1, 3, C3, [ 128 ] ], 15 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 16 | [ -1, 9, C3, [ 256 ] ], 17 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 18 | [ -1, 9, C3, [ 512 ] ], 19 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 20 | [ -1, 3, C3, [ 768 ] ], 21 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 22 | [ -1, 3, C3, [ 1024 ] ], 23 | [ -1, 1, Conv, [ 1280, 3, 2 ] ], # 11-P7/128 24 | [ -1, 1, SPP, [ 1280, [ 3, 5 ] ] ], 25 | [ -1, 3, C3, [ 1280, False ] ], # 13 26 | ] 27 | 28 | # YOLOv5 head 29 | head: 30 | [ [ -1, 1, Conv, [ 1024, 1, 1 ] ], 31 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 32 | [ [ -1, 10 ], 1, Concat, [ 1 ] ], # cat backbone P6 33 | [ -1, 3, C3, [ 1024, False ] ], # 17 34 | 35 | [ -1, 1, Conv, [ 768, 1, 1 ] ], 36 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 37 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 38 | [ -1, 3, C3, [ 768, False ] ], # 21 39 | 40 | [ -1, 1, Conv, [ 512, 1, 1 ] ], 41 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 42 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 43 | [ -1, 3, C3, [ 512, False ] ], # 25 44 | 45 | [ -1, 1, Conv, [ 256, 1, 1 ] ], 46 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 47 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 48 | [ -1, 3, C3, [ 256, False ] ], # 29 (P3/8-small) 49 | 50 | [ -1, 1, Conv, [ 256, 3, 2 ] ], 51 | [ [ -1, 26 ], 1, Concat, [ 1 ] ], # cat head P4 52 | [ -1, 3, C3, [ 512, False ] ], # 32 (P4/16-medium) 53 | 54 | [ -1, 1, Conv, [ 512, 3, 2 ] ], 55 | [ [ -1, 22 ], 1, Concat, [ 1 ] ], # cat head P5 56 | [ -1, 3, C3, [ 768, False ] ], # 35 (P5/32-large) 57 | 58 | [ -1, 1, Conv, [ 768, 3, 2 ] ], 59 | [ [ -1, 18 ], 1, Concat, [ 1 ] ], # cat head P6 60 | [ -1, 3, C3, [ 1024, False ] ], # 38 (P6/64-xlarge) 61 | 62 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], 63 | [ [ -1, 14 ], 1, Concat, [ 1 ] ], # cat head P7 64 | [ -1, 3, C3, [ 1280, False ] ], # 41 (P7/128-xxlarge) 65 | 66 | [ [ 29, 32, 35, 38, 41 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6, P7) 67 | ] 68 | -------------------------------------------------------------------------------- /models/hub/yolov5-panet.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 17 | [-1, 3, BottleneckCSP, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 19 | [-1, 9, BottleneckCSP, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 21 | [-1, 9, BottleneckCSP, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 3, BottleneckCSP, [1024, False]], # 9 25 | ] 26 | 27 | # YOLOv5 PANet head 28 | head: 29 | [[-1, 1, Conv, [512, 1, 1]], 30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 32 | [-1, 3, BottleneckCSP, [512, False]], # 13 33 | 34 | [-1, 1, Conv, [256, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 37 | [-1, 3, BottleneckCSP, [256, False]], # 17 (P3/8-small) 38 | 39 | [-1, 1, Conv, [256, 3, 2]], 40 | [[-1, 14], 1, Concat, [1]], # cat head P4 41 | [-1, 3, BottleneckCSP, [512, False]], # 20 (P4/16-medium) 42 | 43 | [-1, 1, Conv, [512, 3, 2]], 44 | [[-1, 10], 1, Concat, [1]], # cat head P5 45 | [-1, 3, BottleneckCSP, [1024, False]], # 23 (P5/32-large) 46 | 47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 48 | ] 49 | -------------------------------------------------------------------------------- /models/hub/yolov5l6.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [ 19,27, 44,40, 38,94 ] # P3/8 9 | - [ 96,68, 86,152, 180,137 ] # P4/16 10 | - [ 140,301, 303,264, 238,542 ] # P5/32 11 | - [ 436,615, 739,380, 925,792 ] # P6/64 12 | 13 | # YOLOv5 backbone 14 | backbone: 15 | # [from, number, module, args] 16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 18 | [ -1, 3, C3, [ 128 ] ], 19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 20 | [ -1, 9, C3, [ 256 ] ], 21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 22 | [ -1, 9, C3, [ 512 ] ], 23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 24 | [ -1, 3, C3, [ 768 ] ], 25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], 27 | [ -1, 3, C3, [ 1024, False ] ], # 11 28 | ] 29 | 30 | # YOLOv5 head 31 | head: 32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ], 33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 35 | [ -1, 3, C3, [ 768, False ] ], # 15 36 | 37 | [ -1, 1, Conv, [ 512, 1, 1 ] ], 38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 40 | [ -1, 3, C3, [ 512, False ] ], # 19 41 | 42 | [ -1, 1, Conv, [ 256, 1, 1 ] ], 43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) 46 | 47 | [ -1, 1, Conv, [ 256, 3, 2 ] ], 48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) 50 | 51 | [ -1, 1, Conv, [ 512, 3, 2 ] ], 52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) 54 | 55 | [ -1, 1, Conv, [ 768, 3, 2 ] ], 56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) 58 | 59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) 60 | ] 61 | -------------------------------------------------------------------------------- /models/hub/yolov5m6.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 0.67 # model depth multiple 4 | width_multiple: 0.75 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [ 19,27, 44,40, 38,94 ] # P3/8 9 | - [ 96,68, 86,152, 180,137 ] # P4/16 10 | - [ 140,301, 303,264, 238,542 ] # P5/32 11 | - [ 436,615, 739,380, 925,792 ] # P6/64 12 | 13 | # YOLOv5 backbone 14 | backbone: 15 | # [from, number, module, args] 16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 18 | [ -1, 3, C3, [ 128 ] ], 19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 20 | [ -1, 9, C3, [ 256 ] ], 21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 22 | [ -1, 9, C3, [ 512 ] ], 23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 24 | [ -1, 3, C3, [ 768 ] ], 25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], 27 | [ -1, 3, C3, [ 1024, False ] ], # 11 28 | ] 29 | 30 | # YOLOv5 head 31 | head: 32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ], 33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 35 | [ -1, 3, C3, [ 768, False ] ], # 15 36 | 37 | [ -1, 1, Conv, [ 512, 1, 1 ] ], 38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 40 | [ -1, 3, C3, [ 512, False ] ], # 19 41 | 42 | [ -1, 1, Conv, [ 256, 1, 1 ] ], 43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) 46 | 47 | [ -1, 1, Conv, [ 256, 3, 2 ] ], 48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) 50 | 51 | [ -1, 1, Conv, [ 512, 3, 2 ] ], 52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) 54 | 55 | [ -1, 1, Conv, [ 768, 3, 2 ] ], 56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) 58 | 59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) 60 | ] 61 | -------------------------------------------------------------------------------- /models/hub/yolov5s-cbam.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 0.33 # model depth multiple 4 | width_multiple: 0.50 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | #- [5,6, 7,9, 12,10] # P2/4 9 | - [10,13, 16,30, 33,23] # P3/8 10 | - [30,61, 62,45, 59,119] # P4/16 11 | - [116,90, 156,198, 373,326] # P5/32 12 | 13 | # YOLOv5 backbone 14 | backbone: 15 | # [from, number, module, args] # [c=channels,module,kernlsize,strides]- 1代表来自上一层输出 16 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 [c=3,64*0.5=32,3] 举例,输出通道数*width_multiple:=64*0.5 17 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 18 | [-1, 3, C3, [128]], 19 | [-1, 3, CBAM, [128]], # 举例,3*width_multiple:=3*0.33=1 20 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 21 | [-1, 9, C3, [256]], 22 | [-1, 3, CBAM, [256]] , 23 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 24 | [-1, 9, C3, [512]], 25 | [-1, 3, CBAM, [512]], 26 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 27 | [-1, 1, SPP, [1024, [5, 9, 13]]], 28 | [-1, 3, C3, [1024, False]], # 9 29 | [-1, 3, CBAM, [1024]], #13 30 | 31 | ] 32 | 33 | # YOLOv5 head 34 | head: 35 | [[-1, 1, Conv, [512, 1, 1]], 36 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 37 | [[-1, 7], 1, Concat, [1]], # cat backbone P4 38 | [-1, 3, C3, [512, False]], # 13 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]], # 19 (P3/8-small) 44 | [-1, 3, CBAM, [256]], 45 | #[-1, 3, C3, [256]], 46 | 47 | [-1, 1, Conv, [256, 3, 2]], 48 | [[-1, 18], 1, Concat, [1]], # cat head P4 49 | [-1, 3, C3, [512, False]], # 23 (P4/16-medium) [256, 256, 1, False] 50 | [-1, 3, CBAM, [512]], 51 | #[-1, 3, C3, [512]], 52 | 53 | [-1, 1, Conv, [512, 3, 2]], #[256, 256, 3, 2] 54 | [[-1, 14], 1, Concat, [1]], # cat head P5 55 | [-1, 3, C3, [1024, False]], # 27 (P5/32-large) [512, 512, 1, False] 56 | [-1, 3, CBAM, [1024]], 57 | #[-1, 3, C3, [1024]], 58 | 59 | [[22, 26, 30], 1, ASFF_Detect, [nc, anchors,0.5,True]], # ASFF_Detect(P3, P4, P5,mult,rfb) 60 | ] 61 | 62 | -------------------------------------------------------------------------------- /models/hub/yolov5s-ghost.yaml: -------------------------------------------------------------------------------- 1 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license 2 | 3 | # Parameters 4 | nc: 80 # number of classes 5 | depth_multiple: 0.33 # model depth multiple 6 | width_multiple: 0.50 # layer channel multiple 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 16 | [-1, 1, GhostConv, [128, 3, 2]], # 1-P2/4 17 | [-1, 3, C3Ghost, [128]], 18 | [-1, 1, GhostConv, [256, 3, 2]], # 3-P3/8 19 | [-1, 9, C3Ghost, [256]], 20 | [-1, 1, GhostConv, [512, 3, 2]], # 5-P4/16 21 | [-1, 9, C3Ghost, [512]], 22 | [-1, 1, GhostConv, [1024, 3, 2]], # 7-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 3, C3Ghost, [1024, False]], # 9 25 | ] 26 | 27 | # YOLOv5 head 28 | head: 29 | [[-1, 1, GhostConv, [512, 1, 1]], 30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 32 | [-1, 3, C3Ghost, [512, False]], # 13 33 | 34 | [-1, 1, GhostConv, [256, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 37 | [-1, 3, C3Ghost, [256, False]], # 17 (P3/8-small) 38 | 39 | [-1, 1, GhostConv, [256, 3, 2]], 40 | [[-1, 14], 1, Concat, [1]], # cat head P4 41 | [-1, 3, C3Ghost, [512, False]], # 20 (P4/16-medium) 42 | 43 | [-1, 1, GhostConv, [512, 3, 2]], 44 | [[-1, 10], 1, Concat, [1]], # cat head P5 45 | [-1, 3, C3Ghost, [1024, False]], # 23 (P5/32-large) 46 | 47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 48 | ] -------------------------------------------------------------------------------- /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 | 6 | # anchors 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 17 | [-1, 3, C3, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 19 | [-1, 9, C3, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 21 | [-1, 9, C3, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 3, C3TR, [1024, False]], # 9 <-------- C3TR() Transformer module 25 | ] 26 | 27 | # YOLOv5 head 28 | head: 29 | [[-1, 1, Conv, [512, 1, 1]], 30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 32 | [-1, 3, C3, [512, False]], # 13 33 | 34 | [-1, 1, Conv, [256, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 38 | 39 | [-1, 1, Conv, [256, 3, 2]], 40 | [[-1, 14], 1, Concat, [1]], # cat head P4 41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 42 | 43 | [-1, 1, Conv, [512, 3, 2]], 44 | [[-1, 10], 1, Concat, [1]], # cat head P5 45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 46 | 47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 48 | ] 49 | -------------------------------------------------------------------------------- /models/hub/yolov5s6.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 0.33 # model depth multiple 4 | width_multiple: 0.50 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [ 19,27, 44,40, 38,94 ] # P3/8 9 | - [ 96,68, 86,152, 180,137 ] # P4/16 10 | - [ 140,301, 303,264, 238,542 ] # P5/32 11 | - [ 436,615, 739,380, 925,792 ] # P6/64 12 | 13 | # YOLOv5 backbone 14 | backbone: 15 | # [from, number, module, args] 16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 18 | [ -1, 3, C3, [ 128 ] ], 19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 20 | [ -1, 9, C3, [ 256 ] ], 21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 22 | [ -1, 9, C3, [ 512 ] ], 23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 24 | [ -1, 3, C3, [ 768 ] ], 25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], 27 | [ -1, 3, C3, [ 1024, False ] ], # 11 28 | ] 29 | 30 | # YOLOv5 head 31 | head: 32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ], 33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 35 | [ -1, 3, C3, [ 768, False ] ], # 15 36 | 37 | [ -1, 1, Conv, [ 512, 1, 1 ] ], 38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 40 | [ -1, 3, C3, [ 512, False ] ], # 19 41 | 42 | [ -1, 1, Conv, [ 256, 1, 1 ] ], 43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) 46 | 47 | [ -1, 1, Conv, [ 256, 3, 2 ] ], 48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) 50 | 51 | [ -1, 1, Conv, [ 512, 3, 2 ] ], 52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) 54 | 55 | [ -1, 1, Conv, [ 768, 3, 2 ] ], 56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) 58 | 59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) 60 | ] 61 | -------------------------------------------------------------------------------- /models/hub/yolov5x6.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.33 # model depth multiple 4 | width_multiple: 1.25 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [ 19,27, 44,40, 38,94 ] # P3/8 9 | - [ 96,68, 86,152, 180,137 ] # P4/16 10 | - [ 140,301, 303,264, 238,542 ] # P5/32 11 | - [ 436,615, 739,380, 925,792 ] # P6/64 12 | 13 | # YOLOv5 backbone 14 | backbone: 15 | # [from, number, module, args] 16 | [ [ -1, 1, Focus, [ 64, 3 ] ], # 0-P1/2 17 | [ -1, 1, Conv, [ 128, 3, 2 ] ], # 1-P2/4 18 | [ -1, 3, C3, [ 128 ] ], 19 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 3-P3/8 20 | [ -1, 9, C3, [ 256 ] ], 21 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 5-P4/16 22 | [ -1, 9, C3, [ 512 ] ], 23 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 7-P5/32 24 | [ -1, 3, C3, [ 768 ] ], 25 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 9-P6/64 26 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], 27 | [ -1, 3, C3, [ 1024, False ] ], # 11 28 | ] 29 | 30 | # YOLOv5 head 31 | head: 32 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ], 33 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 34 | [ [ -1, 8 ], 1, Concat, [ 1 ] ], # cat backbone P5 35 | [ -1, 3, C3, [ 768, False ] ], # 15 36 | 37 | [ -1, 1, Conv, [ 512, 1, 1 ] ], 38 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 39 | [ [ -1, 6 ], 1, Concat, [ 1 ] ], # cat backbone P4 40 | [ -1, 3, C3, [ 512, False ] ], # 19 41 | 42 | [ -1, 1, Conv, [ 256, 1, 1 ] ], 43 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 44 | [ [ -1, 4 ], 1, Concat, [ 1 ] ], # cat backbone P3 45 | [ -1, 3, C3, [ 256, False ] ], # 23 (P3/8-small) 46 | 47 | [ -1, 1, Conv, [ 256, 3, 2 ] ], 48 | [ [ -1, 20 ], 1, Concat, [ 1 ] ], # cat head P4 49 | [ -1, 3, C3, [ 512, False ] ], # 26 (P4/16-medium) 50 | 51 | [ -1, 1, Conv, [ 512, 3, 2 ] ], 52 | [ [ -1, 16 ], 1, Concat, [ 1 ] ], # cat head P5 53 | [ -1, 3, C3, [ 768, False ] ], # 29 (P5/32-large) 54 | 55 | [ -1, 1, Conv, [ 768, 3, 2 ] ], 56 | [ [ -1, 12 ], 1, Concat, [ 1 ] ], # cat head P6 57 | [ -1, 3, C3, [ 1024, False ] ], # 32 (P6/64-xlarge) 58 | 59 | [ [ 23, 26, 29, 32 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) 60 | ] 61 | -------------------------------------------------------------------------------- /models/hub/yolov5x_se.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 15 # number of classes 3 | depth_multiple: 1 # model depth multiple 4 | width_multiple: 1 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [10, 13, 16, 30, 33, 23] # P3/8 9 | - [30, 61, 62, 45, 59, 119] # P4/16 10 | - [116, 90, 156, 198, 373, 326] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [ 16 | [-1, 1, Focus, [64, 3]], # 0-P1/2 #1 17 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 #2 18 | [-1, 3, C3, [128]], #3 19 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 #4 20 | [-1, 9, C3, [256]], #5 21 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 #6 22 | [-1, 9, C3, [512]], #7 23 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 #8 24 | [-1, 1, SPP, [1024, [5, 9, 13]]], #9 25 | [-1, 3, C3, [1024, False]], # 9 #10 26 | [-1, 1, SELayer, [1024, 4]], #10 27 | ] 28 | 29 | 30 | 31 | # YOLOv5 head 32 | head: [ 33 | [-1, 1, Conv, [512, 1, 1]], #11 /32 34 | [-1, 1, nn.Upsample, [None, 2, "nearest"]], #12 /16 35 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 /16 #13 36 | [-1, 3, C3, [512, False]], # 13 / 16 #14 37 | 38 | [-1, 1, Conv, [256, 1, 1]], #15 /16 39 | [-1, 1, nn.Upsample, [None, 2, "nearest"]], #16 /8 40 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 /8 #17 41 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) /8 #18 42 | 43 | [-1, 1, Conv, [256, 3, 2]], #19 /16 44 | [[-1, 6], 1, Concat, [1]], # cat head P4 #20 45 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) #21 46 | 47 | [-1, 1, Conv, [512, 3, 2]], #22 /32 48 | [[-1, 8], 1, Concat, [1]], # cat head P5 #23 49 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) #24 50 | 51 | [[18, 21, 24], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 52 | ] 53 | -------------------------------------------------------------------------------- /models/yolov5l.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 17 | [-1, 3, C3, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 19 | [-1, 9, C3, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 21 | [-1, 9, C3, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 3, C3, [1024, False]], # 9 25 | ] 26 | 27 | # YOLOv5 head 28 | head: 29 | [[-1, 1, Conv, [512, 1, 1]], 30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 32 | [-1, 3, C3, [512, False]], # 13 33 | 34 | [-1, 1, Conv, [256, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 38 | 39 | [-1, 1, Conv, [256, 3, 2]], 40 | [[-1, 14], 1, Concat, [1]], # cat head P4 41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 42 | 43 | [-1, 1, Conv, [512, 3, 2]], 44 | [[-1, 10], 1, Concat, [1]], # cat head P5 45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 46 | 47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 48 | ] 49 | -------------------------------------------------------------------------------- /models/yolov5m.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 80 # number of classes 3 | depth_multiple: 0.67 # model depth multiple 4 | width_multiple: 0.75 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 17 | [-1, 3, C3, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 19 | [-1, 9, C3, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 21 | [-1, 9, C3, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 3, C3, [1024, False]], # 9 25 | ] 26 | 27 | # YOLOv5 head 28 | head: 29 | [[-1, 1, Conv, [512, 1, 1]], 30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 32 | [-1, 3, C3, [512, False]], # 13 33 | 34 | [-1, 1, Conv, [256, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 38 | 39 | [-1, 1, Conv, [256, 3, 2]], 40 | [[-1, 14], 1, Concat, [1]], # cat head P4 41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 42 | 43 | [-1, 1, Conv, [512, 3, 2]], 44 | [[-1, 10], 1, Concat, [1]], # cat head P5 45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 46 | 47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 48 | ] 49 | -------------------------------------------------------------------------------- /models/yolov5s.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 20 # number of classes 3 | depth_multiple: 0.33 # model depth multiple 控制模型的深度(BottleneckCSP个数) 4 | width_multiple: 0.50 # layer channel multiple 控制Conv通道channel个数(卷积核数量) 5 | # depth_multiple表示BottleneckCSP模块的缩放因子,将所有BottleneckCSP模块的Bottleneck乘上该参数得到最终个数。 6 | # width_multiple表示卷积通道的缩放因子,就是将配置里面的backbone和head部分有关Conv通道的设置,全部乘以该系数。 7 | # 通过这两个参数就可以实现不同复杂度的模型设计。 8 | 9 | # anchors 10 | anchors: 11 | - [10,13, 16,30, 33,23] # P3/8 wh stride=8 12 | - [30,61, 62,45, 59,119] # P4/16 13 | - [116,90, 156,198, 373,326] # P5/32 14 | 15 | # YOLOv5 backbone 16 | backbone: 17 | # [from, number, module, args] 18 | # from表示当前模块的输入来自那一层的输出,-1表示来自上一层的输出 19 | # number表示本模块重复的次数,1表示只有一个,3表示重复3次 20 | # module: 模块名 [模块输入channel, 模块输出channel, 模块其他参数] 21 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 [3, 32, 3] 22 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 [32, 64, 3, 2] 23 | [-1, 3, C3, [128]], # 2 [64, 64, 1] 24 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 [64, 128, 3, 2] 25 | [-1, 9, C3, [256]], # 4 [128, 128, 3] 26 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 [128, 256, 3, 2] 27 | [-1, 9, C3, [512]], # 6 [256, 256, 3] 28 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 [256, 512, 3, 2] 29 | [-1, 1, SPP, [1024, [5, 9, 13]]], # 8 [512, 512, [5, 9, 13]] 30 | [-1, 3, C3, [1024, False]], # 9 [512, 512, 1, False] 31 | ] 32 | 33 | 34 | # YOLOv5 head 作者没有区分neck模块,所以head部分包含了PANet+Detect部分 35 | head: 36 | [[-1, 1, Conv, [512, 1, 1]], # 10 [512, 256, 1, 1] 37 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], # 11 [None, 2, 'nearest'] 38 | [[-1, 6], 1, Concat, [1]], # 12 cat backbone P4 [1] 39 | [-1, 3, C3, [512, False]], # 13 [512, 256, 1, False] 40 | 41 | [-1, 1, Conv, [256, 1, 1]], # 14 [256, 128, 1, 1] 42 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], #15 [None, 2, 'nearest'] 43 | [[-1, 4], 1, Concat, [1]], # 16 cat backbone P3 [1] 44 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) [256, 128, 1, False] 45 | 46 | [-1, 1, Conv, [256, 3, 2]], # 18 [128, 128, 3, 2] 47 | [[-1, 14], 1, Concat, [1]], # 19 cat head P4 [1] 48 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) [256, 256, 1, False] 49 | 50 | [-1, 1, Conv, [512, 3, 2]], # 21 [256, 256, 3, 2] 51 | [[-1, 10], 1, Concat, [1]], # 22 cat head P5 [1] 52 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) [512, 512, 1, False] 53 | 54 | 55 | [[17, 20, 23], 1, Detect, [nc, anchors]], # 24 Detect(P3, P4, P5) 56 | # [nc, anchors, 3个Detect的输出channel] 57 | # [1, [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]], [128, 256, 512]] 58 | ] 59 | -------------------------------------------------------------------------------- /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 | 6 | # anchors 7 | anchors: 8 | - [10,13, 16,30, 33,23] # P3/8 9 | - [30,61, 62,45, 59,119] # P4/16 10 | - [116,90, 156,198, 373,326] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, Focus, [64, 3]], # 0-P1/2 16 | [-1, 1, Conv, [128, 3, 2]], # 1-P2/4 17 | [-1, 3, C3, [128]], 18 | [-1, 1, Conv, [256, 3, 2]], # 3-P3/8 19 | [-1, 9, C3, [256]], 20 | [-1, 1, Conv, [512, 3, 2]], # 5-P4/16 21 | [-1, 9, C3, [512]], 22 | [-1, 1, Conv, [1024, 3, 2]], # 7-P5/32 23 | [-1, 1, SPP, [1024, [5, 9, 13]]], 24 | [-1, 3, C3, [1024, False]], # 9 25 | ] 26 | 27 | # YOLOv5 head 28 | head: 29 | [[-1, 1, Conv, [512, 1, 1]], 30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 31 | [[-1, 6], 1, Concat, [1]], # cat backbone P4 32 | [-1, 3, C3, [512, False]], # 13 33 | 34 | [-1, 1, Conv, [256, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 4], 1, Concat, [1]], # cat backbone P3 37 | [-1, 3, C3, [256, False]], # 17 (P3/8-small) 38 | 39 | [-1, 1, Conv, [256, 3, 2]], 40 | [[-1, 14], 1, Concat, [1]], # cat head P4 41 | [-1, 3, C3, [512, False]], # 20 (P4/16-medium) 42 | 43 | [-1, 1, Conv, [512, 3, 2]], 44 | [[-1, 10], 1, Concat, [1]], # cat head P5 45 | [-1, 3, C3, [1024, False]], # 23 (P5/32-large) 46 | 47 | [[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 48 | ] 49 | -------------------------------------------------------------------------------- /others/Bottleneck.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/Bottleneck.png -------------------------------------------------------------------------------- /others/BottleneckCSP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/BottleneckCSP.png -------------------------------------------------------------------------------- /others/C3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/C3.png -------------------------------------------------------------------------------- /others/CA.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/CA.png -------------------------------------------------------------------------------- /others/CAM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/CAM.png -------------------------------------------------------------------------------- /others/CBAM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/CBAM.png -------------------------------------------------------------------------------- /others/Conv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/Conv.png -------------------------------------------------------------------------------- /others/Focus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/Focus.png -------------------------------------------------------------------------------- /others/SAM.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/SAM.png -------------------------------------------------------------------------------- /others/SE.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/SE.png -------------------------------------------------------------------------------- /others/SPP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/SPP.png -------------------------------------------------------------------------------- /others/Transformer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/Transformer.png -------------------------------------------------------------------------------- /others/formula.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/formula.png -------------------------------------------------------------------------------- /others/yolov5s.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuKai97/yolov5-5.x-annotations/fe915323d9ebf957d224066f688e11c1219fe089/others/yolov5s.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # pip install -r requirements.txt 2 | 3 | # base ---------------------------------------- 4 | matplotlib>=3.2.2 5 | numpy>=1.18.5 6 | opencv-python>=4.1.2 7 | Pillow 8 | PyYAML>=5.3.1 9 | scipy>=1.4.1 10 | torch>=1.7.0 11 | torchvision>=0.8.0 12 | tqdm>=4.41.0 13 | 14 | # logging ------------------------------------- 15 | tensorboard>=2.4.1 16 | # wandb 17 | 18 | # plotting ------------------------------------ 19 | seaborn>=0.11.0 20 | pandas 21 | 22 | # export -------------------------------------- 23 | # coremltools>=4.1 24 | # onnx>=1.8.1 25 | # scikit-learn==0.19.2 # for coreml quantization 26 | 27 | # extras -------------------------------------- 28 | thop # FLOPS computation 29 | pycocotools-windows>=2.0 # COCO mAP 30 | -------------------------------------------------------------------------------- /runs/这里存放训练、验证结果.txt: -------------------------------------------------------------------------------- 1 | 这里存放训练、验证结果 -------------------------------------------------------------------------------- /utils/autoanchor.py: -------------------------------------------------------------------------------- 1 | # Auto-anchor utils 2 | 3 | import numpy as np # numpy矩阵操作模块 4 | import matplotlib.pyplot as plt # matplotlib画图模块 5 | import torch # PyTorch深度学习模块 6 | import yaml # 操作yaml文件模块 7 | from tqdm import tqdm # Python进度条模块 8 | 9 | from utils.general import colorstr 10 | from utils.metrics import wh_iou 11 | 12 | 13 | def check_anchor_order(m): 14 | """用在check_anchors最后 确定anchors和stride的顺序是一致的 15 | Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary 16 | :params m: model中的最后一层 Detect层 17 | """ 18 | # 计算anchor的面积 anchor area [9] 19 | # tensor([134.4, 576.3, 1302.2, 5027.15, 12354.6, 25296.5e, 77122.3, 161472, 245507]) 20 | a = m.anchor_grid.prod(-1).view(-1) 21 | # 计算最大anchor与最小anchor面积差 22 | da = a[-1] - a[0] # delta a tensor(245372.65625) 23 | # 计算最大stride与最小stride差 24 | ds = m.stride[-1] - m.stride[0] # delta s tensor(24.) 25 | # torch.sign(x):当x大于/小于0时,返回1/-1 26 | # 如果这里anchor与stride顺序不一致,则重新调整顺序 27 | if da.sign() != ds.sign(): # same order 28 | print('Reversing anchor order') 29 | m.anchors[:] = m.anchors.flip(0) 30 | m.anchor_grid[:] = m.anchor_grid.flip(0) 31 | 32 | def check_anchors(dataset, model, thr=4.0, imgsz=640): 33 | """用于train.py中 34 | 通过bpr确定是否需要改变anchors 需要就调用k-means重新计算anchors 35 | Check anchor fit to data, recompute if necessary 36 | :params dataset: 自定义数据集LoadImagesAndLabels返回的数据集 37 | :params model: 初始化的模型 38 | :params thr: 超参中得到 界定anchor与label匹配程度的阈值 39 | :params imgsz: 图片尺寸 默认640 40 | """ 41 | # 一些可视化: autoanchor: Analyzing anchors... 42 | prefix = colorstr('autoanchor: ') 43 | print(f'\n{prefix}Origin anchors... ') 44 | 45 | # m: 从model中取出最后一层(Detect) 46 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() 47 | # dataset.shapes.max(1, keepdims=True) = 每张图片的较长边 48 | # shapes: 将数据集图片的最长边缩放到img_size, 较小边相应缩放 得到新的所有数据集图片的宽高 [N, 2] 49 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) 50 | # 产生随机数scale [2501, 1] 51 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale 52 | # [6301, 2] 所有target(6301个)的wh 基于原图大小 shapes * scale: 随机化尺度变化 53 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh 54 | 55 | def metric(k): 56 | """用在check_anchors函数中 compute metric 57 | 根据数据集的所有图片的wh和当前所有anchors k计算 bpr(best possible recall) 和 aat(anchors above threshold) 58 | :params k: anchors [9, 2] wh: [N, 2] 59 | :return bpr: best possible recall 最多能被召回(通过thr)的gt框数量 / 所有gt框数量 小于0.98 才会用k-means计算anchor 60 | :return aat: anchors above threshold 每个target平均有多少个anchors 61 | """ 62 | # None添加维度 所有target(gt)的wh wh[:, None] [6301, 2]->[6301, 1, 2] 63 | # 所有anchor的wh k[None] [9, 2]->[1, 9, 2] 64 | # r: target的高h宽w与anchor的高h_a宽w_a的比值,即h/h_a, w/w_a [6301, 9, 2] 有可能大于1,也可能小于等于1 65 | r = wh[:, None] / k[None] 66 | # x 高宽比和宽高比的最小值 无论r大于1,还是小于等于1最后统一结果都要小于1 [6301, 9] 67 | x = torch.min(r, 1. / r).min(2)[0] 68 | # best [6301] 为每个gt框选择匹配所有anchors宽高比例值最好的那一个比值 69 | best = x.max(1)[0] 70 | # aat(anchors above threshold) 每个target平均有多少个anchors 71 | aat = (x > 1. / thr).float().sum(1).mean() # 当axis=1时,求的是每一行元素的和 72 | # bpr(best possible recall) = 最多能被召回(通过thr)的gt框数量 / 所有gt框数量 小于0.98 才会用k-means计算anchor 73 | bpr = (best > 1. / thr).float().mean() 74 | fitness = (best * (best > 1. / thr).float()).mean() 75 | return bpr, aat, fitness 76 | 77 | # anchors: [N,2] 所有anchors的宽高 基于缩放后的图片大小(较长边为640 较小边相应缩放) 78 | anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors 79 | # 计算出数据集所有图片的wh和当前所有anchors的bpr和aat 80 | # bpr: bpr(best possible recall): 最多能被召回(通过thr)的gt框数量 / 所有gt框数量 [1] 0.96223 小于0.98 才会用k-means计算anchor 81 | # aat(anchors past thr): [1] 3.54360 通过阈值的anchor个数 82 | bpr, aat, fitness = metric(anchors) 83 | print(f"aat: {aat:.5f}, fitness: {fitness:.5f}, best possible recall: {bpr:.5f}") 84 | print(" ".join([f"[{int(i[0])}, {int(i[1])}]" for i in anchors])) 85 | # threshold to recompute 86 | # 考虑这9类anchor的宽高和gt框的宽高之间的差距, 如果bpr<0.98(说明当前anchor不能很好的匹配数据集gt框)就会根据k-means算法重新聚类新的anchor 87 | if bpr < 0.98: 88 | print('. Attempting to improve anchors, please wait...') 89 | na = m.anchor_grid.numel() // 2 # number of anchors 90 | try: 91 | # 如果bpr<0.98(最大为1 越大越好) 使用k-means + 遗传进化算法选择出与数据集更匹配的anchors框 [9, 2] 92 | anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) 93 | except Exception as e: 94 | print(f'{prefix}ERROR: {e}') 95 | # 计算新的anchors的new_bpr 96 | new_bpr = metric(anchors)[0] 97 | # 比较k-means + 遗传进化算法进化后的anchors的new_bpr和原始anchors的bpr 98 | # 注意: 这里并不一定进化后的bpr必大于原始anchors的bpr, 因为两者的衡量标注是不一样的 进化算法的衡量标准是适应度 而这里比的是bpr 99 | if new_bpr > bpr: # replace anchors 100 | anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors) 101 | # 替换m的anchor_grid [9, 2] -> [3, 1, 3, 1, 1, 2] 102 | m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference 103 | # 替换m的anchors(相对各个feature map) [9, 2] -> [3, 3, 2] 104 | m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss 105 | # 检查anchor顺序和stride顺序是否一致 不一致就调整 106 | # 因为我们的m.anchors是相对各个feature map 所以必须要顺序一致 否则效果会很不好 107 | check_anchor_order(m) 108 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.') 109 | else: 110 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.') 111 | print('') # newline 112 | 113 | def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): 114 | """在check_anchors中调用 115 | 使用K-means + 遗传算法 算出更符合当前数据集的anchors 116 | Creates kmeans-evolved anchors from training dataset 117 | :params path: 数据集的路径/数据集本身 118 | :params n: anchor框的个数 119 | :params img_size: 数据集图片约定的大小 120 | :params thr: 阈值 由hyp['anchor_t']参数控制 121 | :params gen: 遗传算法进化迭代的次数(突变 + 选择) 122 | :params verbose: 是否打印所有的进化(成功的)结果 默认传入是Fasle的 只打印最佳的进化结果即可 123 | :return k: k-means + 遗传算法进化 后的anchors 124 | """ 125 | from scipy.cluster.vq import kmeans 126 | 127 | 128 | # 注意一下下面的thr不是传入的thr,而是1/thr, 所以在计算指标这方面还是和check_anchor一样 129 | thr = 1. / thr # 0.25 130 | prefix = colorstr('autoanchor: ') 131 | 132 | def metric(k, wh): # compute metrics 133 | """用于print_results函数和anchor_fitness函数 134 | 计算ratio metric: 整个数据集的gt框与anchor对应宽比和高比即:gt_w/k_w,gt_h/k_h + x + best_x 用于后续计算bpr+aat 135 | 注意我们这里选择的metric是gt框与anchor对应宽比和高比 而不是常用的iou 这点也与nms的筛选条件对应 是yolov5中使用的新方法 136 | :params k: anchor框 137 | :params wh: 整个数据集的wh [N, 2] 138 | :return x: [N, 9] N个gt框与所有anchor框的宽比或高比(两者之中较小者) 139 | :return x.max(1)[0]: [N] N个gt框与所有anchor框中的最大宽比或高比(两者之中较小者) 140 | """ 141 | # [N, 1, 2] / [1, 9, 2] = [N, 9, 2] N个gt_wh和9个anchor的k_wh宽比和高比 142 | # 两者的重合程度越高 就越趋近于1 远离1(<1 或 >1)重合程度都越低 143 | r = wh[:, None] / k[None] 144 | # r=gt_height/anchor_height gt_width / anchor_width 有可能大于1,也可能小于等于1 145 | # torch.min(r, 1. / r): [N, 9, 2] 将所有的宽比和高比统一到<=1 146 | # .min(2): value=[N, 9] 选出每个gt个和anchor的宽比和高比最小的值 index: [N, 9] 这个最小值是宽比(0)还是高比(1) 147 | # [0] 返回value [N, 9] 每个gt个和anchor的宽比和高比最小的值 就是所有gt与anchor重合程度最低的 148 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric 149 | # x = wh_iou(wh, torch.tensor(k)) # iou metric 150 | # x.max(1)[0]: [N] 返回每个gt和所有anchor(9个)中宽比/高比最大的值 151 | return x, x.max(1)[0] # x, best_x 152 | 153 | def anchor_fitness(k): # mutation fitness 154 | """用于kmean_anchors函数 155 | 适应度计算 优胜劣汰 用于遗传算法中衡量突变是否有效的标注 如果有效就进行选择操作 没效就继续下一轮的突变 156 | :params k: [9, 2] k-means生成的9个anchors wh: [N, 2]: 数据集的所有gt框的宽高 157 | :return (best * (best > thr).float()).mean()=适应度计算公式 [1] 注意和bpr有区别 这里是自定义的一种适应度公式 158 | 返回的是输入此时anchor k 对应的适应度 159 | """ 160 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh) 161 | return (best * (best > thr).float()).mean() # fitness 162 | 163 | def print_results(k): 164 | """用于kmean_anchors函数中打印k-means计算相关信息 165 | 计算bpr、aat=>打印信息: 阈值+bpr+aat anchor个数+图片大小+metric_all+best_mean+past_mean+Kmeans聚类出来的anchor框(四舍五入) 166 | :params k: k-means得到的anchor k 167 | :return k: input 168 | """ 169 | # 将k-means得到的anchor k按面积从小到大啊排序 170 | k = k[np.argsort(k.prod(1))] 171 | # x: [N, 9] N个gt框与所有anchor框的宽比或高比(两者之中较小者) 172 | # best: [N] N个gt框与所有anchor框中的最大 宽比或高比(两者之中较小者) 173 | x, best = metric(k, wh0) 174 | # (best > thr).float(): True=>1. False->0. .mean(): 求均值 175 | # bpr(best possible recall): 最多能被召回(通过thr)的gt框数量 / 所有gt框数量 [1] 0.96223 小于0.98 才会用k-means计算anchor 176 | # aat(anchors above threshold): [1] 3.54360 每个target平均有多少个anchors 177 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr 178 | f = anchor_fitness(k) 179 | # print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr') 180 | # print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' 181 | # f'past_thr={x[x > thr].mean():.3f}-mean: ', end='') 182 | print(f"aat: {aat:.5f}, fitness: {f:.5f}, best possible recall: {bpr:.5f}") 183 | for i, x in enumerate(k): 184 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg 185 | 186 | return k 187 | 188 | 189 | # 载入数据集 190 | if isinstance(path, str): # *.yaml file 191 | with open(path) as f: 192 | data_dict = yaml.safe_load(f) # model dict 193 | from utils.datasets import LoadImagesAndLabels 194 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) 195 | else: 196 | dataset = path # dataset 197 | 198 | # 得到数据集中所有数据的wh 199 | # 将数据集图片的最长边缩放到img_size, 较小边相应缩放 200 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) 201 | # 将原本数据集中gt boxes归一化的wh缩放到shapes尺度 202 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) 203 | 204 | # 统计gt boxes中宽或者高小于3个像素的个数, 目标太小 发出警告 205 | i = (wh0 < 3.0).any(1).sum() 206 | if i: 207 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.') 208 | 209 | # 筛选出label大于2个像素的框拿来聚类,[...]内的相当于一个筛选器,为True的留下 210 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels 211 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 212 | 213 | # Kmeans聚类方法: 使用欧式距离来进行聚类 214 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} gt boxes...') 215 | # 计算宽和高的标准差->[w_std,h_std] 216 | s = wh.std(0) # sigmas for whitening 217 | # 开始聚类,仍然是聚成n类,返回聚类后的anchors k(这个anchor k是白化后数据的anchor框) 218 | # 另外还要注意的是这里的kmeans使用欧式距离来计算的 219 | # 运行k-means的次数为30次 obs: 传入的数据必须先白化处理 'whiten operation' 220 | # 白化处理: 新数据的标准差=1 降低数据之间的相关度,不同数据所蕴含的信息之间的重复性就会降低,网络的训练效率就会提高 221 | # 白化操作博客: https://blog.csdn.net/weixin_37872766/article/details/102957235 222 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance 223 | assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}') 224 | k *= s # k*s 得到原来数据(白化前)的anchor框 225 | 226 | wh = torch.tensor(wh, dtype=torch.float32) # filtered wh 227 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered wh0 228 | 229 | # 输出新算的anchors k 相关的信息 230 | k = print_results(k) 231 | 232 | # Plot wh 233 | # k, d = [None] * 20, [None] * 20 234 | # for i in tqdm(range(1, 21)): 235 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance 236 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) 237 | # ax = ax.ravel() 238 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') 239 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh 240 | # ax[0].hist(wh[wh[:, 0]<100, 0], 400) 241 | # ax[1].hist(wh[wh[:, 1]<100, 1], 400) 242 | # fig.savefig('wh.png', dpi=200) 243 | 244 | # Evolve 类似遗传/进化算法 变异操作 245 | npr = np.random # 随机工具 246 | # f: fitness 0.62690 247 | # sh: (9,2) 248 | # mp: 突变比例mutation prob=0.9 s: sigma=0.1 249 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma 250 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar 251 | # 根据聚类出来的n个点采用遗传算法生成新的anchor 252 | for _ in pbar: 253 | # 重复1000次突变+选择 选择出1000次突变里的最佳anchor k和最佳适应度f 254 | v = np.ones(sh) # v [9, 2] 全是1 255 | while (v == 1).all(): 256 | # 产生变异规则 mutate until a change occurs (prevent duplicates) 257 | # npr.random(sh) < mp: 让v以90%的比例进行变异 选到变异的就为1 没有选到变异的就为0 258 | v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) 259 | # 变异(改变这一时刻之前的最佳适应度对应的anchor k) 260 | kg = (k.copy() * v).clip(min=2.0) 261 | # 计算变异后的anchor kg的适应度 262 | fg = anchor_fitness(kg) 263 | # 如果变异后的anchor kg的适应度>最佳适应度k 就进行选择操作 264 | if fg > f: 265 | # 选择变异后的anchor kg为最佳的anchor k 变异后的适应度fg为最佳适应度f 266 | f, k = fg, kg.copy() 267 | 268 | # 打印信息 269 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' 270 | if verbose: 271 | print_results(k) 272 | return print_results(k) -------------------------------------------------------------------------------- /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.launch --nproc_per_node {nd} --master_port {port} train.py --resume {last}' 32 | else: # single-GPU 33 | cmd = f'python train.py --resume {last}' 34 | 35 | cmd += ' > /dev/null 2>&1 &' # redirect output to dev/null and run in daemon thread 36 | print(cmd) 37 | os.system(cmd) 38 | -------------------------------------------------------------------------------- /utils/aws/userdata.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html 3 | # This script will run only once on first instance start (for a re-start script see mime.sh) 4 | # /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir 5 | # Use >300 GB SSD 6 | 7 | cd home/ubuntu 8 | if [ ! -d yolov5 ]; then 9 | echo "Running first-time script." # install dependencies, download COCO, pull Docker 10 | git clone https://github.com/ultralytics/yolov5 -b master && sudo chmod -R 777 yolov5 11 | cd yolov5 12 | bash data/scripts/get_coco.sh && echo "COCO done." & 13 | sudo docker pull ultralytics/yolov5:latest && echo "Docker done." & 14 | python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." & 15 | wait && echo "All tasks done." # finish background tasks 16 | else 17 | echo "Running re-start script." # resume interrupted runs 18 | i=0 19 | list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour' 20 | while IFS= read -r id; do 21 | ((i++)) 22 | echo "restarting container $i: $id" 23 | sudo docker start $id 24 | # sudo docker exec -it $id python train.py --resume # single-GPU 25 | sudo docker exec -d $id python utils/aws/resume.py # multi-scenario 26 | done <<<"$list" 27 | fi 28 | -------------------------------------------------------------------------------- /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/google_utils.py: -------------------------------------------------------------------------------- 1 | # 谷歌云对应的链接 2 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries 3 | # 该文件负责从github/googleleaps/google drive 等网站下载所需的一些文件 4 | 5 | import os # 与操作系统进行交互的模块 6 | import platform # 提供获取操作系统相关信息的模块 7 | import subprocess # 子进程定义及操作的模块 8 | import time # 时间模块 更底层 9 | import urllib # 用于操作网页 URL,并对网页的内容进行抓取处理 如urllib.parse: 解析url 10 | from pathlib import Path # Path将str转换为Path对象 使字符串路径易于操作的模块 11 | 12 | import requests # 通过urllib3实现自动发送HTTP/1.1请求的第三方模块 13 | import torch # pytorch模块 14 | 15 | 16 | def gsutil_getsize(url=''): 17 | """ 18 | 用于返回网站链接对应文件的大小 19 | gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du 20 | """ 21 | # 创建一个子进程在命令行执行 gsutil du url 命令(访问 Cloud Storage) 返回执行结果(文件) 22 | s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8') 23 | # 返回文件的bytes大小 24 | return eval(s.split(' ')[0]) if len(s) else 0 25 | 26 | 27 | def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''): 28 | """ 29 | 下载 url/url2 路径对应的网页文件 30 | Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes 31 | :params file: 要下载的文件名 32 | :params url: 第一个下载地址 一般是github 33 | :params url2: 第二个下载地址(第一个下载地址下载失败后使用) 一般是googleleaps等云服务器 34 | :params min_bytes: 判断文件是否下载下来 只有文件存在且文件大小要大于min_bytes才能判断文件已经下载下来了 35 | :params error_msg: 文件下载失败的显示信息 初始化默认’‘ 36 | """ 37 | file = Path(file) 38 | assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}" 39 | try: # 尝试从url中下载文件 一般是github 40 | print(f'Downloading {url} to {file}...') 41 | # 从url中下载文件 42 | torch.hub.download_url_to_file(url, str(file)) 43 | # 判断文件是否下载下来了(文件存在且文件大小要大于min_bytes) 44 | assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check 45 | except Exception as e: # 不行就尝试从url2中下载文件 一般是googleleaps(云服务器) 46 | # 移除之前下载失败的文件 47 | file.unlink(missing_ok=True) # remove partial downloads 48 | print(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...') 49 | os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail 50 | finally: 51 | # 检查文件是否下载下来了(是否存在) 或 文件大小是否小于min_bytes 52 | if not file.exists() or file.stat().st_size < min_bytes: # check 53 | # 下载失败 移除下载失败的文件 remove partial downloads 54 | file.unlink(missing_ok=True) 55 | # 打印错误信息 56 | print(f"ERROR: {assert_msg}\n{error_msg}") 57 | print('') 58 | 59 | 60 | def attempt_download(file, repo='ultralytics/yolov5'): 61 | """train.py 62 | 实现从几个云平台(github/googleleaps云服务器)下载文件(预训练模型) 63 | :params file: 如果是文件路径 且这个路径不存在文件就尝试下载文件 64 | 果是url地址 就直接下载文件 65 | 如果只是一个要下载的文件名, 那就获取版本号开始下载(github/googleleaps) 66 | :params repo: 下载文件的github仓库名 默认是'ultralytics/yolov5' 67 | """ 68 | # .strip()删除字符串前后空格 /n /t等 .replace将 ' 替换为空格 Path将str转换为Path对象 69 | file = Path(str(file).strip().replace("'", '')) 70 | 71 | # 如果这个文件路径不存在文件 就尝试下载 72 | if not file.exists(): 73 | # urllib.parse: 解析url .unquote: 对url进行解码 decode '%2F' to '/' etc. 74 | name = Path(urllib.parse.unquote(str(file))).name 75 | # 如果解析的文件名是http:/ 或 https:/ 开头就直接下载 76 | if str(file).startswith(('http:/', 'https:/')): # download 77 | # url: 下载路径 url 78 | url = str(file).replace(':/', '://') # Pathlib turns :// -> :/ 79 | # name: 要下载的文件名 80 | name = name.split('?')[0] # parse authentication https://url.com/file.txt?auth... 81 | # 下载文件 82 | safe_download(file=name, url=url, min_bytes=1E5) 83 | return name 84 | 85 | # GitHub assets 86 | file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required) 87 | try: 88 | # 利用github api 获取最新的版本相关信息 这里的response是一个打字典 89 | response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api 90 | # response['assets']中包含多个字典的列表 其中记录每一个asset的相关信息 91 | # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...] 92 | assets = [x['name'] for x in response['assets']] 93 | # tag: 当前最新版本号 如'v5.0' 94 | tag = response['tag_name'] 95 | except: # 获取失败 就退而求其次 直接利用git命令强行补齐版本信息 96 | assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 97 | 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt'] 98 | try: 99 | # 创建一个子进程在命令行执行 git tag 命令(返回版本号 版本号信息一般在字典最后 -1) 返回执行结果(版本号tag) 100 | tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1] 101 | except: 102 | # 如果还是失败 就强行自己补一个版本号 tag='v5.0' 103 | tag = 'v5.0' # current release 104 | 105 | if name in assets: 106 | # 开始从github中下载文件 107 | # file: 要下载的文件名 108 | # url: 第一个下载地址 一般是github repo: github仓库名 tag: 版本号 name: 文件名 .pt 109 | # url2: 第二个备用的下载地址 一般是googleapis(云服务器) 110 | # min_bytes: 判断文件是否下载下来 只有文件存在且文件大小要大于min_bytes才能判断文件已经下载下来了 111 | # error_msg: 下载失败的显示信息 112 | safe_download(file, 113 | url=f'https://github.com/{repo}/releases/download/{tag}/{name}', 114 | url2=f'https://storage.googleapis.com/{repo}/ckpt/{name}', # backup url (optional) 115 | min_bytes=1E5, 116 | error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/') 117 | 118 | return str(file) 119 | 120 | 121 | def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'): 122 | """ 123 | 实现从google drive上下载压缩文件 124 | :params id: url ?后面的id参数的参数值 125 | :params file: 需要下载的压缩文件名 126 | """ 127 | t = time.time() # 获取当前时间 128 | file = Path(file) # Path将str转换为Path对象 129 | cookie = Path('cookie') # gdrive cookie 130 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='') 131 | file.unlink(missing_ok=True) # 移除已经存在的文件(可能是下载失败/下载不完全) 132 | cookie.unlink(missing_ok=True) # 移除已经存在的cookie 133 | 134 | # 尝试下载压缩文件 135 | out = "NUL" if platform.system() == "Windows" else "/dev/null" 136 | # 使用cmd命令从google drive上下载文件 137 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}') 138 | if os.path.exists('cookie'): 139 | # 如果文件较大 就需要有令牌get_token(存在cookie才有令牌)的指令s才能下载 140 | # get_token()函数在下面定义了 用于获取当前cookie的令牌token 141 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}' 142 | else: 143 | # 小文件就不需要带令牌的指令s 直接下载就行 144 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"' 145 | # 执行下载指令s 并获得返回 如果cmd命令执行成功 则os.system()命令会返回0 146 | r = os.system(s) 147 | cookie.unlink(missing_ok=True) # 再次移除已经存在的cookie 148 | 149 | # 下载错误检测 如果r != 0 则下载错误 150 | if r != 0: 151 | file.unlink(missing_ok=True) # 下载错误 移除下载的文件(可能不完全或者下载失败) 152 | print('Download error ') # raise Exception('Download error') 153 | return r 154 | 155 | 156 | # 如果是压缩文件 就解压 file.suffix方法可以获取file文件的后缀 157 | if file.suffix == '.zip': 158 | print('unzipping... ', end='') 159 | os.system(f'unzip -q {file}') # cmd命令执行解压命令 160 | file.unlink() # 移除.zip压缩文件 161 | 162 | print(f'Done ({time.time() - t:.1f}s)') # 打印下载 + 解压过程所需要的时间 163 | return r 164 | 165 | 166 | def get_token(cookie="./cookie"): 167 | """ 168 | 实现从cookie中获取令牌token 在gdrive_download中使用 169 | """ 170 | with open(cookie) as f: 171 | for line in f: 172 | if "download" in line: 173 | return line.split()[-1] 174 | return "" 175 | 176 | 177 | # --------------------------------------- 下面两个函数没什么用 可以不看 --------------------------------------------------- 178 | # def upload_blob(bucket_name, source_file_name, destination_blob_name): 179 | # # Uploads a file to a bucket 180 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python 181 | # 182 | # storage_client = storage.Client() 183 | # bucket = storage_client.get_bucket(bucket_name) 184 | # blob = bucket.blob(destination_blob_name) 185 | # 186 | # blob.upload_from_filename(source_file_name) 187 | # 188 | # print('File {} uploaded to {}.'.format( 189 | # source_file_name, 190 | # destination_blob_name)) 191 | # 192 | # 193 | # def download_blob(bucket_name, source_blob_name, destination_file_name): 194 | # # Uploads a blob from a bucket 195 | # storage_client = storage.Client() 196 | # bucket = storage_client.get_bucket(bucket_name) 197 | # blob = bucket.blob(source_blob_name) 198 | # 199 | # blob.download_to_filename(destination_file_name) 200 | # 201 | # print('Blob {} downloaded to {}.'.format( 202 | # source_blob_name, 203 | # destination_file_name)) 204 | -------------------------------------------------------------------------------- /utils/loss.py: -------------------------------------------------------------------------------- 1 | # Loss functions 2 | import math 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): 11 | """用在ComputeLoss类中 12 | 标签平滑操作 [1, 0] => [0.95, 0.05] 13 | https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441 14 | https://arxiv.org/pdf/1902.04103.pdf eqn 3 15 | :params eps: 平滑参数 16 | :return positive, negative label smoothing BCE targets 两个值分别代表正样本和负样本的标签取值 17 | 原先的正样本=1 负样本=0 改为 正样本=1.0 - 0.5 * eps 负样本=0.5 * eps 18 | """ 19 | return 1.0 - 0.5 * eps, 0.5 * eps 20 | 21 | 22 | class BCEBlurWithLogitsLoss(nn.Module): 23 | """用在ComputeLoss类的__init__函数中 24 | BCEwithLogitLoss() with reduced missing label effects. 25 | https://github.com/ultralytics/yolov5/issues/1030 26 | The idea was to reduce the effects of false positive (missing labels) 就是检测成正样本了 但是检测错了 27 | """ 28 | def __init__(self, alpha=0.05): 29 | super(BCEBlurWithLogitsLoss, self).__init__() 30 | self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss() 31 | self.alpha = alpha 32 | 33 | def forward(self, pred, true): 34 | loss = self.loss_fcn(pred, true) 35 | pred = torch.sigmoid(pred) # prob from logits 36 | # dx = [-1, 1] 当pred=1 true=0时(网络预测说这里有个obj但是gt说这里没有), dx=1 => alpha_factor=0 => loss=0 37 | # 这种就是检测成正样本了但是检测错了(false positive)或者missing label的情况 这种情况不应该过多的惩罚->loss=0 38 | dx = pred - true # reduce only missing label effects 39 | # 如果采样绝对值的话 会减轻pred和gt差异过大而造成的影响 40 | # dx = (pred - true).abs() # reduce missing label and false label effects 41 | alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4)) 42 | loss *= alpha_factor 43 | return loss.mean() 44 | 45 | 46 | class FocalLoss(nn.Module): 47 | """用在代替原本的BCEcls(分类损失)和BCEobj(置信度损失) 48 | Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) 49 | 论文: https://arxiv.org/abs/1708.02002 50 | https://blog.csdn.net/qq_38253797/article/details/116292496 51 | TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py 52 | """ 53 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): 54 | super(FocalLoss, self).__init__() 55 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()=Sigmoid+BCELoss 定义为多分类交叉熵损失函数 56 | self.gamma = gamma # 参数gamma 用于削弱简单样本对loss的贡献程度 57 | self.alpha = alpha # 参数alpha 用于平衡正负样本个数不均衡的问题 58 | # self.reduction: 控制FocalLoss损失输出模式 sum/mean/none 默认是Mean 59 | self.reduction = loss_fcn.reduction 60 | # focalloss中的BCE函数的reduction='None' BCE不使用Sum或者Mean 61 | self.loss_fcn.reduction = 'none' # 需要将Focal loss应用于每一个样本之中 62 | 63 | def forward(self, pred, true): 64 | loss = self.loss_fcn(pred, true) # 正常BCE的loss: loss = -log(p_t) 65 | # p_t = torch.exp(-loss) 66 | # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability 67 | 68 | pred_prob = torch.sigmoid(pred) # prob from logits 69 | # true=1 p_t=pred_prob true=0 p_t=1-pred_prob 70 | p_t = true * pred_prob + (1 - true) * (1 - pred_prob) # p_t 71 | # true=1 alpha_factor=self.alpha true=0 alpha_factor=1-self.alpha 72 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) # alpha_t 73 | modulating_factor = (1.0 - p_t) ** self.gamma # 这里代表Focal loss中的指数项 74 | # 返回最终的loss=BCE * 两个参数 (看看公式就行了 和公式一模一样) 75 | loss *= alpha_factor * modulating_factor 76 | 77 | # 最后选择focalloss返回的类型 默认是mean 78 | if self.reduction == 'mean': 79 | return loss.mean() 80 | elif self.reduction == 'sum': 81 | return loss.sum() 82 | else: # 'none' 83 | return loss 84 | 85 | 86 | class QFocalLoss(nn.Module): 87 | """用来代替FocalLoss 88 | QFocalLoss 来自General Focal Loss论文: https://arxiv.org/abs/2006.04388 89 | Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) 90 | """ 91 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): 92 | super(QFocalLoss, self).__init__() 93 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() 94 | self.gamma = gamma 95 | self.alpha = alpha 96 | self.reduction = loss_fcn.reduction 97 | self.loss_fcn.reduction = 'none' # required to apply FL to each element 98 | 99 | def forward(self, pred, true): 100 | loss = self.loss_fcn(pred, true) 101 | 102 | pred_prob = torch.sigmoid(pred) # prob from logits 103 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) 104 | # 和FocalLoss相比只变了这里 105 | modulating_factor = torch.abs(true - pred_prob) ** self.gamma 106 | loss *= alpha_factor * modulating_factor 107 | 108 | if self.reduction == 'mean': 109 | return loss.mean() 110 | elif self.reduction == 'sum': 111 | return loss.sum() 112 | else: # 'none' 113 | return loss 114 | 115 | 116 | class ComputeLoss: 117 | # Compute losses 这个函数会用在train.py中进行损失计算 118 | def __init__(self, model, autobalance=False): 119 | super(ComputeLoss, self).__init__() 120 | self.sort_obj_iou = False # 后面筛选置信度损失正样本的时候是否先对iou排序 121 | 122 | device = next(model.parameters()).device # get model device 123 | h = model.hyp # hyperparameters 124 | 125 | # Define criteria 定义分类损失和置信度损失 126 | # BCEcls = BCEBlurWithLogitsLoss() 127 | # BCEobj = BCEBlurWithLogitsLoss() 128 | # h['cls_pw']=1 BCEWithLogitsLoss默认的正样本权重也是1 129 | BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device)) 130 | BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device)) 131 | 132 | # 标签平滑 eps=0代表不做标签平滑-> cp=1 cn=0 eps!=0代表做标签平滑 cp代表positive的标签值 cn代表negative的标签值 133 | self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets 134 | 135 | # Focal loss g=0 代表不用focal loss 136 | g = h['fl_gamma'] # focal loss gamma 137 | if g > 0: 138 | # g>0 将分类损失和置信度损失(BCE)都换成focalloss损失函数 139 | BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g) 140 | # BCEcls, BCEobj = QFocalLoss(BCEcls, g), QFocalLoss(BCEobj, g) # 调用QFocalLoss来代替FocalLoss 141 | 142 | # det: 返回的是模型的检测头 Detector 3个 分别对应产生三个输出feature map 143 | det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module 144 | 145 | # balance用来设置三个feature map对应输出的置信度损失系数(平衡三个feature map的置信度损失) 146 | # 从左到右分别对应大feature map(检测小目标)到小feature map(检测大目标) 147 | # 思路: It seems that larger output layers may overfit earlier, so those numbers may need a bit of adjustment 148 | # 一般来说,检测小物体的难度大一点,所以会增加大特征图的损失系数,让模型更加侧重小物体的检测 149 | # 如果det.nl=3就返回[4.0, 1.0, 0.4]否则返回[4.0, 1.0, 0.25, 0.06, .02] 150 | # self.balance = {3: [4.0, 1.0, 0.4], 4: [4.0, 1.0, 0.25, 0.06], 5: [4.0, 1.0, 0.25, 0.06, .02]}[det.nl] 151 | self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7 152 | 153 | # 三个预测头的下采样率det.stride: [8, 16, 32] .index(16): 求出下采样率stride=16的索引 154 | # 这个参数会用来自动计算更新3个feature map的置信度损失系数self.balance 155 | self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index 156 | 157 | # self.BCEcls: 类别损失函数 self.BCEobj: 置信度损失函数 self.hyp: 超参数 158 | # self.gr: 计算真实框的置信度标准的iou ratio self.autobalance: 是否自动更新各feature map的置信度损失平衡系数 默认False 159 | self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, model.gr, h, autobalance 160 | 161 | # na: number of anchors 每个grid_cell的anchor数量 = 3 162 | # nc: number of classes 数据集的总类别 = 80 163 | # nl: number of detection layers Detect的个数 = 3 164 | # anchors: [3, 3, 2] 3个feature map 每个feature map上有3个anchor(w,h) 这里的anchor尺寸是相对feature map的 165 | for k in 'na', 'nc', 'nl', 'anchors': 166 | # setattr: 给对象self的属性k赋值为getattr(det, k) 167 | # getattr: 返回det对象的k属性 168 | # 所以这句话的意思: 讲det的k属性赋值给self.k属性 其中k in 'na', 'nc', 'nl', 'anchors' 169 | setattr(self, k, getattr(det, k)) 170 | 171 | def __call__(self, p, targets): # predictions, targets, model 172 | """ 173 | :params p: 预测框 由模型构建中的三个检测头Detector返回的三个yolo层的输出 174 | tensor格式 list列表 存放三个tensor 对应的是三个yolo层的输出 175 | 如: [4, 3, 112, 112, 85]、[4, 3, 56, 56, 85]、[4, 3, 28, 28, 85] 176 | [bs, anchor_num, grid_h, grid_w, xywh+class+classes] 177 | 可以看出来这里的预测值p是三个yolo层每个grid_cell(每个grid_cell有三个预测值)的预测值,后面肯定要进行正样本筛选 178 | :params targets: 数据增强后的真实框 [63, 6] [num_object, batch_index+class+xywh] 179 | :params loss * bs: 整个batch的总损失 进行反向传播 180 | :params torch.cat((lbox, lobj, lcls, loss)).detach(): 回归损失、置信度损失、分类损失和总损失 这个参数只用来可视化参数或保存信息 181 | """ 182 | device = targets.device # 确定运行的设备 183 | 184 | # 初始化lcls, lbox, lobj三种损失值 tensor([0.]) 185 | lcls, lbox, lobj = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device) 186 | 187 | # 每一个都是append的 有feature map个 每个都是当前这个feature map中3个anchor筛选出的所有的target(3个grid_cell进行预测) 188 | # tcls: 表示这个target所属的class index 189 | # tbox: xywh 其中xy为这个target对当前grid_cell左上角的偏移量 190 | # indices: b: 表示这个target属于的image index 191 | # a: 表示这个target使用的anchor index 192 | # gj: 经过筛选后确定某个target在某个网格中进行预测(计算损失) gj表示这个网格的左上角y坐标 193 | # gi: 表示这个网格的左上角x坐标 194 | # anch: 表示这个target所使用anchor的尺度(相对于这个feature map) 注意可能一个target会使用大小不同anchor进行计算 195 | tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets 196 | 197 | # 依次遍历三个feature map的预测输出pi 198 | for i, pi in enumerate(p): # layer index, layer predictions 199 | b, a, gj, gi = indices[i] # image_index, anchor_index, gridy, gridx 200 | 201 | tobj = torch.zeros_like(pi[..., 0], device=device) # 初始化target置信度(先全是负样本 后面再筛选正样本赋值) 202 | 203 | n = b.shape[0] # number of targets 204 | if n: 205 | # 精确得到第b张图片的第a个feature map的grid_cell(gi, gj)对应的预测值 206 | # 用这个预测值与我们筛选的这个grid_cell的真实框进行预测(计算损失) 207 | ps = pi[b, a, gj, gi] # prediction subset corresponding to targets 208 | 209 | # Regression loss 只计算所有正样本的回归损失 210 | # 新的公式: pxy = [-0.5 + cx, 1.5 + cx] pwh = [0, 4pw] 这个区域内都是正样本 211 | # Get more positive samples, accelerate convergence and be more stable 212 | pxy = ps[:, :2].sigmoid() * 2. - 0.5 # 一个归一化操作 和论文里不同 213 | # https://github.com/ultralytics/yolov3/issues/168 214 | pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i] # 和论文里不同 这里是作者自己提出的公式 215 | pbox = torch.cat((pxy, pwh), 1) # predicted box 216 | # 这里的tbox[i]中的xy是这个target对当前grid_cell左上角的偏移量[0,1] 而pbox.T是一个归一化的值 217 | # 就是要用这种方式训练 传回loss 修改梯度 让pbox越来越接近tbox(偏移量) 218 | iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target) 219 | lbox += (1.0 - iou).mean() # iou loss 220 | 221 | # Objectness loss stpe1 222 | # iou.detach() 不会更新iou梯度 iou并不是反向传播的参数 所以不需要反向传播梯度信息 223 | score_iou = iou.detach().clamp(0).type(tobj.dtype) # .clamp(0)必须大于等于0 224 | if self.sort_obj_iou: # 可以看下官方的解释 我也不是很清楚为什么这里要对iou排序??? 225 | # https://github.com/ultralytics/yolov5/issues/3605 226 | # There maybe several GTs match the same anchor when calculate ComputeLoss in the scene with dense targets 227 | sort_id = torch.argsort(score_iou) 228 | b, a, gj, gi, score_iou = b[sort_id], a[sort_id], gj[sort_id], gi[sort_id], score_iou[sort_id] 229 | # 预测信息有置信度 但是真实框信息是没有置信度的 所以需要我们认为的给一个标准置信度 230 | # self.gr是iou ratio [0, 1] self.gr越大置信度越接近iou self.gr越小越接近1(人为加大训练难度) 231 | tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * score_iou # iou ratio 232 | # tobj[b, a, gj, gi] = 1 # 如果发现预测的score不高 数据集目标太小太拥挤 困难样本过多 可以试试这个 233 | 234 | # Classification loss 只计算所有正样本的分类损失 235 | if self.nc > 1: # cls loss (only if multiple classes) 236 | # targets 原本负样本是0 这里使用smooth label 就是cn 237 | t = torch.full_like(ps[:, 5:], self.cn, device=device) 238 | t[range(n), tcls[i]] = self.cp # 筛选到的正样本对应位置值是cp 239 | lcls += self.BCEcls(ps[:, 5:], t) # BCE 240 | 241 | # Append targets to text file 242 | # with open('targets.txt', 'a') as file: 243 | # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)] 244 | 245 | # Objectness loss stpe2 置信度损失是用所有样本(正样本 + 负样本)一起计算损失的 246 | obji = self.BCEobj(pi[..., 4], tobj) 247 | # 每个feature map的置信度损失权重不同 要乘以相应的权重系数self.balance[i] 248 | # 一般来说,检测小物体的难度大一点,所以会增加大特征图的损失系数,让模型更加侧重小物体的检测 249 | lobj += obji * self.balance[i] # obj loss 250 | 251 | if self.autobalance: 252 | # 自动更新各个feature map的置信度损失系数 253 | self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item() 254 | 255 | if self.autobalance: 256 | self.balance = [x / self.balance[self.ssi] for x in self.balance] 257 | 258 | # 根据超参中的损失权重参数 对各个损失进行平衡 防止总损失被某个损失所左右 259 | lbox *= self.hyp['box'] 260 | lobj *= self.hyp['obj'] 261 | lcls *= self.hyp['cls'] 262 | 263 | bs = tobj.shape[0] # batch size 264 | 265 | loss = lbox + lobj + lcls # 平均每张图片的总损失 266 | 267 | # loss * bs: 整个batch的总损失 268 | # .detach() 利用损失值进行反向传播 利用梯度信息更新的是损失函数的参数 而对于损失这个值是不需要梯度反向传播的 269 | return loss * bs, torch.cat((lbox, lobj, lcls, loss)).detach() 270 | 271 | def build_targets(self, p, targets): 272 | """ 273 | Build targets for compute_loss() 274 | :params p: 预测框 由模型构建中的三个检测头Detector返回的三个yolo层的输出 275 | tensor格式 list列表 存放三个tensor 对应的是三个yolo层的输出 276 | 如: [4, 3, 112, 112, 85]、[4, 3, 56, 56, 85]、[4, 3, 28, 28, 85] 277 | [bs, anchor_num, grid_h, grid_w, xywh+class+classes] 278 | 可以看出来这里的预测值p是三个yolo层每个grid_cell(每个grid_cell有三个预测值)的预测值,后面肯定要进行正样本筛选 279 | :params targets: 数据增强后的真实框 [63, 6] [num_target, image_index+class+xywh] xywh为归一化后的框 280 | :return tcls: 表示这个target所属的class index 281 | tbox: xywh 其中xy为这个target对当前grid_cell左上角的偏移量 282 | indices: b: 表示这个target属于的image index 283 | a: 表示这个target使用的anchor index 284 | gj: 经过筛选后确定某个target在某个网格中进行预测(计算损失) gj表示这个网格的左上角y坐标 285 | gi: 表示这个网格的左上角x坐标 286 | anch: 表示这个target所使用anchor的尺度(相对于这个feature map) 注意可能一个target会使用大小不同anchor进行计算 287 | """ 288 | na, nt = self.na, targets.shape[0] # number of anchors 3, targets 63 289 | tcls, tbox, indices, anch = [], [], [], [] # 初始化tcls tbox indices anch 290 | 291 | # gain是为了后面将targets=[na,nt,7]中的归一化了的xywh映射到相对feature map尺度上 292 | # 7: image_index+class+xywh+anchor_index 293 | gain = torch.ones(7, device=targets.device) 294 | 295 | # 需要在3个anchor上都进行训练 所以将标签赋值na=3个 ai代表3个anchor上在所有的target对应的anchor索引 就是用来标记下当前这个target属于哪个anchor 296 | # [1, 3] -> [3, 1] -> [3, 63]=[na, nt] 三行 第一行63个0 第二行63个1 第三行63个2 297 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) 298 | 299 | # [63, 6] [3, 63] -> [3, 63, 6] [3, 63, 1] -> [3, 63, 7] 7: [image_index+class+xywh+anchor_index] 300 | # 对每一个feature map: 这一步是将target复制三份 对应一个feature map的三个anchor 301 | # 先假设所有的target对三个anchor都是正样本(复制三份) 再进行筛选 并将ai加进去标记当前是哪个anchor的target 302 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices 303 | 304 | # 这两个变量是用来扩展正样本的 因为预测框预测到target有可能不止当前的格子预测到了 305 | # 可能周围的格子也预测到了高质量的样本 我们也要把这部分的预测信息加入正样本中 306 | g = 0.5 # bias 中心偏移 用来衡量target中心点离哪个格子更近 307 | # 以自身 + 周围左上右下4个网格 = 5个网格 用来计算offsets 308 | off = torch.tensor([[0, 0], 309 | [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m 310 | # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm 311 | ], device=targets.device).float() * g # offsets 312 | 313 | # 遍历三个feature 筛选每个feature map(包含batch张图片)的每个anchor的正样本 314 | for i in range(self.nl): # self.nl: number of detection layers Detect的个数 = 3 315 | # anchors: 当前feature map对应的三个anchor尺寸(相对feature map) [3, 2] 316 | anchors = self.anchors[i] 317 | 318 | # gain: 保存每个输出feature map的宽高 -> gain[2:6]=gain[whwh] 319 | # [1, 1, 1, 1, 1, 1, 1] -> [1, 1, 112, 112, 112,112, 1]=image_index+class+xywh+anchor_index 320 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain 321 | 322 | # t = [3, 63, 7] 将target中的xywh的归一化尺度放缩到相对当前feature map的坐标尺度 323 | # [3, 63, image_index+class+xywh+anchor_index] 324 | t = targets * gain 325 | 326 | if nt: # 开始匹配 Matches 327 | # t=[na, nt, 7] t[:, :, 4:6]=[na, nt, 2]=[3, 63, 2] 328 | # anchors[:, None]=[na, 1, 2] 329 | # r=[na, nt, 2]=[3, 63, 2] 330 | # 当前feature map的3个anchor的所有正样本(没删除前是所有的targets)与三个anchor的宽高比(w/w h/h) 331 | r = t[:, :, 4:6] / anchors[:, None] # wh ratio (w/w h/h) 332 | 333 | # 筛选条件 GT与anchor的宽比或高比超过一定的阈值 就当作负样本 334 | # torch.max(r, 1. / r)=[3, 63, 2] 筛选出宽比w1/w2 w2/w1 高比h1/h2 h2/h1中最大的那个 335 | # .max(2)返回宽比 高比两者中较大的一个值和它的索引 [0]返回较大的一个值 336 | # j: [3, 63] False: 当前gt是当前anchor的负样本 True: 当前gt是当前anchor的正样本 337 | j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare 338 | # yolov3 v4的筛选方法: wh_iou GT与anchor的wh_iou超过一定的阈值就是正样本 339 | # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) 340 | 341 | # 根据筛选条件j, 过滤负样本, 得到当前feature map上三个anchor的所有正样本t(batch_size张图片) 342 | # t: [3, 63, 7] -> [126, 7] [num_Positive_sample, image_index+class+xywh+anchor_index] 343 | t = t[j] # filter 344 | 345 | # Offsets 筛选当前格子周围格子 找到2个离target中心最近的两个格子 可能周围的格子也预测到了高质量的样本 我们也要把这部分的预测信息加入正样本中 346 | # 除了target所在的当前格子外, 还有2个格子对目标进行检测(计算损失) 也就是说一个目标需要3个格子去预测(计算损失) 347 | # 首先当前格子是其中1个 再从当前格子的上下左右四个格子中选择2个 用这三个格子去预测这个目标(计算损失) 348 | # feature map上的原点在左上角 向右为x轴正坐标 向下为y轴正坐标 349 | gxy = t[:, 2:4] # grid xy 取target中心的坐标xy(相对feature map左上角的坐标) 350 | gxi = gain[[2, 3]] - gxy # inverse 得到target中心点相对于右下角的坐标 gain[[2, 3]]为当前feature map的wh 351 | # 筛选中心坐标 距离当前grid_cell的左、上方偏移小于g=0.5 且 中心坐标必须大于1(坐标不能在边上 此时就没有4个格子了) 352 | # j: [126] bool 如果是True表示当前target中心点所在的格子的左边格子也对该target进行回归(后续进行计算损失) 353 | # k: [126] bool 如果是True表示当前target中心点所在的格子的上边格子也对该target进行回归(后续进行计算损失) 354 | j, k = ((gxy % 1. < g) & (gxy > 1.)).T 355 | # 筛选中心坐标 距离当前grid_cell的右、下方偏移小于g=0.5 且 中心坐标必须大于1(坐标不能在边上 此时就没有4个格子了) 356 | # l: [126] bool 如果是True表示当前target中心点所在的格子的右边格子也对该target进行回归(后续进行计算损失) 357 | # m: [126] bool 如果是True表示当前target中心点所在的格子的下边格子也对该target进行回归(后续进行计算损失) 358 | l, m = ((gxi % 1. < g) & (gxi > 1.)).T 359 | # j: [5, 126] torch.ones_like(j): 当前格子, 不需要筛选全是True j, k, l, m: 左上右下格子的筛选结果 360 | j = torch.stack((torch.ones_like(j), j, k, l, m)) 361 | # 得到筛选后所有格子的正样本 格子数<=3*126 都不在边上等号成立 362 | # t: [126, 7] -> 复制5份target[5, 126, 7] 分别对应当前格子和左上右下格子5个格子 363 | # j: [5, 126] + t: [5, 126, 7] => t: [378, 7] 理论上是小于等于3倍的126 当且仅当没有边界的格子等号成立 364 | t = t.repeat((5, 1, 1))[j] 365 | # torch.zeros_like(gxy)[None]: [1, 126, 2] off[:, None]: [5, 1, 2] => [5, 126, 2] 366 | # j筛选后: [378, 2] 得到所有筛选后的网格的中心相对于这个要预测的真实框所在网格边界(左右上下边框)的偏移量 367 | offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] 368 | else: 369 | t = targets[0] 370 | offsets = 0 371 | 372 | # Define 373 | b, c = t[:, :2].long().T # image_index, class 374 | gxy = t[:, 2:4] # target的xy 375 | gwh = t[:, 4:6] # target的wh 376 | gij = (gxy - offsets).long() # 预测真实框的网格所在的左上角坐标(有左上右下的网格) 377 | gi, gj = gij.T # grid xy indices 378 | 379 | # Append 380 | a = t[:, 6].long() # anchor index 381 | # b: image index a: anchor index gj: 网格的左上角y坐标 gi: 网格的左上角x坐标 382 | indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) 383 | # tbix: xywh 其中xy为这个target对当前grid_cell左上角的偏移量 384 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box 385 | anch.append(anchors[a]) # 对应的所有anchors 386 | tcls.append(c) # class 387 | 388 | return tcls, tbox, indices, anch 389 | 390 | 391 | 392 | 393 | -------------------------------------------------------------------------------- /utils/wandb_logging/log_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import yaml 4 | 5 | from utils.wandb_logging.wandb_utils import WandbLogger 6 | 7 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' 8 | 9 | 10 | def create_dataset_artifact(opt): 11 | with open(opt.data) as f: 12 | data = yaml.safe_load(f) # data dict 13 | logger = WandbLogger(opt, '', None, data, job_type='Dataset Creation') 14 | 15 | 16 | if __name__ == '__main__': 17 | parser = argparse.ArgumentParser() 18 | parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') 19 | parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') 20 | parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project') 21 | parser.add_argument('--entity', default=None, help='W&B entity') 22 | 23 | opt = parser.parse_args() 24 | opt.resume = False # Explicitly disallow resume check for dataset upload job 25 | 26 | create_dataset_artifact(opt) 27 | -------------------------------------------------------------------------------- /utils/wandb_logging/wandb_utils.py: -------------------------------------------------------------------------------- 1 | """Utilities and tools for tracking runs with Weights & Biases.""" 2 | import logging 3 | import os 4 | import sys 5 | from contextlib import contextmanager 6 | from pathlib import Path 7 | 8 | import yaml 9 | from tqdm import tqdm 10 | 11 | sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path 12 | from utils.datasets import LoadImagesAndLabels 13 | from utils.datasets import img2label_paths 14 | from utils.general import colorstr, check_dataset, check_file 15 | 16 | try: 17 | import wandb 18 | from wandb import init, finish 19 | except ImportError: 20 | wandb = None 21 | # wandb = None 22 | 23 | RANK = int(os.getenv('RANK', -1)) 24 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' 25 | 26 | 27 | def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX): 28 | return from_string[len(prefix):] 29 | 30 | 31 | def check_wandb_config_file(data_config_file): 32 | wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path 33 | if Path(wandb_config).is_file(): 34 | return wandb_config 35 | return data_config_file 36 | 37 | 38 | def get_run_info(run_path): 39 | run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX)) 40 | run_id = run_path.stem 41 | project = run_path.parent.stem 42 | entity = run_path.parent.parent.stem 43 | model_artifact_name = 'run_' + run_id + '_model' 44 | return entity, project, run_id, model_artifact_name 45 | 46 | 47 | def check_wandb_resume(opt): 48 | process_wandb_config_ddp_mode(opt) if RANK not in [-1, 0] else None 49 | if isinstance(opt.resume, str): 50 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): 51 | if RANK not in [-1, 0]: # For resuming DDP runs 52 | entity, project, run_id, model_artifact_name = get_run_info(opt.resume) 53 | api = wandb.Api() 54 | artifact = api.artifact(entity + '/' + project + '/' + model_artifact_name + ':latest') 55 | modeldir = artifact.download() 56 | opt.weights = str(Path(modeldir) / "last.pt") 57 | return True 58 | return None 59 | 60 | 61 | def process_wandb_config_ddp_mode(opt): 62 | with open(check_file(opt.data)) as f: 63 | data_dict = yaml.safe_load(f) # data dict 64 | train_dir, val_dir = None, None 65 | if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX): 66 | api = wandb.Api() 67 | train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias) 68 | train_dir = train_artifact.download() 69 | train_path = Path(train_dir) / 'data/images/' 70 | data_dict['train'] = str(train_path) 71 | 72 | if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX): 73 | api = wandb.Api() 74 | val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias) 75 | val_dir = val_artifact.download() 76 | val_path = Path(val_dir) / 'data/images/' 77 | data_dict['val'] = str(val_path) 78 | if train_dir or val_dir: 79 | ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml') 80 | with open(ddp_data_path, 'w') as f: 81 | yaml.safe_dump(data_dict, f) 82 | opt.data = ddp_data_path 83 | 84 | 85 | class WandbLogger(): 86 | """Log training runs, datasets, models, and predictions to Weights & Biases. 87 | 88 | This logger sends information to W&B at wandb.ai. By default, this information 89 | includes hyperparameters, system configuration and metrics, model metrics, 90 | and basic data metrics and analyses. 91 | 92 | By providing additional command line arguments to train.py, datasets, 93 | models and predictions can also be logged. 94 | 95 | For more on how this logger is used, see the Weights & Biases documentation: 96 | https://docs.wandb.com/guides/integrations/yolov5 97 | """ 98 | 99 | def __init__(self, opt, name, run_id, data_dict, job_type='Training'): 100 | # Pre-training routine -- 101 | self.job_type = job_type 102 | self.wandb, self.wandb_run, self.data_dict = wandb, None if not wandb else wandb.run, data_dict 103 | # It's more elegant to stick to 1 wandb.init call, but useful config data is overwritten in the WandbLogger's wandb.init call 104 | if isinstance(opt.resume, str): # checks resume from artifact 105 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): 106 | entity, project, run_id, model_artifact_name = get_run_info(opt.resume) 107 | model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name 108 | assert wandb, 'install wandb to resume wandb runs' 109 | # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config 110 | self.wandb_run = wandb.init(id=run_id, 111 | project=project, 112 | entity=entity, 113 | resume='allow', 114 | allow_val_change=True) 115 | opt.resume = model_artifact_name 116 | elif self.wandb: 117 | self.wandb_run = wandb.init(config=opt, 118 | resume="allow", 119 | project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem, 120 | entity=opt.entity, 121 | name=name, 122 | job_type=job_type, 123 | id=run_id, 124 | allow_val_change=True) if not wandb.run else wandb.run 125 | if self.wandb_run: 126 | if self.job_type == 'Training': 127 | if not opt.resume: 128 | wandb_data_dict = self.check_and_upload_dataset(opt) if opt.upload_dataset else data_dict 129 | # Info useful for resuming from artifacts 130 | self.wandb_run.config.update({'opt': vars(opt), 'data_dict': data_dict}, allow_val_change=True) 131 | self.data_dict = self.setup_training(opt, data_dict) 132 | if self.job_type == 'Dataset Creation': 133 | self.data_dict = self.check_and_upload_dataset(opt) 134 | else: 135 | prefix = colorstr('wandb: ') 136 | print(f"{prefix}Install Weights & Biases for YOLOv5 logging with 'pip install wandb' (recommended)") 137 | 138 | def check_and_upload_dataset(self, opt): 139 | assert wandb, 'Install wandb to upload dataset' 140 | config_path = self.log_dataset_artifact(check_file(opt.data), 141 | opt.single_cls, 142 | 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem) 143 | print("Created dataset config file ", config_path) 144 | with open(config_path) as f: 145 | wandb_data_dict = yaml.safe_load(f) 146 | return wandb_data_dict 147 | 148 | def setup_training(self, opt, data_dict): 149 | self.log_dict, self.current_epoch, self.log_imgs = {}, 0, 16 # Logging Constants 150 | self.bbox_interval = opt.bbox_interval 151 | if isinstance(opt.resume, str): 152 | modeldir, _ = self.download_model_artifact(opt) 153 | if modeldir: 154 | self.weights = Path(modeldir) / "last.pt" 155 | config = self.wandb_run.config 156 | opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str( 157 | self.weights), config.save_period, config.total_batch_size, config.bbox_interval, config.epochs, \ 158 | config.opt['hyp'] 159 | data_dict = dict(self.wandb_run.config.data_dict) # eliminates the need for config file to resume 160 | if 'val_artifact' not in self.__dict__: # If --upload_dataset is set, use the existing artifact, don't download 161 | self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'), 162 | opt.artifact_alias) 163 | self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'), 164 | opt.artifact_alias) 165 | self.result_artifact, self.result_table, self.val_table, self.weights = None, None, None, None 166 | if self.train_artifact_path is not None: 167 | train_path = Path(self.train_artifact_path) / 'data/images/' 168 | data_dict['train'] = str(train_path) 169 | if self.val_artifact_path is not None: 170 | val_path = Path(self.val_artifact_path) / 'data/images/' 171 | data_dict['val'] = str(val_path) 172 | self.val_table = self.val_artifact.get("val") 173 | self.map_val_table_path() 174 | wandb.log({"validation dataset": self.val_table}) 175 | 176 | if self.val_artifact is not None: 177 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") 178 | self.result_table = wandb.Table(["epoch", "id", "ground truth", "prediction", "avg_confidence"]) 179 | if opt.bbox_interval == -1: 180 | self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1 181 | return data_dict 182 | 183 | def download_dataset_artifact(self, path, alias): 184 | if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX): 185 | artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias) 186 | dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace("\\","/")) 187 | assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'" 188 | datadir = dataset_artifact.download() 189 | return datadir, dataset_artifact 190 | return None, None 191 | 192 | def download_model_artifact(self, opt): 193 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): 194 | model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest") 195 | assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist' 196 | modeldir = model_artifact.download() 197 | epochs_trained = model_artifact.metadata.get('epochs_trained') 198 | total_epochs = model_artifact.metadata.get('total_epochs') 199 | is_finished = total_epochs is None 200 | assert not is_finished, 'training is finished, can only resume incomplete runs.' 201 | return modeldir, model_artifact 202 | return None, None 203 | 204 | def log_model(self, path, opt, epoch, fitness_score, best_model=False): 205 | model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={ 206 | 'original_url': str(path), 207 | 'epochs_trained': epoch + 1, 208 | 'save period': opt.save_period, 209 | 'project': opt.project, 210 | 'total_epochs': opt.epochs, 211 | 'fitness_score': fitness_score 212 | }) 213 | model_artifact.add_file(str(path / 'last.pt'), name='last.pt') 214 | wandb.log_artifact(model_artifact, 215 | aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else '']) 216 | print("Saving model artifact on epoch ", epoch + 1) 217 | 218 | def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False): 219 | with open(data_file) as f: 220 | data = yaml.safe_load(f) # data dict 221 | check_dataset(data) 222 | nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names']) 223 | names = {k: v for k, v in enumerate(names)} # to index dictionary 224 | self.train_artifact = self.create_dataset_table(LoadImagesAndLabels( 225 | data['train'], rect=True, batch_size=1), names, name='train') if data.get('train') else None 226 | self.val_artifact = self.create_dataset_table(LoadImagesAndLabels( 227 | data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None 228 | if data.get('train'): 229 | data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train') 230 | if data.get('val'): 231 | data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val') 232 | path = data_file if overwrite_config else '_wandb.'.join(data_file.rsplit('.', 1)) # updated data.yaml path 233 | data.pop('download', None) 234 | data.pop('path', None) 235 | with open(path, 'w') as f: 236 | yaml.safe_dump(data, f) 237 | 238 | if self.job_type == 'Training': # builds correct artifact pipeline graph 239 | self.wandb_run.use_artifact(self.val_artifact) 240 | self.wandb_run.use_artifact(self.train_artifact) 241 | self.val_artifact.wait() 242 | self.val_table = self.val_artifact.get('val') 243 | self.map_val_table_path() 244 | else: 245 | self.wandb_run.log_artifact(self.train_artifact) 246 | self.wandb_run.log_artifact(self.val_artifact) 247 | return path 248 | 249 | def map_val_table_path(self): 250 | self.val_table_map = {} 251 | print("Mapping dataset") 252 | for i, data in enumerate(tqdm(self.val_table.data)): 253 | self.val_table_map[data[3]] = data[0] 254 | 255 | def create_dataset_table(self, dataset, class_to_id, name='dataset'): 256 | # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging 257 | artifact = wandb.Artifact(name=name, type="dataset") 258 | img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None 259 | img_files = tqdm(dataset.img_files) if not img_files else img_files 260 | for img_file in img_files: 261 | if Path(img_file).is_dir(): 262 | artifact.add_dir(img_file, name='data/images') 263 | labels_path = 'labels'.join(dataset.path.rsplit('images', 1)) 264 | artifact.add_dir(labels_path, name='data/labels') 265 | else: 266 | artifact.add_file(img_file, name='data/images/' + Path(img_file).name) 267 | label_file = Path(img2label_paths([img_file])[0]) 268 | artifact.add_file(str(label_file), 269 | name='data/labels/' + label_file.name) if label_file.exists() else None 270 | table = wandb.Table(columns=["id", "train_image", "Classes", "name"]) 271 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()]) 272 | for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)): 273 | box_data, img_classes = [], {} 274 | for cls, *xywh in labels[:, 1:].tolist(): 275 | cls = int(cls) 276 | box_data.append({"position": {"middle": [xywh[0], xywh[1]], "width": xywh[2], "height": xywh[3]}, 277 | "class_id": cls, 278 | "box_caption": "%s" % (class_to_id[cls])}) 279 | img_classes[cls] = class_to_id[cls] 280 | boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space 281 | table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), list(img_classes.values()), 282 | Path(paths).name) 283 | artifact.add(table, name) 284 | return artifact 285 | 286 | def log_training_progress(self, predn, path, names): 287 | if self.val_table and self.result_table: 288 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()]) 289 | box_data = [] 290 | total_conf = 0 291 | for *xyxy, conf, cls in predn.tolist(): 292 | if conf >= 0.25: 293 | box_data.append( 294 | {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]}, 295 | "class_id": int(cls), 296 | "box_caption": "%s %.3f" % (names[cls], conf), 297 | "scores": {"class_score": conf}, 298 | "domain": "pixel"}) 299 | total_conf = total_conf + conf 300 | boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space 301 | id = self.val_table_map[Path(path).name] 302 | self.result_table.add_data(self.current_epoch, 303 | id, 304 | self.val_table.data[id][1], 305 | wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set), 306 | total_conf / max(1, len(box_data)) 307 | ) 308 | 309 | def log(self, log_dict): 310 | if self.wandb_run: 311 | for key, value in log_dict.items(): 312 | self.log_dict[key] = value 313 | 314 | def end_epoch(self, best_result=False): 315 | if self.wandb_run: 316 | with all_logging_disabled(): 317 | wandb.log(self.log_dict) 318 | self.log_dict = {} 319 | if self.result_artifact: 320 | self.result_artifact.add(self.result_table, 'result') 321 | wandb.log_artifact(self.result_artifact, aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 322 | ('best' if best_result else '')]) 323 | 324 | wandb.log({"evaluation": self.result_table}) 325 | self.result_table = wandb.Table(["epoch", "id", "ground truth", "prediction", "avg_confidence"]) 326 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") 327 | 328 | def finish_run(self): 329 | if self.wandb_run: 330 | if self.log_dict: 331 | with all_logging_disabled(): 332 | wandb.log(self.log_dict) 333 | wandb.run.finish() 334 | 335 | 336 | @contextmanager 337 | def all_logging_disabled(highest_level=logging.CRITICAL): 338 | """ source - https://gist.github.com/simon-weber/7853144 339 | A context manager that will prevent any logging messages triggered during the body from being processed. 340 | :param highest_level: the maximum logging level in use. 341 | This would only need to be changed if a custom level greater than CRITICAL is defined. 342 | """ 343 | previous_level = logging.root.manager.disable 344 | logging.disable(highest_level) 345 | try: 346 | yield 347 | finally: 348 | logging.disable(previous_level) 349 | -------------------------------------------------------------------------------- /weights/这里存放权重文件.txt: -------------------------------------------------------------------------------- 1 | 这里存放权重文件 2 | 权重地址:https://github.com/ultralytics/yolov5/releases --------------------------------------------------------------------------------