├── .gitignore ├── LICENSE ├── README.md ├── data ├── argoverse_hd.yaml ├── coco.yaml ├── coco128.yaml ├── hyp.finetune.yaml ├── hyp.scratch.yaml ├── images │ ├── 1.jpg │ ├── FDDB.png │ ├── Widerface.jpg │ ├── Yolo5face.png │ ├── bus.jpg │ ├── landmark.png │ ├── pr-curves2.png │ ├── result.jpg │ ├── stem.png │ ├── test.jpg │ ├── yolo5-top.png │ ├── yolo5.png │ └── zidane.jpg ├── retinaface2yolo.py ├── scripts │ ├── get_argoverse_hd.sh │ ├── get_coco.sh │ └── get_voc.sh ├── train2yolo.py ├── val2yolo.py ├── val2yolo_for_test.py ├── voc.yaml └── widerface.yaml ├── detect_face.py ├── export.py ├── hubconf.py ├── models ├── __init__.py ├── blazeface.yaml ├── blazeface_fpn.yaml ├── common.py ├── experimental.py ├── yolo.py ├── yolov5l.yaml ├── yolov5l6.yaml ├── yolov5m.yaml ├── yolov5m6.yaml ├── yolov5n-0.5.yaml ├── yolov5n.yaml ├── yolov5n6.yaml ├── yolov5s.yaml └── yolov5s6.yaml ├── test.py ├── test_widerface.py ├── torch2trt ├── imgs │ ├── yolov5l-face.jpg │ ├── yolov5m-face.jpg │ ├── yolov5n-0.5.jpg │ ├── yolov5n-face.jpg │ └── yolov5s-face.jpg ├── main.py ├── readme.md ├── readme_CN.md ├── sample.jpg ├── speed.py └── trt_model.py ├── train.py ├── utils ├── __init__.py ├── activations.py ├── autoanchor.py ├── aws │ ├── __init__.py │ ├── mime.sh │ ├── resume.py │ └── userdata.sh ├── datasets.py ├── face_datasets.py ├── general.py ├── google_app_engine │ ├── Dockerfile │ ├── additional_requirements.txt │ └── app.yaml ├── google_utils.py ├── infer_utils.py ├── loss.py ├── metrics.py ├── plots.py ├── torch_utils.py └── wandb_logging │ ├── __init__.py │ ├── log_dataset.py │ └── wandb_utils.py ├── weights └── download_weights.sh └── widerface_evaluate ├── README.md ├── bbox.cpython-37m-x86_64-linux-gnu.so ├── bbox.cpython-38-x86_64-linux-gnu.so ├── box_overlaps.c ├── box_overlaps.pyx ├── build ├── temp.linux-x86_64-3.7 │ └── box_overlaps.o └── temp.linux-x86_64-3.8 │ └── box_overlaps.o ├── evaluation.py ├── ground_truth ├── wider_easy_val.mat ├── wider_face_val.mat ├── wider_hard_val.mat └── wider_medium_val.mat └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | */__pycache__ 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## What's New 2 | 3 | **2024.04** [ncnn-android-yolov8-face](https://github.com/derronqi/ncnn-android-yolov8-face) 4 | 5 | **2023.04** [yolov8-face](https://github.com/derronqi/yolov8-face) (🔥🔥🔥↑) 6 | 7 | **2022.10** [yolov7-face](https://github.com/derronqi/yolov7-face) (🔥🔥🔥↑) 8 | 9 | 10 | **2022.8**: yolov7 11 | 12 | | Method | Test Size | Easy | Medium | Hard | FLOPs (B) @640 | 13 | | -----------------| ---------- | ----- | ------ | ----- | -------------- | 14 | | yolov7-lite-t | 640 | 88.7 | 85.2 | 71.5 | 0.8 | 15 | | yolov7-lite-s | 640 | 92.7 | 89.9 | 78.5 | 3.0 | 16 | | yolov7-tiny | 640 | 94.7 | 92.6 | 82.1 | 13.2 | 17 | | yolov7s | 640 | 94.8 | 93.1 | 85.2 | 16.8 | 18 | | yolov7 | 640 | 96.9 | 95.5 | 88.0 | 103.4 | 19 | | yolov7+TTA | 640 | 97.2 | 95.8 | 87.7 | 103.4 | 20 | 21 | 22 | **2021.12**: Yolov5-face to TensorRT. 23 | 24 | | Backbone | Pytorch(ms) | TensorRT_FP16(ms) | 25 | | :----------: | :---------: | :---------------: | 26 | | yolov5n-0.5 | 7.7 | 2.1 | 27 | | yolov5n-face | 7.7 | 2.4 | 28 | | yolov5s-face | 5.6 | 2.2 | 29 | | yolov5m-face | 9.9 | 3.3 | 30 | | yolov5l-face | 15.9 | 4.5 | 31 | 32 | > Pytorch=1.10.0+cu102 TensorRT=8.2.0.6 Hardware=rtx2080ti 33 | 34 | **2021.11**: BlazeFace 35 | 36 | | Method | multi scale | Easy | Medium | Hard | Model Size(MB) | Link | 37 | | -------------------- | ----------- | ----- | ------ | ----- | -------------- | ----- | 38 | | BlazeFace | Ture | 88.5 | 85.5 | 73.1 | 0.472 | https://github.com/PaddlePaddle/PaddleDetection | 39 | | BlazeFace-FPN-SSH | Ture | 90.7 | 88.3 | 79.3 | 0.479 | https://github.com/PaddlePaddle/PaddleDetection | 40 | | yolov5-blazeface | True | 90.4 | 88.7 | 78.0 | 0.493 | https://pan.baidu.com/s/1RHp8wa615OuDVhsO-qrMpQ pwd:r3v3 https://drive.google.com/file/d/1adi6ke2vCLQFcpbvFqWo_J4wZIfPqSMG| 41 | | yolov5-blazeface-fpn | True | 90.8 | 89.4 | 79.1 | 0.493 | - | 42 | 43 | 44 | **2021.08**: Add new training dataset [Multi-Task-Facial](https://drive.google.com/file/d/1Pwd6ga06cDjeOX20RSC1KWiT888Q9IpM/view?usp=sharing),improve large face detection. 45 | | Method | Easy | Medium | Hard | 46 | | -------------------- | ----- | ------ | ----- | 47 | | ***YOLOv5s*** | 94.56 | 92.92 | 83.84 | 48 | | ***YOLOv5m*** | 95.46 | 93.87 | 85.54 | 49 | 50 | **QQ Group**: 1164802745 51 | 52 | ## Introduction 53 | 54 | Yolov5-face is a real-time,high accuracy face detection. 55 | 56 | ![](data/images/yolov5-face-p6.png) 57 | 58 | ## Performance 59 | 60 | Single Scale Inference on VGA resolution(max side is equal to 640 and scale). 61 | 62 | ***Large family*** 63 | 64 | | Method | Backbone | Easy | Medium | Hard | \#Params(M) | \#Flops(G) | 65 | | :------------------ | -------------- | ----- | ------ | ----- | ----------- | ---------- | 66 | | DSFD (CVPR19) | ResNet152 | 94.29 | 91.47 | 71.39 | 120.06 | 259.55 | 67 | | RetinaFace (CVPR20) | ResNet50 | 94.92 | 91.90 | 64.17 | 29.50 | 37.59 | 68 | | HAMBox (CVPR20) | ResNet50 | 95.27 | 93.76 | 76.75 | 30.24 | 43.28 | 69 | | TinaFace (Arxiv20) | ResNet50 | 95.61 | 94.25 | 81.43 | 37.98 | 172.95 | 70 | | SCRFD-34GF(Arxiv21) | Bottleneck Res | 96.06 | 94.92 | 85.29 | 9.80 | 34.13 | 71 | | SCRFD-10GF(Arxiv21) | Basic Res | 95.16 | 93.87 | 83.05 | 3.86 | 9.98 | 72 | | - | - | - | - | - | - | - | 73 | | ***YOLOv5s*** | CSPNet | 94.67 | 92.75 | 83.03 | 7.075 | 5.751 | 74 | | **YOLOv5s6** | CSPNet | 95.48 | 93.66 | 82.8 | 12.386 | 6.280 | 75 | | ***YOLOv5m*** | CSPNet | 95.30 | 93.76 | 85.28 | 21.063 | 18.146 | 76 | | **YOLOv5m6** | CSPNet | 95.66 | 94.1 | 85.2 | 35.485 | 19.773 | 77 | | ***YOLOv5l*** | CSPNet | 95.78 | 94.30 | 86.13 | 46.627 | 41.607 | 78 | | ***YOLOv5l6*** | CSPNet | 96.38 | 94.90 | 85.88 | 76.674 | 45.279 | 79 | 80 | 81 | ***Small family*** 82 | 83 | | Method | Backbone | Easy | Medium | Hard | \#Params(M) | \#Flops(G) | 84 | | -------------------- | --------------- | ----- | ------ | ----- | ----------- | ---------- | 85 | | RetinaFace (CVPR20 | MobileNet0.25 | 87.78 | 81.16 | 47.32 | 0.44 | 0.802 | 86 | | FaceBoxes (IJCB17) | | 76.17 | 57.17 | 24.18 | 1.01 | 0.275 | 87 | | SCRFD-0.5GF(Arxiv21) | Depth-wise Conv | 90.57 | 88.12 | 68.51 | 0.57 | 0.508 | 88 | | SCRFD-2.5GF(Arxiv21) | Basic Res | 93.78 | 92.16 | 77.87 | 0.67 | 2.53 | 89 | | - | - | - | - | - | - | - | 90 | | ***YOLOv5n*** | ShuffleNetv2 | 93.74 | 91.54 | 80.32 | 1.726 | 2.111 | 91 | | ***YOLOv5n-0.5*** | ShuffleNetv2 | 90.76 | 88.12 | 73.82 | 0.447 | 0.571 | 92 | 93 | 94 | 95 | ## Pretrained-Models 96 | 97 | | Name | Easy | Medium | Hard | FLOPs(G) | Params(M) | Link | 98 | | ----------- | ----- | ------ | ----- | -------- | --------- | ------------------------------------------------------------ | 99 | | yolov5n-0.5 | 90.76 | 88.12 | 73.82 | 0.571 | 0.447 | Link: https://pan.baidu.com/s/1UgiKwzFq5NXI2y-Zui1kiA pwd: s5ow, https://drive.google.com/file/d/1XJ8w55Y9Po7Y5WP4X1Kg1a77ok2tL_KY/view?usp=sharing | 100 | | yolov5n | 93.61 | 91.52 | 80.53 | 2.111 | 1.726 | Link: https://pan.baidu.com/s/1xsYns6cyB84aPDgXB7sNDQ pwd: lw9j,https://drive.google.com/file/d/18oenL6tjFkdR1f5IgpYeQfDFqU4w3jEr/view?usp=sharing | 101 | | yolov5s | 94.33 | 92.61 | 83.15 | 5.751 | 7.075 | Link: https://pan.baidu.com/s/1fyzLxZYx7Ja1_PCIWRhxbw Link: eq0q,https://drive.google.com/file/d/1zxaHeLDyID9YU4-hqK7KNepXIwbTkRIO/view?usp=sharing | 102 | | yolov5m | 95.30 | 93.76 | 85.28 | 18.146 | 21.063 | Link: https://pan.baidu.com/s/1oePvd2K6R4-gT0g7EERmdQ pwd: jmtk, https://drive.google.com/file/d/1Sx-KEGXSxvPMS35JhzQKeRBiqC98VDDI | 103 | | yolov5l | 95.78 | 94.30 | 86.13 | 41.607 | 46.627 | Link: https://pan.baidu.com/s/11l4qSEgA2-c7e8lpRt8iFw pwd: 0mq7, https://drive.google.com/file/d/16F-3AjdQBn9p3nMhStUxfDNAE_1bOF_r | 104 | 105 | ## Data preparation 106 | 107 | 1. Download WIDERFace datasets. 108 | 2. Download annotation files from [google drive](https://drive.google.com/file/d/1tU_IjyOwGQfGNUvZGwWWM4SwxKp2PUQ8/view?usp=sharing). 109 | 110 | ```shell 111 | cd data 112 | python3 train2yolo.py /path/to/original/widerface/train [/path/to/save/widerface/train] 113 | python3 val2yolo.py /path/to/original/widerface [/path/to/save/widerface/val] 114 | ``` 115 | 116 | 117 | 118 | ## Training 119 | 120 | ```shell 121 | CUDA_VISIBLE_DEVICES="0,1,2,3" python3 train.py --data data/widerface.yaml --cfg models/yolov5s.yaml --weights 'pretrained models' 122 | ``` 123 | 124 | 125 | 126 | ## WIDERFace Evaluation 127 | 128 | ```shell 129 | python3 test_widerface.py --weights 'your test model' --img-size 640 130 | 131 | cd widerface_evaluate 132 | python3 evaluation.py 133 | ``` 134 | 135 | #### Test 136 | 137 | ![](data/images/result.jpg) 138 | 139 | #### Landmark Visulization 140 | 141 | ![](data/images/landmark.png) 142 | First row: RetinaFace, 2nd row: YOLOv5m-Face 143 | **YOLO5Face was used in the 3rd place standard face recogntion track of the [ICCV2021 Masked Face Recognition Challenge](https://www.face-benchmark.org/challenge.html).** 144 | 145 | 146 | #### AXera demo 147 | 148 | https://github.com/AXERA-TECH/ax-samples/blob/main/examples/ax_yolov5s_face_steps.cc 149 | 150 | #### Android demo 151 | 152 | https://github.com/FeiGeChuanShu/ncnn_Android_face/tree/main/ncnn-android-yolov5_face 153 | 154 | #### OpenCV DNN demo 155 | 156 | https://github.com/hpc203/yolov5-face-landmarks-opencv-v2 157 | 158 | #### ONNXRuntime/MNN/TNN/NCNN C++ demo 159 | 160 | https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/ort/cv/yolo5face.cpp 161 | 162 | https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/mnn/cv/mnn_yolo5face.cpp 163 | 164 | https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/tnn/cv/tnn_yolo5face.cpp 165 | 166 | https://github.com/DefTruth/lite.ai.toolkit/blob/main/lite/ncnn/cv/ncnn_yolo5face.cpp 167 | 168 | #### References 169 | 170 | https://github.com/ultralytics/yolov5 171 | 172 | https://github.com/DayBreak-u/yolo-face-with-landmark 173 | 174 | https://github.com/xialuxi/yolov5_face_landmark 175 | 176 | https://github.com/biubug6/Pytorch_Retinaface 177 | 178 | https://github.com/deepinsight/insightface 179 | 180 | 181 | #### Citation 182 | - If you think this work is useful for you, please cite 183 | 184 | @article{YOLO5Face, 185 | title = {YOLO5Face: Why Reinventing a Face Detector}, 186 | author = {Delong Qi and Weijun Tan and Qi Yao and Jingfeng Liu}, 187 | booktitle = {ArXiv preprint ArXiv:2105.12931}, 188 | year = {2021} 189 | } 190 | 191 | -------------------------------------------------------------------------------- /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_folder 5 | # /argoverse 6 | # /yolov5 7 | 8 | 9 | # download command/URL (optional) 10 | download: bash data/scripts/get_argoverse_hd.sh 11 | 12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/] 13 | train: ../argoverse/Argoverse-1.1/images/train/ # 39384 images 14 | val: ../argoverse/Argoverse-1.1/images/val/ # 15062 iamges 15 | test: ../argoverse/Argoverse-1.1/images/test/ # Submit to: https://eval.ai/web/challenges/challenge-page/800/overview 16 | 17 | # number of classes 18 | nc: 8 19 | 20 | # class names 21 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'bus', 'truck', 'traffic_light', 'stop_sign' ] 22 | -------------------------------------------------------------------------------- /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_folder 5 | # /coco 6 | # /yolov5 7 | 8 | 9 | # download command/URL (optional) 10 | download: bash data/scripts/get_coco.sh 11 | 12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/] 13 | train: ../coco/train2017.txt # 118287 images 14 | val: ../coco/val2017.txt # 5000 images 15 | test: ../coco/test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794 16 | 17 | # number of classes 18 | nc: 80 19 | 20 | # class names 21 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 22 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 23 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 24 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 25 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 26 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 27 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 28 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 29 | 'hair drier', 'toothbrush' ] 30 | 31 | # Print classes 32 | # with open('data/coco.yaml') as f: 33 | # d = yaml.load(f, Loader=yaml.FullLoader) # dict 34 | # for i, x in enumerate(d['names']): 35 | # print(i, x) 36 | -------------------------------------------------------------------------------- /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_folder 5 | # /coco128 6 | # /yolov5 7 | 8 | 9 | # download command/URL (optional) 10 | download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip 11 | 12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/] 13 | train: ../coco128/images/train2017/ # 128 images 14 | val: ../coco128/images/train2017/ # 128 images 15 | 16 | # number of classes 17 | nc: 80 18 | 19 | # class names 20 | names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 21 | 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 22 | 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 23 | 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 24 | 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 25 | 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 26 | 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 27 | 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 28 | 'hair drier', 'toothbrush' ] 29 | -------------------------------------------------------------------------------- /data/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/hyp.scratch.yaml: -------------------------------------------------------------------------------- 1 | # Hyperparameters for COCO training from scratch 2 | # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300 3 | # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials 4 | 5 | 6 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3) 7 | lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf) 8 | momentum: 0.937 # SGD momentum/Adam beta1 9 | weight_decay: 0.0005 # optimizer weight decay 5e-4 10 | warmup_epochs: 3.0 # warmup epochs (fractions ok) 11 | warmup_momentum: 0.8 # warmup initial momentum 12 | warmup_bias_lr: 0.1 # warmup initial bias lr 13 | box: 0.05 # box loss gain 14 | cls: 0.5 # cls loss gain 15 | landmark: 0.005 # landmark loss gain 16 | cls_pw: 1.0 # cls BCELoss positive_weight 17 | obj: 1.0 # obj loss gain (scale with pixels) 18 | obj_pw: 1.0 # obj BCELoss positive_weight 19 | iou_t: 0.20 # IoU training threshold 20 | anchor_t: 4.0 # anchor-multiple threshold 21 | # anchors: 3 # anchors per output layer (0 to ignore) 22 | fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5) 23 | hsv_h: 0.015 # image HSV-Hue augmentation (fraction) 24 | hsv_s: 0.7 # image HSV-Saturation augmentation (fraction) 25 | hsv_v: 0.4 # image HSV-Value augmentation (fraction) 26 | degrees: 0.0 # image rotation (+/- deg) 27 | translate: 0.1 # image translation (+/- fraction) 28 | scale: 0.5 # image scale (+/- gain) 29 | shear: 0.5 # image shear (+/- deg) 30 | perspective: 0.0 # image perspective (+/- fraction), range 0-0.001 31 | flipud: 0.0 # image flip up-down (probability) 32 | fliplr: 0.5 # image flip left-right (probability) 33 | mosaic: 0.5 # image mosaic (probability) 34 | mixup: 0.0 # image mixup (probability) 35 | -------------------------------------------------------------------------------- /data/images/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/1.jpg -------------------------------------------------------------------------------- /data/images/FDDB.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/FDDB.png -------------------------------------------------------------------------------- /data/images/Widerface.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/Widerface.jpg -------------------------------------------------------------------------------- /data/images/Yolo5face.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/Yolo5face.png -------------------------------------------------------------------------------- /data/images/bus.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/bus.jpg -------------------------------------------------------------------------------- /data/images/landmark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/landmark.png -------------------------------------------------------------------------------- /data/images/pr-curves2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/pr-curves2.png -------------------------------------------------------------------------------- /data/images/result.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/result.jpg -------------------------------------------------------------------------------- /data/images/stem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/stem.png -------------------------------------------------------------------------------- /data/images/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/test.jpg -------------------------------------------------------------------------------- /data/images/yolo5-top.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/yolo5-top.png -------------------------------------------------------------------------------- /data/images/yolo5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/yolo5.png -------------------------------------------------------------------------------- /data/images/zidane.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/data/images/zidane.jpg -------------------------------------------------------------------------------- /data/retinaface2yolo.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path 3 | import sys 4 | import torch 5 | import torch.utils.data as data 6 | import cv2 7 | import numpy as np 8 | 9 | class WiderFaceDetection(data.Dataset): 10 | def __init__(self, txt_path, preproc=None): 11 | self.preproc = preproc 12 | self.imgs_path = [] 13 | self.words = [] 14 | f = open(txt_path,'r') 15 | lines = f.readlines() 16 | isFirst = True 17 | labels = [] 18 | for line in lines: 19 | line = line.rstrip() 20 | if line.startswith('#'): 21 | if isFirst is True: 22 | isFirst = False 23 | else: 24 | labels_copy = labels.copy() 25 | self.words.append(labels_copy) 26 | labels.clear() 27 | path = line[2:] 28 | path = txt_path.replace('label.txt','images/') + path 29 | self.imgs_path.append(path) 30 | else: 31 | line = line.split(' ') 32 | label = [float(x) for x in line] 33 | labels.append(label) 34 | 35 | self.words.append(labels) 36 | 37 | def __len__(self): 38 | return len(self.imgs_path) 39 | 40 | def __getitem__(self, index): 41 | img = cv2.imread(self.imgs_path[index]) 42 | height, width, _ = img.shape 43 | 44 | labels = self.words[index] 45 | annotations = np.zeros((0, 15)) 46 | if len(labels) == 0: 47 | return annotations 48 | for idx, label in enumerate(labels): 49 | annotation = np.zeros((1, 15)) 50 | # bbox 51 | annotation[0, 0] = label[0] # x1 52 | annotation[0, 1] = label[1] # y1 53 | annotation[0, 2] = label[0] + label[2] # x2 54 | annotation[0, 3] = label[1] + label[3] # y2 55 | 56 | # landmarks 57 | annotation[0, 4] = label[4] # l0_x 58 | annotation[0, 5] = label[5] # l0_y 59 | annotation[0, 6] = label[7] # l1_x 60 | annotation[0, 7] = label[8] # l1_y 61 | annotation[0, 8] = label[10] # l2_x 62 | annotation[0, 9] = label[11] # l2_y 63 | annotation[0, 10] = label[13] # l3_x 64 | annotation[0, 11] = label[14] # l3_y 65 | annotation[0, 12] = label[16] # l4_x 66 | annotation[0, 13] = label[17] # l4_y 67 | if (annotation[0, 4]<0): 68 | annotation[0, 14] = -1 69 | else: 70 | annotation[0, 14] = 1 71 | 72 | annotations = np.append(annotations, annotation, axis=0) 73 | target = np.array(annotations) 74 | if self.preproc is not None: 75 | img, target = self.preproc(img, target) 76 | 77 | return torch.from_numpy(img), target 78 | 79 | def detection_collate(batch): 80 | """Custom collate fn for dealing with batches of images that have a different 81 | number of associated object annotations (bounding boxes). 82 | 83 | Arguments: 84 | batch: (tuple) A tuple of tensor images and lists of annotations 85 | 86 | Return: 87 | A tuple containing: 88 | 1) (tensor) batch of images stacked on their 0 dim 89 | 2) (list of tensors) annotations for a given image are stacked on 0 dim 90 | """ 91 | targets = [] 92 | imgs = [] 93 | for _, sample in enumerate(batch): 94 | for _, tup in enumerate(sample): 95 | if torch.is_tensor(tup): 96 | imgs.append(tup) 97 | elif isinstance(tup, type(np.empty(0))): 98 | annos = torch.from_numpy(tup).float() 99 | targets.append(annos) 100 | 101 | return (torch.stack(imgs, 0), targets) 102 | 103 | save_path = '/ssd_1t/derron/yolov5-face/data/widerface/train' 104 | aa=WiderFaceDetection("/ssd_1t/derron/yolov5-face/data/widerface/widerface/train/label.txt") 105 | for i in range(len(aa.imgs_path)): 106 | print(i, aa.imgs_path[i]) 107 | img = cv2.imread(aa.imgs_path[i]) 108 | base_img = os.path.basename(aa.imgs_path[i]) 109 | base_txt = os.path.basename(aa.imgs_path[i])[:-4] +".txt" 110 | save_img_path = os.path.join(save_path, base_img) 111 | save_txt_path = os.path.join(save_path, base_txt) 112 | with open(save_txt_path, "w") as f: 113 | height, width, _ = img.shape 114 | labels = aa.words[i] 115 | annotations = np.zeros((0, 14)) 116 | if len(labels) == 0: 117 | continue 118 | for idx, label in enumerate(labels): 119 | annotation = np.zeros((1, 14)) 120 | # bbox 121 | label[0] = max(0, label[0]) 122 | label[1] = max(0, label[1]) 123 | label[2] = min(width - 1, label[2]) 124 | label[3] = min(height - 1, label[3]) 125 | annotation[0, 0] = (label[0] + label[2] / 2) / width # cx 126 | annotation[0, 1] = (label[1] + label[3] / 2) / height # cy 127 | annotation[0, 2] = label[2] / width # w 128 | annotation[0, 3] = label[3] / height # h 129 | #if (label[2] -label[0]) < 8 or (label[3] - label[1]) < 8: 130 | # img[int(label[1]):int(label[3]), int(label[0]):int(label[2])] = 127 131 | # continue 132 | # landmarks 133 | annotation[0, 4] = label[4] / width # l0_x 134 | annotation[0, 5] = label[5] / height # l0_y 135 | annotation[0, 6] = label[7] / width # l1_x 136 | annotation[0, 7] = label[8] / height # l1_y 137 | annotation[0, 8] = label[10] / width # l2_x 138 | annotation[0, 9] = label[11] / height # l2_y 139 | annotation[0, 10] = label[13] / width # l3_x 140 | annotation[0, 11] = label[14] / height # l3_y 141 | annotation[0, 12] = label[16] / width # l4_x 142 | annotation[0, 13] = label[17] / height # l4_y 143 | str_label="0 " 144 | for i in range(len(annotation[0])): 145 | str_label =str_label+" "+str(annotation[0][i]) 146 | str_label = str_label.replace('[', '').replace(']', '') 147 | str_label = str_label.replace(',', '') + '\n' 148 | f.write(str_label) 149 | cv2.imwrite(save_img_path, img) 150 | 151 | -------------------------------------------------------------------------------- /data/scripts/get_argoverse_hd.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ 3 | # Download command: bash data/scripts/get_argoverse_hd.sh 4 | # Train command: python train.py --data argoverse_hd.yaml 5 | # Default dataset location is next to /yolov5: 6 | # /parent_folder 7 | # /argoverse 8 | # /yolov5 9 | 10 | # Download/unzip images 11 | d='../argoverse/' # unzip directory 12 | mkdir $d 13 | url=https://argoverse-hd.s3.us-east-2.amazonaws.com/ 14 | f=Argoverse-HD-Full.zip 15 | curl -L $url$f -o $f && unzip -q $f -d $d && rm $f &# download, unzip, remove in background 16 | wait # finish background tasks 17 | 18 | cd ../argoverse/Argoverse-1.1/ 19 | ln -s tracking images 20 | 21 | cd ../Argoverse-HD/annotations/ 22 | 23 | python3 - "$@" <train.txt 91 | cat 2007_train.txt 2007_val.txt 2007_test.txt 2012_train.txt 2012_val.txt >train.all.txt 92 | 93 | python3 - "$@" < 3: 111 | print('Too many arguments were provided.') 112 | print('Run command: python3 train2yolo.py /path/to/original/widerface/train [/path/to/save/widerface/train]') 113 | exit(1) 114 | original_path = sys.argv[1] 115 | 116 | if len(sys.argv) == 2: 117 | if not os.path.isdir('widerface'): 118 | os.mkdir('widerface') 119 | if not os.path.isdir('widerface/train'): 120 | os.mkdir('widerface/train') 121 | 122 | save_path = 'widerface/train' 123 | else: 124 | save_path = sys.argv[2] 125 | 126 | if not os.path.isfile(os.path.join(original_path, 'label.txt')): 127 | print('Missing label.txt file.') 128 | exit(1) 129 | 130 | aa = WiderFaceDetection(os.path.join(original_path, 'label.txt')) 131 | 132 | for i in range(len(aa.imgs_path)): 133 | print(i, aa.imgs_path[i]) 134 | img = cv2.imread(aa.imgs_path[i]) 135 | base_img = os.path.basename(aa.imgs_path[i]) 136 | base_txt = os.path.basename(aa.imgs_path[i])[:-4] + ".txt" 137 | save_img_path = os.path.join(save_path, base_img) 138 | save_txt_path = os.path.join(save_path, base_txt) 139 | with open(save_txt_path, "w") as f: 140 | height, width, _ = img.shape 141 | labels = aa.words[i] 142 | annotations = np.zeros((0, 14)) 143 | if len(labels) == 0: 144 | continue 145 | for idx, label in enumerate(labels): 146 | annotation = np.zeros((1, 14)) 147 | # bbox 148 | label[0] = max(0, label[0]) 149 | label[1] = max(0, label[1]) 150 | label[2] = min(width - 1, label[2]) 151 | label[3] = min(height - 1, label[3]) 152 | annotation[0, 0] = (label[0] + label[2] / 2) / width # cx 153 | annotation[0, 1] = (label[1] + label[3] / 2) / height # cy 154 | annotation[0, 2] = label[2] / width # w 155 | annotation[0, 3] = label[3] / height # h 156 | #if (label[2] -label[0]) < 8 or (label[3] - label[1]) < 8: 157 | # img[int(label[1]):int(label[3]), int(label[0]):int(label[2])] = 127 158 | # continue 159 | # landmarks 160 | annotation[0, 4] = label[4] / width # l0_x 161 | annotation[0, 5] = label[5] / height # l0_y 162 | annotation[0, 6] = label[7] / width # l1_x 163 | annotation[0, 7] = label[8] / height # l1_y 164 | annotation[0, 8] = label[10] / width # l2_x 165 | annotation[0, 9] = label[11] / height # l2_y 166 | annotation[0, 10] = label[13] / width # l3_x 167 | annotation[0, 11] = label[14] / height # l3_y 168 | annotation[0, 12] = label[16] / width # l4_x 169 | annotation[0, 13] = label[17] / height # l4_y 170 | str_label = "0 " 171 | for i in range(len(annotation[0])): 172 | str_label = str_label + " " + str(annotation[0][i]) 173 | str_label = str_label.replace('[', '').replace(']', '') 174 | str_label = str_label.replace(',', '') + '\n' 175 | f.write(str_label) 176 | cv2.imwrite(save_img_path, img) 177 | -------------------------------------------------------------------------------- /data/val2yolo.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import numpy as np 4 | import shutil 5 | import sys 6 | from tqdm import tqdm 7 | 8 | 9 | def xywh2xxyy(box): 10 | x1 = box[0] 11 | y1 = box[1] 12 | x2 = box[0] + box[2] 13 | y2 = box[1] + box[3] 14 | return x1, x2, y1, y2 15 | 16 | 17 | def convert(size, box): 18 | dw = 1. / (size[0]) 19 | dh = 1. / (size[1]) 20 | x = (box[0] + box[1]) / 2.0 - 1 21 | y = (box[2] + box[3]) / 2.0 - 1 22 | w = box[1] - box[0] 23 | h = box[3] - box[2] 24 | x = x * dw 25 | w = w * dw 26 | y = y * dh 27 | h = h * dh 28 | return x, y, w, h 29 | 30 | 31 | def wider2face(root, phase='val', ignore_small=0): 32 | data = {} 33 | with open('{}/{}/label.txt'.format(root, phase), 'r') as f: 34 | lines = f.readlines() 35 | for line in tqdm(lines): 36 | line = line.strip() 37 | if '#' in line: 38 | path = '{}/{}/images/{}'.format(root, phase, line.split()[-1]) 39 | img = cv2.imread(path) 40 | height, width, _ = img.shape 41 | data[path] = list() 42 | else: 43 | box = np.array(line.split()[0:4], dtype=np.float32) # (x1,y1,w,h) 44 | if box[2] < ignore_small or box[3] < ignore_small: 45 | continue 46 | box = convert((width, height), xywh2xxyy(box)) 47 | label = '0 {} {} {} {} -1 -1 -1 -1 -1 -1 -1 -1 -1 -1'.format(round(box[0], 4), round(box[1], 4), 48 | round(box[2], 4), round(box[3], 4)) 49 | data[path].append(label) 50 | return data 51 | 52 | 53 | if __name__ == '__main__': 54 | if len(sys.argv) == 1: 55 | print('Missing path to WIDERFACE folder.') 56 | print('Run command: python3 val2yolo.py /path/to/original/widerface [/path/to/save/widerface/val]') 57 | exit(1) 58 | elif len(sys.argv) > 3: 59 | print('Too many arguments were provided.') 60 | print('Run command: python3 val2yolo.py /path/to/original/widerface [/path/to/save/widerface/val]') 61 | exit(1) 62 | 63 | root_path = sys.argv[1] 64 | if not os.path.isfile(os.path.join(root_path, 'val', 'label.txt')): 65 | print('Missing label.txt file.') 66 | exit(1) 67 | 68 | if len(sys.argv) == 2: 69 | if not os.path.isdir('widerface'): 70 | os.mkdir('widerface') 71 | if not os.path.isdir('widerface/val'): 72 | os.mkdir('widerface/val') 73 | 74 | save_path = 'widerface/val' 75 | else: 76 | save_path = sys.argv[2] 77 | 78 | datas = wider2face(root_path, phase='val') 79 | for idx, data in enumerate(datas.keys()): 80 | pict_name = os.path.basename(data) 81 | out_img = f'{save_path}/{idx}.jpg' 82 | out_txt = f'{save_path}/{idx}.txt' 83 | shutil.copyfile(data, out_img) 84 | labels = datas[data] 85 | f = open(out_txt, 'w') 86 | for label in labels: 87 | f.write(label + '\n') 88 | f.close() 89 | -------------------------------------------------------------------------------- /data/val2yolo_for_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import numpy as np 4 | import shutil 5 | from tqdm import tqdm 6 | 7 | root = '/ssd_1t/derron/WiderFace' 8 | 9 | 10 | def xywh2xxyy(box): 11 | x1 = box[0] 12 | y1 = box[1] 13 | x2 = box[0] + box[2] 14 | y2 = box[1] + box[3] 15 | return (x1, x2, y1, y2) 16 | 17 | 18 | def convert(size, box): 19 | dw = 1. / (size[0]) 20 | dh = 1. / (size[1]) 21 | x = (box[0] + box[1]) / 2.0 - 1 22 | y = (box[2] + box[3]) / 2.0 - 1 23 | w = box[1] - box[0] 24 | h = box[3] - box[2] 25 | x = x * dw 26 | w = w * dw 27 | y = y * dh 28 | h = h * dh 29 | return (x, y, w, h) 30 | 31 | 32 | def wider2face(phase='val', ignore_small=0): 33 | data = {} 34 | with open('{}/{}/label.txt'.format(root, phase), 'r') as f: 35 | lines = f.readlines() 36 | for line in tqdm(lines): 37 | line = line.strip() 38 | if '#' in line: 39 | path = '{}/{}/images/{}'.format(root, phase, os.path.basename(line)) 40 | img = cv2.imread(path) 41 | height, width, _ = img.shape 42 | data[path] = list() 43 | else: 44 | box = np.array(line.split()[0:4], dtype=np.float32) # (x1,y1,w,h) 45 | if box[2] < ignore_small or box[3] < ignore_small: 46 | continue 47 | box = convert((width, height), xywh2xxyy(box)) 48 | label = '0 {} {} {} {} -1 -1 -1 -1 -1 -1 -1 -1 -1 -1'.format(round(box[0], 4), round(box[1], 4), 49 | round(box[2], 4), round(box[3], 4)) 50 | data[path].append(label) 51 | return data 52 | 53 | 54 | if __name__ == '__main__': 55 | datas = wider2face('val') 56 | for idx, data in enumerate(datas.keys()): 57 | pict_name = os.path.basename(data) 58 | out_img = 'widerface/val/images/{}'.format(pict_name) 59 | out_txt = 'widerface/val/labels/{}.txt'.format(os.path.splitext(pict_name)[0]) 60 | shutil.copyfile(data, out_img) 61 | labels = datas[data] 62 | f = open(out_txt, 'w') 63 | for label in labels: 64 | f.write(label + '\n') 65 | f.close() 66 | -------------------------------------------------------------------------------- /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_folder 5 | # /VOC 6 | # /yolov5 7 | 8 | 9 | # download command/URL (optional) 10 | download: bash data/scripts/get_voc.sh 11 | 12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/] 13 | train: ../VOC/images/train/ # 16551 images 14 | val: ../VOC/images/val/ # 4952 images 15 | 16 | # number of classes 17 | nc: 20 18 | 19 | # class names 20 | names: [ 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 21 | 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor' ] 22 | -------------------------------------------------------------------------------- /data/widerface.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_folder 5 | # /VOC 6 | # /yolov5 7 | 8 | 9 | # download command/URL (optional) 10 | download: bash data/scripts/get_voc.sh 11 | 12 | # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/] 13 | train: /ssd_1t/derron/yolov5-face/data/widerface/train # 16551 images 14 | val: /ssd_1t/derron/yolov5-face/data/widerface/val # 16551 images 15 | #val: /ssd_1t/derron/yolov5-face/data/widerface/train/ # 4952 images 16 | 17 | # number of classes 18 | nc: 1 19 | 20 | # class names 21 | names: [ 'face'] 22 | -------------------------------------------------------------------------------- /detect_face.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | import argparse 3 | import time 4 | from pathlib import Path 5 | import sys 6 | import os 7 | 8 | import numpy as np 9 | import cv2 10 | import torch 11 | import torch.backends.cudnn as cudnn 12 | from numpy import random 13 | import copy 14 | 15 | FILE = Path(__file__).resolve() 16 | ROOT = FILE.parents[0] # YOLOv5 root directory 17 | if str(ROOT) not in sys.path: 18 | sys.path.append(str(ROOT)) # add ROOT to PATH 19 | ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative 20 | 21 | from models.experimental import attempt_load 22 | from utils.datasets import letterbox, img_formats, vid_formats, LoadImages, LoadStreams 23 | from utils.general import check_img_size, non_max_suppression_face, apply_classifier, scale_coords, xyxy2xywh, \ 24 | strip_optimizer, set_logging, increment_path 25 | from utils.plots import plot_one_box 26 | from utils.torch_utils import select_device, load_classifier, time_synchronized 27 | 28 | 29 | def load_model(weights, device): 30 | model = attempt_load(weights, map_location=device) # load FP32 model 31 | return model 32 | 33 | 34 | def scale_coords_landmarks(img1_shape, coords, img0_shape, ratio_pad=None): 35 | # Rescale coords (xyxy) from img1_shape to img0_shape 36 | if ratio_pad is None: # calculate from img0_shape 37 | gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new 38 | pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding 39 | else: 40 | gain = ratio_pad[0][0] 41 | pad = ratio_pad[1] 42 | 43 | coords[:, [0, 2, 4, 6, 8]] -= pad[0] # x padding 44 | coords[:, [1, 3, 5, 7, 9]] -= pad[1] # y padding 45 | coords[:, :10] /= gain 46 | #clip_coords(coords, img0_shape) 47 | coords[:, 0].clamp_(0, img0_shape[1]) # x1 48 | coords[:, 1].clamp_(0, img0_shape[0]) # y1 49 | coords[:, 2].clamp_(0, img0_shape[1]) # x2 50 | coords[:, 3].clamp_(0, img0_shape[0]) # y2 51 | coords[:, 4].clamp_(0, img0_shape[1]) # x3 52 | coords[:, 5].clamp_(0, img0_shape[0]) # y3 53 | coords[:, 6].clamp_(0, img0_shape[1]) # x4 54 | coords[:, 7].clamp_(0, img0_shape[0]) # y4 55 | coords[:, 8].clamp_(0, img0_shape[1]) # x5 56 | coords[:, 9].clamp_(0, img0_shape[0]) # y5 57 | return coords 58 | 59 | def show_results(img, xyxy, conf, landmarks, class_num): 60 | h,w,c = img.shape 61 | tl = 1 or round(0.002 * (h + w) / 2) + 1 # line/font thickness 62 | x1 = int(xyxy[0]) 63 | y1 = int(xyxy[1]) 64 | x2 = int(xyxy[2]) 65 | y2 = int(xyxy[3]) 66 | img = img.copy() 67 | 68 | cv2.rectangle(img, (x1,y1), (x2, y2), (0,255,0), thickness=tl, lineType=cv2.LINE_AA) 69 | 70 | clors = [(255,0,0),(0,255,0),(0,0,255),(255,255,0),(0,255,255)] 71 | 72 | for i in range(5): 73 | point_x = int(landmarks[2 * i]) 74 | point_y = int(landmarks[2 * i + 1]) 75 | cv2.circle(img, (point_x, point_y), tl+1, clors[i], -1) 76 | 77 | tf = max(tl - 1, 1) # font thickness 78 | label = str(conf)[:5] 79 | cv2.putText(img, label, (x1, y1 - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) 80 | return img 81 | 82 | 83 | def detect( 84 | model, 85 | source, 86 | device, 87 | project, 88 | name, 89 | exist_ok, 90 | save_img, 91 | view_img 92 | ): 93 | # Load model 94 | img_size = 640 95 | conf_thres = 0.6 96 | iou_thres = 0.5 97 | imgsz=(640, 640) 98 | 99 | # Directories 100 | save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run 101 | Path(save_dir).mkdir(parents=True, exist_ok=True) # make dir 102 | 103 | is_file = Path(source).suffix[1:] in (img_formats + vid_formats) 104 | is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) 105 | webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file) 106 | 107 | # Dataloader 108 | if webcam: 109 | print('loading streams:', source) 110 | dataset = LoadStreams(source, img_size=imgsz) 111 | bs = 1 # batch_size 112 | else: 113 | print('loading images', source) 114 | dataset = LoadImages(source, img_size=imgsz) 115 | bs = 1 # batch_size 116 | vid_path, vid_writer = [None] * bs, [None] * bs 117 | 118 | for path, im, im0s, vid_cap in dataset: 119 | 120 | if len(im.shape) == 4: 121 | orgimg = np.squeeze(im.transpose(0, 2, 3, 1), axis= 0) 122 | else: 123 | orgimg = im.transpose(1, 2, 0) 124 | 125 | orgimg = cv2.cvtColor(orgimg, cv2.COLOR_BGR2RGB) 126 | img0 = copy.deepcopy(orgimg) 127 | h0, w0 = orgimg.shape[:2] # orig hw 128 | r = img_size / max(h0, w0) # resize image to img_size 129 | if r != 1: # always resize down, only resize up if training with augmentation 130 | interp = cv2.INTER_AREA if r < 1 else cv2.INTER_LINEAR 131 | img0 = cv2.resize(img0, (int(w0 * r), int(h0 * r)), interpolation=interp) 132 | 133 | imgsz = check_img_size(img_size, s=model.stride.max()) # check img_size 134 | 135 | img = letterbox(img0, new_shape=imgsz)[0] 136 | # Convert from w,h,c to c,w,h 137 | img = img.transpose(2, 0, 1).copy() 138 | 139 | img = torch.from_numpy(img).to(device) 140 | img = img.float() # uint8 to fp16/32 141 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 142 | if img.ndimension() == 3: 143 | img = img.unsqueeze(0) 144 | 145 | # Inference 146 | pred = model(img)[0] 147 | 148 | # Apply NMS 149 | pred = non_max_suppression_face(pred, conf_thres, iou_thres) 150 | print(len(pred[0]), 'face' if len(pred[0]) == 1 else 'faces') 151 | 152 | # Process detections 153 | for i, det in enumerate(pred): # detections per image 154 | 155 | if webcam: # batch_size >= 1 156 | p, im0, frame = path[i], im0s[i].copy(), dataset.count 157 | else: 158 | p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0) 159 | 160 | p = Path(p) # to Path 161 | save_path = str(Path(save_dir) / p.name) # im.jpg 162 | 163 | if len(det): 164 | # Rescale boxes from img_size to im0 size 165 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() 166 | 167 | # Print results 168 | for c in det[:, -1].unique(): 169 | n = (det[:, -1] == c).sum() # detections per class 170 | 171 | det[:, 5:15] = scale_coords_landmarks(img.shape[2:], det[:, 5:15], im0.shape).round() 172 | 173 | for j in range(det.size()[0]): 174 | xyxy = det[j, :4].view(-1).tolist() 175 | conf = det[j, 4].cpu().numpy() 176 | landmarks = det[j, 5:15].view(-1).tolist() 177 | class_num = det[j, 15].cpu().numpy() 178 | 179 | im0 = show_results(im0, xyxy, conf, landmarks, class_num) 180 | 181 | if view_img: 182 | cv2.imshow('result', im0) 183 | k = cv2.waitKey(1) 184 | 185 | # Save results (image with detections) 186 | if save_img: 187 | if dataset.mode == 'image': 188 | cv2.imwrite(save_path, im0) 189 | else: # 'video' or 'stream' 190 | if vid_path[i] != save_path: # new video 191 | vid_path[i] = save_path 192 | if isinstance(vid_writer[i], cv2.VideoWriter): 193 | vid_writer[i].release() # release previous video writer 194 | if vid_cap: # video 195 | fps = vid_cap.get(cv2.CAP_PROP_FPS) 196 | w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) 197 | h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) 198 | else: # stream 199 | fps, w, h = 30, im0.shape[1], im0.shape[0] 200 | save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos 201 | vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) 202 | try: 203 | vid_writer[i].write(im0) 204 | except Exception as e: 205 | print(e) 206 | 207 | 208 | 209 | 210 | 211 | if __name__ == '__main__': 212 | parser = argparse.ArgumentParser() 213 | parser.add_argument('--weights', nargs='+', type=str, default='runs/train/exp5/weights/last.pt', help='model.pt path(s)') 214 | parser.add_argument('--source', type=str, default='0', help='source') # file/folder, 0 for webcam 215 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 216 | parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name') 217 | parser.add_argument('--name', default='exp', help='save results to project/name') 218 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') 219 | parser.add_argument('--save-img', action='store_true', help='save results') 220 | parser.add_argument('--view-img', action='store_true', help='show results') 221 | opt = parser.parse_args() 222 | 223 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 224 | model = load_model(opt.weights, device) 225 | detect(model, opt.source, device, opt.project, opt.name, opt.exist_ok, opt.save_img, opt.view_img) 226 | -------------------------------------------------------------------------------- /export.py: -------------------------------------------------------------------------------- 1 | """Exports a YOLOv5 *.pt model to ONNX and TorchScript formats 2 | 3 | Usage: 4 | $ export PYTHONPATH="$PWD" && python models/export.py --weights ./weights/yolov5s.pt --img 640 --batch 1 5 | """ 6 | 7 | import argparse 8 | import sys 9 | import time 10 | 11 | sys.path.append('./') # to run '$ python *.py' files in subdirectories 12 | 13 | import torch 14 | import torch.nn as nn 15 | 16 | import models 17 | from models.experimental import attempt_load 18 | from utils.activations import Hardswish, SiLU 19 | from utils.general import set_logging, check_img_size 20 | import onnx 21 | 22 | if __name__ == '__main__': 23 | parser = argparse.ArgumentParser() 24 | parser.add_argument('--weights', type=str, default='./yolov5s.pt', help='weights path') # from yolov5/models/ 25 | parser.add_argument('--img_size', nargs='+', type=int, default=[640, 640], help='image size') # height, width 26 | parser.add_argument('--batch_size', type=int, default=1, help='batch size') 27 | parser.add_argument('--dynamic', action='store_true', default=False, help='enable dynamic axis in onnx model') 28 | parser.add_argument('--onnx2pb', action='store_true', default=False, help='export onnx to pb') 29 | parser.add_argument('--onnx_infer', action='store_true', default=True, help='onnx infer test') 30 | #=======================TensorRT================================= 31 | parser.add_argument('--onnx2trt', action='store_true', default=False, help='export onnx to tensorrt') 32 | parser.add_argument('--fp16_trt', action='store_true', default=False, help='fp16 infer') 33 | #================================================================ 34 | opt = parser.parse_args() 35 | opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand 36 | print(opt) 37 | set_logging() 38 | t = time.time() 39 | 40 | # Load PyTorch model 41 | model = attempt_load(opt.weights, map_location=torch.device('cpu')) # load FP32 model 42 | delattr(model.model[-1], 'anchor_grid') 43 | model.model[-1].anchor_grid=[torch.zeros(1)] * 3 # nl=3 number of detection layers 44 | model.model[-1].export_cat = True 45 | model.eval() 46 | labels = model.names 47 | 48 | # Checks 49 | gs = int(max(model.stride)) # grid size (max stride) 50 | opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples 51 | 52 | # Input 53 | img = torch.zeros(opt.batch_size, 3, *opt.img_size) # image size(1,3,320,192) iDetection 54 | 55 | # Update model 56 | for k, m in model.named_modules(): 57 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 58 | if isinstance(m, models.common.Conv): # assign export-friendly activations 59 | if isinstance(m.act, nn.Hardswish): 60 | m.act = Hardswish() 61 | elif isinstance(m.act, nn.SiLU): 62 | m.act = SiLU() 63 | # elif isinstance(m, models.yolo.Detect): 64 | # m.forward = m.forward_export # assign forward (optional) 65 | if isinstance(m, models.common.ShuffleV2Block):#shufflenet block nn.SiLU 66 | for i in range(len(m.branch1)): 67 | if isinstance(m.branch1[i], nn.SiLU): 68 | m.branch1[i] = SiLU() 69 | for i in range(len(m.branch2)): 70 | if isinstance(m.branch2[i], nn.SiLU): 71 | m.branch2[i] = SiLU() 72 | y = model(img) # dry run 73 | 74 | # ONNX export 75 | print('\nStarting ONNX export with onnx %s...' % onnx.__version__) 76 | f = opt.weights.replace('.pt', '.onnx') # filename 77 | model.fuse() # only for ONNX 78 | input_names=['input'] 79 | output_names=['output'] 80 | torch.onnx.export(model, img, f, verbose=False, opset_version=12, 81 | input_names=input_names, 82 | output_names=output_names, 83 | dynamic_axes = {'input': {0: 'batch'}, 84 | 'output': {0: 'batch'} 85 | } if opt.dynamic else None) 86 | 87 | # Checks 88 | onnx_model = onnx.load(f) # load onnx model 89 | onnx.checker.check_model(onnx_model) # check onnx model 90 | print('ONNX export success, saved as %s' % f) 91 | # Finish 92 | print('\nExport complete (%.2fs). Visualize with https://github.com/lutzroeder/netron.' % (time.time() - t)) 93 | 94 | 95 | # onnx infer 96 | if opt.onnx_infer: 97 | import onnxruntime 98 | import numpy as np 99 | providers = ['CPUExecutionProvider'] 100 | session = onnxruntime.InferenceSession(f, providers=providers) 101 | im = img.cpu().numpy().astype(np.float32) # torch to numpy 102 | y_onnx = session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: im})[0] 103 | print("pred's shape is ",y_onnx.shape) 104 | print("max(|torch_pred - onnx_pred|) =",abs(y.cpu().numpy()-y_onnx).max()) 105 | 106 | 107 | # TensorRT export 108 | if opt.onnx2trt: 109 | from torch2trt.trt_model import ONNX_to_TRT 110 | print('\nStarting TensorRT...') 111 | ONNX_to_TRT(onnx_model_path=f,trt_engine_path=f.replace('.onnx', '.trt'),fp16_mode=opt.fp16_trt) 112 | 113 | # PB export 114 | if opt.onnx2pb: 115 | print('download the newest onnx_tf by https://github.com/onnx/onnx-tensorflow/tree/master/onnx_tf') 116 | from onnx_tf.backend import prepare 117 | import tensorflow as tf 118 | 119 | outpb = f.replace('.onnx', '.pb') # filename 120 | # strict=True maybe leads to KeyError: 'pyfunc_0', check: https://github.com/onnx/onnx-tensorflow/issues/167 121 | tf_rep = prepare(onnx_model, strict=False) # prepare tf representation 122 | tf_rep.export_graph(outpb) # export the model 123 | 124 | out_onnx = tf_rep.run(img) # onnx output 125 | 126 | # check pb 127 | with tf.Graph().as_default(): 128 | graph_def = tf.GraphDef() 129 | with open(outpb, "rb") as f: 130 | graph_def.ParseFromString(f.read()) 131 | tf.import_graph_def(graph_def, name="") 132 | with tf.Session() as sess: 133 | init = tf.global_variables_initializer() 134 | input_x = sess.graph.get_tensor_by_name(input_names[0]+':0') # input 135 | outputs = [] 136 | for i in output_names: 137 | outputs.append(sess.graph.get_tensor_by_name(i+':0')) 138 | out_pb = sess.run(outputs, feed_dict={input_x: img}) 139 | 140 | print(f'out_pytorch {y}') 141 | print(f'out_onnx {out_onnx}') 142 | print(f'out_pb {out_pb}') 143 | -------------------------------------------------------------------------------- /hubconf.py: -------------------------------------------------------------------------------- 1 | """File for accessing YOLOv5 via PyTorch Hub https://pytorch.org/hub/ 2 | 3 | Usage: 4 | import torch 5 | model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True, channels=3, classes=80) 6 | """ 7 | 8 | from pathlib import Path 9 | 10 | import torch 11 | 12 | from models.yolo import Model 13 | from utils.general import set_logging 14 | from utils.google_utils import attempt_download 15 | 16 | dependencies = ['torch', 'yaml'] 17 | set_logging() 18 | 19 | 20 | def create(name, pretrained, channels, classes, autoshape): 21 | """Creates a specified YOLOv5 model 22 | 23 | Arguments: 24 | name (str): name of model, i.e. 'yolov5s' 25 | pretrained (bool): load pretrained weights into the model 26 | channels (int): number of input channels 27 | classes (int): number of model classes 28 | 29 | Returns: 30 | pytorch model 31 | """ 32 | config = Path(__file__).parent / 'models' / f'{name}.yaml' # model.yaml path 33 | try: 34 | model = Model(config, channels, classes) 35 | if pretrained: 36 | fname = f'{name}.pt' # checkpoint filename 37 | attempt_download(fname) # download if not found locally 38 | ckpt = torch.load(fname, map_location=torch.device('cpu')) # load 39 | state_dict = ckpt['model'].float().state_dict() # to FP32 40 | state_dict = {k: v for k, v in state_dict.items() if model.state_dict()[k].shape == v.shape} # filter 41 | model.load_state_dict(state_dict, strict=False) # load 42 | if len(ckpt['model'].names) == classes: 43 | model.names = ckpt['model'].names # set class names attribute 44 | if autoshape: 45 | model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS 46 | return model 47 | 48 | except Exception as e: 49 | help_url = 'https://github.com/ultralytics/yolov5/issues/36' 50 | s = 'Cache maybe be out of date, try force_reload=True. See %s for help.' % help_url 51 | raise Exception(s) from e 52 | 53 | 54 | def yolov5s(pretrained=False, channels=3, classes=80, autoshape=True): 55 | """YOLOv5-small model from https://github.com/ultralytics/yolov5 56 | 57 | Arguments: 58 | pretrained (bool): load pretrained weights into the model, default=False 59 | channels (int): number of input channels, default=3 60 | classes (int): number of model classes, default=80 61 | 62 | Returns: 63 | pytorch model 64 | """ 65 | return create('yolov5s', pretrained, channels, classes, autoshape) 66 | 67 | 68 | def yolov5m(pretrained=False, channels=3, classes=80, autoshape=True): 69 | """YOLOv5-medium model from https://github.com/ultralytics/yolov5 70 | 71 | Arguments: 72 | pretrained (bool): load pretrained weights into the model, default=False 73 | channels (int): number of input channels, default=3 74 | classes (int): number of model classes, default=80 75 | 76 | Returns: 77 | pytorch model 78 | """ 79 | return create('yolov5m', pretrained, channels, classes, autoshape) 80 | 81 | 82 | def yolov5l(pretrained=False, channels=3, classes=80, autoshape=True): 83 | """YOLOv5-large model from https://github.com/ultralytics/yolov5 84 | 85 | Arguments: 86 | pretrained (bool): load pretrained weights into the model, default=False 87 | channels (int): number of input channels, default=3 88 | classes (int): number of model classes, default=80 89 | 90 | Returns: 91 | pytorch model 92 | """ 93 | return create('yolov5l', pretrained, channels, classes, autoshape) 94 | 95 | 96 | def yolov5x(pretrained=False, channels=3, classes=80, autoshape=True): 97 | """YOLOv5-xlarge model from https://github.com/ultralytics/yolov5 98 | 99 | Arguments: 100 | pretrained (bool): load pretrained weights into the model, default=False 101 | channels (int): number of input channels, default=3 102 | classes (int): number of model classes, default=80 103 | 104 | Returns: 105 | pytorch model 106 | """ 107 | return create('yolov5x', pretrained, channels, classes, autoshape) 108 | 109 | 110 | def custom(path_or_model='path/to/model.pt', autoshape=True): 111 | """YOLOv5-custom model from https://github.com/ultralytics/yolov5 112 | 113 | Arguments (3 options): 114 | path_or_model (str): 'path/to/model.pt' 115 | path_or_model (dict): torch.load('path/to/model.pt') 116 | path_or_model (nn.Module): torch.load('path/to/model.pt')['model'] 117 | 118 | Returns: 119 | pytorch model 120 | """ 121 | model = torch.load(path_or_model) if isinstance(path_or_model, str) else path_or_model # load checkpoint 122 | if isinstance(model, dict): 123 | model = model['model'] # load model 124 | 125 | hub_model = Model(model.yaml).to(next(model.parameters()).device) # create 126 | hub_model.load_state_dict(model.float().state_dict()) # load state_dict 127 | hub_model.names = model.names # class names 128 | return hub_model.autoshape() if autoshape else hub_model 129 | 130 | 131 | if __name__ == '__main__': 132 | model = create(name='yolov5s', pretrained=True, channels=3, classes=80, autoshape=True) # pretrained example 133 | # model = custom(path_or_model='path/to/model.pt') # custom example 134 | 135 | # Verify inference 136 | from PIL import Image 137 | 138 | imgs = [Image.open(x) for x in Path('data/images').glob('*.jpg')] 139 | results = model(imgs) 140 | results.show() 141 | results.print() 142 | -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/models/__init__.py -------------------------------------------------------------------------------- /models/blazeface.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [5,6, 10,13, 21,26] # P3/8 9 | - [55,72, 225,304, 438,553] # P4/16 10 | 11 | # YOLOv5 backbone 12 | backbone: 13 | # [from, number, module, args] 14 | [[-1, 1, Conv, [24, 3, 2]], # 0-P1/2 15 | [-1, 2, BlazeBlock, [24]], # 1 16 | [-1, 1, BlazeBlock, [48, None, 2]], # 2-P2/4 17 | [-1, 2, BlazeBlock, [48]], # 3 18 | [-1, 1, DoubleBlazeBlock, [96, 24, 2]], # 4-P3/8 19 | [-1, 2, DoubleBlazeBlock, [96, 24]], # 5 20 | [-1, 1, DoubleBlazeBlock, [96, 24, 2]], # 6-P4/16 21 | [-1, 2, DoubleBlazeBlock, [96, 24]], # 7 22 | ] 23 | 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [64, 1, 1]], # 8 (P4/32-large) 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 5], 1, Concat, [1]], # cat backbone P3 30 | [-1, 1, Conv, [64, 1, 1]], # 11 (P3/8-medium) 31 | 32 | [[11, 8], 1, Detect, [nc, anchors]], # Detect(P3, P4) 33 | ] 34 | -------------------------------------------------------------------------------- /models/blazeface_fpn.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [5,6, 10,13, 21,26] # P3/8 9 | - [55,72, 225,304, 438,553] # P4/16 10 | 11 | # YOLOv5 backbone 12 | backbone: 13 | # [from, number, module, args] 14 | [[-1, 1, Conv, [24, 3, 2]], # 0-P1/2 15 | [-1, 2, BlazeBlock, [24]], # 1 16 | [-1, 1, BlazeBlock, [48, None, 2]], # 2-P2/4 17 | [-1, 2, BlazeBlock, [48]], # 3 18 | [-1, 1, DoubleBlazeBlock, [96, 24, 2]], # 4-P3/8 19 | [-1, 2, DoubleBlazeBlock, [96, 24]], # 5 20 | [-1, 1, DoubleBlazeBlock, [96, 24, 2]], # 6-P4/16 21 | [-1, 2, DoubleBlazeBlock, [96, 24]], # 7 22 | ] 23 | 24 | 25 | # YOLOv5 head 26 | head: 27 | [[-1, 1, Conv, [48, 1, 1]], # 8 28 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 29 | [[-1, 5], 1, Concat, [1]], # cat backbone P3 30 | [-1, 1, Conv, [48, 1, 1]], # 11 (P3/8-medium) 31 | 32 | [-1, 1, nn.MaxPool2d, [3, 2, 1]], # 12 33 | [[-1, 7], 1, Concat, [1]], # cat backbone P3 34 | [-1, 1, Conv, [48, 1, 1]], # 14 (P4/16-large) 35 | 36 | [[11, 14], 1, Detect, [nc, anchors]], # Detect(P3, P4) 37 | ] 38 | 39 | -------------------------------------------------------------------------------- /models/experimental.py: -------------------------------------------------------------------------------- 1 | # This file contains experimental modules 2 | 3 | import numpy as np 4 | import torch 5 | import torch.nn as nn 6 | 7 | from models.common import Conv, DWConv 8 | from utils.google_utils import attempt_download 9 | 10 | 11 | class CrossConv(nn.Module): 12 | # Cross Convolution Downsample 13 | def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False): 14 | # ch_in, ch_out, kernel, stride, groups, expansion, shortcut 15 | super(CrossConv, self).__init__() 16 | c_ = int(c2 * e) # hidden channels 17 | self.cv1 = Conv(c1, c_, (1, k), (1, s)) 18 | self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g) 19 | self.add = shortcut and c1 == c2 20 | 21 | def forward(self, x): 22 | return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) 23 | 24 | 25 | class Sum(nn.Module): 26 | # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070 27 | def __init__(self, n, weight=False): # n: number of inputs 28 | super(Sum, self).__init__() 29 | self.weight = weight # apply weights boolean 30 | self.iter = range(n - 1) # iter object 31 | if weight: 32 | self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights 33 | 34 | def forward(self, x): 35 | y = x[0] # no weight 36 | if self.weight: 37 | w = torch.sigmoid(self.w) * 2 38 | for i in self.iter: 39 | y = y + x[i + 1] * w[i] 40 | else: 41 | for i in self.iter: 42 | y = y + x[i + 1] 43 | return y 44 | 45 | 46 | class GhostConv(nn.Module): 47 | # Ghost Convolution https://github.com/huawei-noah/ghostnet 48 | def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups 49 | super(GhostConv, self).__init__() 50 | c_ = c2 // 2 # hidden channels 51 | self.cv1 = Conv(c1, c_, k, s, None, g, act) 52 | self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) 53 | 54 | def forward(self, x): 55 | y = self.cv1(x) 56 | return torch.cat([y, self.cv2(y)], 1) 57 | 58 | 59 | class GhostBottleneck(nn.Module): 60 | # Ghost Bottleneck https://github.com/huawei-noah/ghostnet 61 | def __init__(self, c1, c2, k, s): 62 | super(GhostBottleneck, self).__init__() 63 | c_ = c2 // 2 64 | self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw 65 | DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw 66 | GhostConv(c_, c2, 1, 1, act=False)) # pw-linear 67 | self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), 68 | Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() 69 | 70 | def forward(self, x): 71 | return self.conv(x) + self.shortcut(x) 72 | 73 | 74 | class MixConv2d(nn.Module): 75 | # Mixed Depthwise Conv https://arxiv.org/abs/1907.09595 76 | def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True): 77 | super(MixConv2d, self).__init__() 78 | groups = len(k) 79 | if equal_ch: # equal c_ per group 80 | i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices 81 | c_ = [(i == g).sum() for g in range(groups)] # intermediate channels 82 | else: # equal weight.numel() per group 83 | b = [c2] + [0] * groups 84 | a = np.eye(groups + 1, groups, k=-1) 85 | a -= np.roll(a, 1, axis=1) 86 | a *= np.array(k) ** 2 87 | a[0] = 1 88 | c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b 89 | 90 | self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)]) 91 | self.bn = nn.BatchNorm2d(c2) 92 | self.act = nn.LeakyReLU(0.1, inplace=True) 93 | 94 | def forward(self, x): 95 | return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1))) 96 | 97 | 98 | class Ensemble(nn.ModuleList): 99 | # Ensemble of models 100 | def __init__(self): 101 | super(Ensemble, self).__init__() 102 | 103 | def forward(self, x, augment=False): 104 | y = [] 105 | for module in self: 106 | y.append(module(x, augment)[0]) 107 | # y = torch.stack(y).max(0)[0] # max ensemble 108 | # y = torch.stack(y).mean(0) # mean ensemble 109 | y = torch.cat(y, 1) # nms ensemble 110 | return y, None # inference, train output 111 | 112 | 113 | def attempt_load(weights, map_location=None): 114 | # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a 115 | model = Ensemble() 116 | for w in weights if isinstance(weights, list) else [weights]: 117 | attempt_download(w) 118 | model.append(torch.load(w, map_location=map_location)['model'].float().fuse().eval()) # load FP32 model 119 | 120 | # Compatibility updates 121 | for m in model.modules(): 122 | if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]: 123 | m.inplace = True # pytorch 1.7.0 compatibility 124 | elif type(m) is Conv: 125 | m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility 126 | 127 | if len(model) == 1: 128 | return model[-1] # return model 129 | else: 130 | print('Ensemble created with %s\n' % weights) 131 | for k in ['names', 'stride']: 132 | setattr(model, k, getattr(model[-1], k)) 133 | return model # return ensemble 134 | -------------------------------------------------------------------------------- /models/yolov5l.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [4,5, 8,10, 13,16] # P3/8 9 | - [23,29, 43,55, 73,105] # P4/16 10 | - [146,217, 231,300, 335,433] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, StemBlock, [64, 3, 2]], # 0-P1/2 16 | [-1, 3, C3, [128]], 17 | [-1, 1, Conv, [256, 3, 2]], # 2-P3/8 18 | [-1, 9, C3, [256]], 19 | [-1, 1, Conv, [512, 3, 2]], # 4-P4/16 20 | [-1, 9, C3, [512]], 21 | [-1, 1, Conv, [1024, 3, 2]], # 6-P5/32 22 | [-1, 1, SPP, [1024, [3,5,7]]], 23 | [-1, 3, C3, [1024, False]], # 8 24 | ] 25 | 26 | # YOLOv5 head 27 | head: 28 | [[-1, 1, Conv, [512, 1, 1]], 29 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 30 | [[-1, 5], 1, Concat, [1]], # cat backbone P4 31 | [-1, 3, C3, [512, False]], # 12 32 | 33 | [-1, 1, Conv, [256, 1, 1]], 34 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 35 | [[-1, 3], 1, Concat, [1]], # cat backbone P3 36 | [-1, 3, C3, [256, False]], # 16 (P3/8-small) 37 | 38 | [-1, 1, Conv, [256, 3, 2]], 39 | [[-1, 13], 1, Concat, [1]], # cat head P4 40 | [-1, 3, C3, [512, False]], # 19 (P4/16-medium) 41 | 42 | [-1, 1, Conv, [512, 3, 2]], 43 | [[-1, 9], 1, Concat, [1]], # cat head P5 44 | [-1, 3, C3, [1024, False]], # 22 (P5/32-large) 45 | 46 | [[16, 19, 22], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 47 | ] 48 | -------------------------------------------------------------------------------- /models/yolov5l6.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [6,7, 9,11, 13,16] # P3/8 9 | - [18,23, 26,33, 37,47] # P4/16 10 | - [54,67, 77,104, 112,154] # P5/32 11 | - [174,238, 258,355, 445,568] # P6/64 12 | 13 | # YOLOv5 backbone 14 | backbone: 15 | # [from, number, module, args] 16 | [ [ -1, 1, StemBlock, [ 64, 3, 2 ] ], # 0-P1/2 17 | [ -1, 3, C3, [ 128 ] ], 18 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 2-P3/8 19 | [ -1, 9, C3, [ 256 ] ], 20 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 4-P4/16 21 | [ -1, 9, C3, [ 512 ] ], 22 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 6-P5/32 23 | [ -1, 3, C3, [ 768 ] ], 24 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 8-P6/64 25 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], 26 | [ -1, 3, C3, [ 1024, False ] ], # 10 27 | ] 28 | 29 | # YOLOv5 head 30 | head: 31 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ], 32 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 33 | [ [ -1, 7 ], 1, Concat, [ 1 ] ], # cat backbone P5 34 | [ -1, 3, C3, [ 768, False ] ], # 14 35 | 36 | [ -1, 1, Conv, [ 512, 1, 1 ] ], 37 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 38 | [ [ -1, 5 ], 1, Concat, [ 1 ] ], # cat backbone P4 39 | [ -1, 3, C3, [ 512, False ] ], # 18 40 | 41 | [ -1, 1, Conv, [ 256, 1, 1 ] ], 42 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 43 | [ [ -1, 3 ], 1, Concat, [ 1 ] ], # cat backbone P3 44 | [ -1, 3, C3, [ 256, False ] ], # 22 (P3/8-small) 45 | 46 | [ -1, 1, Conv, [ 256, 3, 2 ] ], 47 | [ [ -1, 19 ], 1, Concat, [ 1 ] ], # cat head P4 48 | [ -1, 3, C3, [ 512, False ] ], # 25 (P4/16-medium) 49 | 50 | [ -1, 1, Conv, [ 512, 3, 2 ] ], 51 | [ [ -1, 15 ], 1, Concat, [ 1 ] ], # cat head P5 52 | [ -1, 3, C3, [ 768, False ] ], # 28 (P5/32-large) 53 | 54 | [ -1, 1, Conv, [ 768, 3, 2 ] ], 55 | [ [ -1, 11 ], 1, Concat, [ 1 ] ], # cat head P6 56 | [ -1, 3, C3, [ 1024, False ] ], # 31 (P6/64-xlarge) 57 | 58 | [ [ 22, 25, 28, 31 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) 59 | ] 60 | 61 | -------------------------------------------------------------------------------- /models/yolov5m.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # 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 | - [4,5, 8,10, 13,16] # P3/8 9 | - [23,29, 43,55, 73,105] # P4/16 10 | - [146,217, 231,300, 335,433] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, StemBlock, [64, 3, 2]], # 0-P1/2 16 | [-1, 3, C3, [128]], 17 | [-1, 1, Conv, [256, 3, 2]], # 2-P3/8 18 | [-1, 9, C3, [256]], 19 | [-1, 1, Conv, [512, 3, 2]], # 4-P4/16 20 | [-1, 9, C3, [512]], 21 | [-1, 1, Conv, [1024, 3, 2]], # 6-P5/32 22 | [-1, 1, SPP, [1024, [3,5,7]]], 23 | [-1, 3, C3, [1024, False]], # 8 24 | ] 25 | 26 | # YOLOv5 head 27 | head: 28 | [[-1, 1, Conv, [512, 1, 1]], 29 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 30 | [[-1, 5], 1, Concat, [1]], # cat backbone P4 31 | [-1, 3, C3, [512, False]], # 12 32 | 33 | [-1, 1, Conv, [256, 1, 1]], 34 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 35 | [[-1, 3], 1, Concat, [1]], # cat backbone P3 36 | [-1, 3, C3, [256, False]], # 16 (P3/8-small) 37 | 38 | [-1, 1, Conv, [256, 3, 2]], 39 | [[-1, 13], 1, Concat, [1]], # cat head P4 40 | [-1, 3, C3, [512, False]], # 19 (P4/16-medium) 41 | 42 | [-1, 1, Conv, [512, 3, 2]], 43 | [[-1, 9], 1, Concat, [1]], # cat head P5 44 | [-1, 3, C3, [1024, False]], # 22 (P5/32-large) 45 | 46 | [[16, 19, 22], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 47 | ] 48 | -------------------------------------------------------------------------------- /models/yolov5m6.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # 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 | - [6,7, 9,11, 13,16] # P3/8 9 | - [18,23, 26,33, 37,47] # P4/16 10 | - [54,67, 77,104, 112,154] # P5/32 11 | - [174,238, 258,355, 445,568] # P6/64 12 | 13 | # YOLOv5 backbone 14 | backbone: 15 | # [from, number, module, args] 16 | [ [ -1, 1, StemBlock, [ 64, 3, 2 ] ], # 0-P1/2 17 | [ -1, 3, C3, [ 128 ] ], 18 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 2-P3/8 19 | [ -1, 9, C3, [ 256 ] ], 20 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 4-P4/16 21 | [ -1, 9, C3, [ 512 ] ], 22 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 6-P5/32 23 | [ -1, 3, C3, [ 768 ] ], 24 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 8-P6/64 25 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], 26 | [ -1, 3, C3, [ 1024, False ] ], # 10 27 | ] 28 | 29 | # YOLOv5 head 30 | head: 31 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ], 32 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 33 | [ [ -1, 7 ], 1, Concat, [ 1 ] ], # cat backbone P5 34 | [ -1, 3, C3, [ 768, False ] ], # 14 35 | 36 | [ -1, 1, Conv, [ 512, 1, 1 ] ], 37 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 38 | [ [ -1, 5 ], 1, Concat, [ 1 ] ], # cat backbone P4 39 | [ -1, 3, C3, [ 512, False ] ], # 18 40 | 41 | [ -1, 1, Conv, [ 256, 1, 1 ] ], 42 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 43 | [ [ -1, 3 ], 1, Concat, [ 1 ] ], # cat backbone P3 44 | [ -1, 3, C3, [ 256, False ] ], # 22 (P3/8-small) 45 | 46 | [ -1, 1, Conv, [ 256, 3, 2 ] ], 47 | [ [ -1, 19 ], 1, Concat, [ 1 ] ], # cat head P4 48 | [ -1, 3, C3, [ 512, False ] ], # 25 (P4/16-medium) 49 | 50 | [ -1, 1, Conv, [ 512, 3, 2 ] ], 51 | [ [ -1, 15 ], 1, Concat, [ 1 ] ], # cat head P5 52 | [ -1, 3, C3, [ 768, False ] ], # 28 (P5/32-large) 53 | 54 | [ -1, 1, Conv, [ 768, 3, 2 ] ], 55 | [ [ -1, 11 ], 1, Concat, [ 1 ] ], # cat head P6 56 | [ -1, 3, C3, [ 1024, False ] ], # 31 (P6/64-xlarge) 57 | 58 | [ [ 22, 25, 28, 31 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) 59 | ] 60 | 61 | -------------------------------------------------------------------------------- /models/yolov5n-0.5.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 0.5 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [4,5, 8,10, 13,16] # P3/8 9 | - [23,29, 43,55, 73,105] # P4/16 10 | - [146,217, 231,300, 335,433] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, StemBlock, [32, 3, 2]], # 0-P2/4 16 | [-1, 1, ShuffleV2Block, [128, 2]], # 1-P3/8 17 | [-1, 3, ShuffleV2Block, [128, 1]], # 2 18 | [-1, 1, ShuffleV2Block, [256, 2]], # 3-P4/16 19 | [-1, 7, ShuffleV2Block, [256, 1]], # 4 20 | [-1, 1, ShuffleV2Block, [512, 2]], # 5-P5/32 21 | [-1, 3, ShuffleV2Block, [512, 1]], # 6 22 | ] 23 | 24 | # YOLOv5 head 25 | head: 26 | [[-1, 1, Conv, [128, 1, 1]], 27 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 28 | [[-1, 4], 1, Concat, [1]], # cat backbone P4 29 | [-1, 1, C3, [128, False]], # 10 30 | 31 | [-1, 1, Conv, [128, 1, 1]], 32 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 33 | [[-1, 2], 1, Concat, [1]], # cat backbone P3 34 | [-1, 1, C3, [128, False]], # 14 (P3/8-small) 35 | 36 | [-1, 1, Conv, [128, 3, 2]], 37 | [[-1, 11], 1, Concat, [1]], # cat head P4 38 | [-1, 1, C3, [128, False]], # 17 (P4/16-medium) 39 | 40 | [-1, 1, Conv, [128, 3, 2]], 41 | [[-1, 7], 1, Concat, [1]], # cat head P5 42 | [-1, 1, C3, [128, False]], # 20 (P5/32-large) 43 | 44 | [[14, 17, 20], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 45 | ] 46 | 47 | -------------------------------------------------------------------------------- /models/yolov5n.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [4,5, 8,10, 13,16] # P3/8 9 | - [23,29, 43,55, 73,105] # P4/16 10 | - [146,217, 231,300, 335,433] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, StemBlock, [32, 3, 2]], # 0-P2/4 16 | [-1, 1, ShuffleV2Block, [128, 2]], # 1-P3/8 17 | [-1, 3, ShuffleV2Block, [128, 1]], # 2 18 | [-1, 1, ShuffleV2Block, [256, 2]], # 3-P4/16 19 | [-1, 7, ShuffleV2Block, [256, 1]], # 4 20 | [-1, 1, ShuffleV2Block, [512, 2]], # 5-P5/32 21 | [-1, 3, ShuffleV2Block, [512, 1]], # 6 22 | ] 23 | 24 | # YOLOv5 head 25 | head: 26 | [[-1, 1, Conv, [128, 1, 1]], 27 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 28 | [[-1, 4], 1, Concat, [1]], # cat backbone P4 29 | [-1, 1, C3, [128, False]], # 10 30 | 31 | [-1, 1, Conv, [128, 1, 1]], 32 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 33 | [[-1, 2], 1, Concat, [1]], # cat backbone P3 34 | [-1, 1, C3, [128, False]], # 14 (P3/8-small) 35 | 36 | [-1, 1, Conv, [128, 3, 2]], 37 | [[-1, 11], 1, Concat, [1]], # cat head P4 38 | [-1, 1, C3, [128, False]], # 17 (P4/16-medium) 39 | 40 | [-1, 1, Conv, [128, 3, 2]], 41 | [[-1, 7], 1, Concat, [1]], # cat head P5 42 | [-1, 1, C3, [128, False]], # 20 (P5/32-large) 43 | 44 | [[14, 17, 20], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 45 | ] 46 | 47 | -------------------------------------------------------------------------------- /models/yolov5n6.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # number of classes 3 | depth_multiple: 1.0 # model depth multiple 4 | width_multiple: 1.0 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [6,7, 9,11, 13,16] # P3/8 9 | - [18,23, 26,33, 37,47] # P4/16 10 | - [54,67, 77,104, 112,154] # P5/32 11 | - [174,238, 258,355, 445,568] # P6/64 12 | 13 | # YOLOv5 backbone 14 | backbone: 15 | # [from, number, module, args] 16 | [[-1, 1, StemBlock, [32, 3, 2]], # 0-P2/4 17 | [-1, 1, ShuffleV2Block, [128, 2]], # 1-P3/8 18 | [-1, 3, ShuffleV2Block, [128, 1]], # 2 19 | [-1, 1, ShuffleV2Block, [256, 2]], # 3-P4/16 20 | [-1, 7, ShuffleV2Block, [256, 1]], # 4 21 | [-1, 1, ShuffleV2Block, [384, 2]], # 5-P5/32 22 | [-1, 3, ShuffleV2Block, [384, 1]], # 6 23 | [-1, 1, ShuffleV2Block, [512, 2]], # 7-P6/64 24 | [-1, 3, ShuffleV2Block, [512, 1]], # 8 25 | ] 26 | 27 | # YOLOv5 head 28 | head: 29 | [[-1, 1, Conv, [128, 1, 1]], 30 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 31 | [[-1, 6], 1, Concat, [1]], # cat backbone P5 32 | [-1, 1, C3, [128, False]], # 12 33 | 34 | [-1, 1, Conv, [128, 1, 1]], 35 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 36 | [[-1, 4], 1, Concat, [1]], # cat backbone P4 37 | [-1, 1, C3, [128, False]], # 16 (P4/8-small) 38 | 39 | [-1, 1, Conv, [128, 1, 1]], 40 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 41 | [[-1, 2], 1, Concat, [1]], # cat backbone P3 42 | [-1, 1, C3, [128, False]], # 20 (P3/8-small) 43 | 44 | [-1, 1, Conv, [128, 3, 2]], 45 | [[-1, 17], 1, Concat, [1]], # cat head P4 46 | [-1, 1, C3, [128, False]], # 23 (P4/16-medium) 47 | 48 | [-1, 1, Conv, [128, 3, 2]], 49 | [[-1, 13], 1, Concat, [1]], # cat head P5 50 | [-1, 1, C3, [128, False]], # 26 (P5/32-large) 51 | 52 | [-1, 1, Conv, [128, 3, 2]], 53 | [[-1, 9], 1, Concat, [1]], # cat head P6 54 | [-1, 1, C3, [128, False]], # 29 (P6/64-large) 55 | 56 | [[20, 23, 26, 29], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 57 | ] 58 | 59 | -------------------------------------------------------------------------------- /models/yolov5s.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # number of classes 3 | depth_multiple: 0.33 # model depth multiple 4 | width_multiple: 0.5 # layer channel multiple 5 | 6 | # anchors 7 | anchors: 8 | - [4,5, 8,10, 13,16] # P3/8 9 | - [23,29, 43,55, 73,105] # P4/16 10 | - [146,217, 231,300, 335,433] # P5/32 11 | 12 | # YOLOv5 backbone 13 | backbone: 14 | # [from, number, module, args] 15 | [[-1, 1, StemBlock, [64, 3, 2]], # 0-P1/2 16 | [-1, 3, C3, [128]], 17 | [-1, 1, Conv, [256, 3, 2]], # 2-P3/8 18 | [-1, 9, C3, [256]], 19 | [-1, 1, Conv, [512, 3, 2]], # 4-P4/16 20 | [-1, 9, C3, [512]], 21 | [-1, 1, Conv, [1024, 3, 2]], # 6-P5/32 22 | [-1, 1, SPP, [1024, [3,5,7]]], 23 | [-1, 3, C3, [1024, False]], # 8 24 | ] 25 | 26 | # YOLOv5 head 27 | head: 28 | [[-1, 1, Conv, [512, 1, 1]], 29 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 30 | [[-1, 5], 1, Concat, [1]], # cat backbone P4 31 | [-1, 3, C3, [512, False]], # 12 32 | 33 | [-1, 1, Conv, [256, 1, 1]], 34 | [-1, 1, nn.Upsample, [None, 2, 'nearest']], 35 | [[-1, 3], 1, Concat, [1]], # cat backbone P3 36 | [-1, 3, C3, [256, False]], # 16 (P3/8-small) 37 | 38 | [-1, 1, Conv, [256, 3, 2]], 39 | [[-1, 13], 1, Concat, [1]], # cat head P4 40 | [-1, 3, C3, [512, False]], # 19 (P4/16-medium) 41 | 42 | [-1, 1, Conv, [512, 3, 2]], 43 | [[-1, 9], 1, Concat, [1]], # cat head P5 44 | [-1, 3, C3, [1024, False]], # 22 (P5/32-large) 45 | 46 | [[16, 19, 22], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5) 47 | ] 48 | -------------------------------------------------------------------------------- /models/yolov5s6.yaml: -------------------------------------------------------------------------------- 1 | # parameters 2 | nc: 1 # 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 | - [6,7, 9,11, 13,16] # P3/8 9 | - [18,23, 26,33, 37,47] # P4/16 10 | - [54,67, 77,104, 112,154] # P5/32 11 | - [174,238, 258,355, 445,568] # P6/64 12 | 13 | # YOLOv5 backbone 14 | backbone: 15 | # [from, number, module, args] 16 | [ [ -1, 1, StemBlock, [ 64, 3, 2 ] ], # 0-P1/2 17 | [ -1, 3, C3, [ 128 ] ], 18 | [ -1, 1, Conv, [ 256, 3, 2 ] ], # 2-P3/8 19 | [ -1, 9, C3, [ 256 ] ], 20 | [ -1, 1, Conv, [ 512, 3, 2 ] ], # 4-P4/16 21 | [ -1, 9, C3, [ 512 ] ], 22 | [ -1, 1, Conv, [ 768, 3, 2 ] ], # 6-P5/32 23 | [ -1, 3, C3, [ 768 ] ], 24 | [ -1, 1, Conv, [ 1024, 3, 2 ] ], # 8-P6/64 25 | [ -1, 1, SPP, [ 1024, [ 3, 5, 7 ] ] ], 26 | [ -1, 3, C3, [ 1024, False ] ], # 10 27 | ] 28 | 29 | # YOLOv5 head 30 | head: 31 | [ [ -1, 1, Conv, [ 768, 1, 1 ] ], 32 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 33 | [ [ -1, 7 ], 1, Concat, [ 1 ] ], # cat backbone P5 34 | [ -1, 3, C3, [ 768, False ] ], # 14 35 | 36 | [ -1, 1, Conv, [ 512, 1, 1 ] ], 37 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 38 | [ [ -1, 5 ], 1, Concat, [ 1 ] ], # cat backbone P4 39 | [ -1, 3, C3, [ 512, False ] ], # 18 40 | 41 | [ -1, 1, Conv, [ 256, 1, 1 ] ], 42 | [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ], 43 | [ [ -1, 3 ], 1, Concat, [ 1 ] ], # cat backbone P3 44 | [ -1, 3, C3, [ 256, False ] ], # 22 (P3/8-small) 45 | 46 | [ -1, 1, Conv, [ 256, 3, 2 ] ], 47 | [ [ -1, 19 ], 1, Concat, [ 1 ] ], # cat head P4 48 | [ -1, 3, C3, [ 512, False ] ], # 25 (P4/16-medium) 49 | 50 | [ -1, 1, Conv, [ 512, 3, 2 ] ], 51 | [ [ -1, 15 ], 1, Concat, [ 1 ] ], # cat head P5 52 | [ -1, 3, C3, [ 768, False ] ], # 28 (P5/32-large) 53 | 54 | [ -1, 1, Conv, [ 768, 3, 2 ] ], 55 | [ [ -1, 11 ], 1, Concat, [ 1 ] ], # cat head P6 56 | [ -1, 3, C3, [ 1024, False ] ], # 31 (P6/64-xlarge) 57 | 58 | [ [ 22, 25, 28, 31 ], 1, Detect, [ nc, anchors ] ], # Detect(P3, P4, P5, P6) 59 | ] 60 | 61 | -------------------------------------------------------------------------------- /test_widerface.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import glob 3 | import time 4 | from pathlib import Path 5 | 6 | import os 7 | import cv2 8 | import torch 9 | import torch.backends.cudnn as cudnn 10 | from numpy import random 11 | import numpy as np 12 | from models.experimental import attempt_load 13 | from utils.datasets import letterbox 14 | from utils.general import check_img_size, check_requirements, non_max_suppression_face, apply_classifier, \ 15 | scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path 16 | from utils.plots import plot_one_box 17 | from utils.torch_utils import select_device, load_classifier, time_synchronized 18 | from tqdm import tqdm 19 | 20 | def dynamic_resize(shape, stride=64): 21 | max_size = max(shape[0], shape[1]) 22 | if max_size % stride != 0: 23 | max_size = (int(max_size / stride) + 1) * stride 24 | return max_size 25 | 26 | def scale_coords_landmarks(img1_shape, coords, img0_shape, ratio_pad=None): 27 | # Rescale coords (xyxy) from img1_shape to img0_shape 28 | if ratio_pad is None: # calculate from img0_shape 29 | gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new 30 | pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding 31 | else: 32 | gain = ratio_pad[0][0] 33 | pad = ratio_pad[1] 34 | 35 | coords[:, [0, 2, 4, 6, 8]] -= pad[0] # x padding 36 | coords[:, [1, 3, 5, 7, 9]] -= pad[1] # y padding 37 | coords[:, :10] /= gain 38 | #clip_coords(coords, img0_shape) 39 | coords[:, 0].clamp_(0, img0_shape[1]) # x1 40 | coords[:, 1].clamp_(0, img0_shape[0]) # y1 41 | coords[:, 2].clamp_(0, img0_shape[1]) # x2 42 | coords[:, 3].clamp_(0, img0_shape[0]) # y2 43 | coords[:, 4].clamp_(0, img0_shape[1]) # x3 44 | coords[:, 5].clamp_(0, img0_shape[0]) # y3 45 | coords[:, 6].clamp_(0, img0_shape[1]) # x4 46 | coords[:, 7].clamp_(0, img0_shape[0]) # y4 47 | coords[:, 8].clamp_(0, img0_shape[1]) # x5 48 | coords[:, 9].clamp_(0, img0_shape[0]) # y5 49 | return coords 50 | 51 | def show_results(img, xywh, conf, landmarks, class_num): 52 | h,w,c = img.shape 53 | tl = 1 or round(0.002 * (h + w) / 2) + 1 # line/font thickness 54 | x1 = int(xywh[0] * w - 0.5 * xywh[2] * w) 55 | y1 = int(xywh[1] * h - 0.5 * xywh[3] * h) 56 | x2 = int(xywh[0] * w + 0.5 * xywh[2] * w) 57 | y2 = int(xywh[1] * h + 0.5 * xywh[3] * h) 58 | cv2.rectangle(img, (x1,y1), (x2, y2), (0,255,0), thickness=tl, lineType=cv2.LINE_AA) 59 | 60 | clors = [(255,0,0),(0,255,0),(0,0,255),(255,255,0),(0,255,255)] 61 | 62 | for i in range(5): 63 | point_x = int(landmarks[2 * i] * w) 64 | point_y = int(landmarks[2 * i + 1] * h) 65 | cv2.circle(img, (point_x, point_y), tl+1, clors[i], -1) 66 | 67 | tf = max(tl - 1, 1) # font thickness 68 | label = str(int(class_num)) + ': ' + str(conf)[:5] 69 | cv2.putText(img, label, (x1, y1 - 2), 0, tl / 3, [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) 70 | return img 71 | 72 | def detect(model, img0): 73 | stride = int(model.stride.max()) # model stride 74 | imgsz = opt.img_size 75 | if imgsz <= 0: # original size 76 | imgsz = dynamic_resize(img0.shape) 77 | imgsz = check_img_size(imgsz, s=64) # check img_size 78 | img = letterbox(img0, imgsz)[0] 79 | # Convert 80 | img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 81 | img = np.ascontiguousarray(img) 82 | img = torch.from_numpy(img).to(device) 83 | img = img.float() # uint8 to fp16/32 84 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 85 | if img.ndimension() == 3: 86 | img = img.unsqueeze(0) 87 | 88 | # Inference 89 | pred = model(img, augment=opt.augment)[0] 90 | # Apply NMS 91 | pred = non_max_suppression_face(pred, opt.conf_thres, opt.iou_thres)[0] 92 | gn = torch.tensor(img0.shape)[[1, 0, 1, 0]].to(device) # normalization gain whwh 93 | gn_lks = torch.tensor(img0.shape)[[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]].to(device) # normalization gain landmarks 94 | boxes = [] 95 | h, w, c = img0.shape 96 | if pred is not None: 97 | pred[:, :4] = scale_coords(img.shape[2:], pred[:, :4], img0.shape).round() 98 | pred[:, 5:15] = scale_coords_landmarks(img.shape[2:], pred[:, 5:15], img0.shape).round() 99 | for j in range(pred.size()[0]): 100 | xywh = (xyxy2xywh(pred[j, :4].view(1, 4)) / gn).view(-1) 101 | xywh = xywh.data.cpu().numpy() 102 | conf = pred[j, 4].cpu().numpy() 103 | landmarks = (pred[j, 5:15].view(1, 10) / gn_lks).view(-1).tolist() 104 | class_num = pred[j, 15].cpu().numpy() 105 | x1 = int(xywh[0] * w - 0.5 * xywh[2] * w) 106 | y1 = int(xywh[1] * h - 0.5 * xywh[3] * h) 107 | x2 = int(xywh[0] * w + 0.5 * xywh[2] * w) 108 | y2 = int(xywh[1] * h + 0.5 * xywh[3] * h) 109 | boxes.append([x1, y1, x2-x1, y2-y1, conf]) 110 | return boxes 111 | 112 | 113 | if __name__ == '__main__': 114 | parser = argparse.ArgumentParser() 115 | parser.add_argument('--weights', nargs='+', type=str, default='runs/train/exp5/weights/last.pt', help='model.pt path(s)') 116 | parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') 117 | parser.add_argument('--conf-thres', type=float, default=0.02, help='object confidence threshold') 118 | parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS') 119 | parser.add_argument('--device', default='0', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') 120 | parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS') 121 | parser.add_argument('--augment', action='store_true', help='augmented inference') 122 | parser.add_argument('--update', action='store_true', help='update all models') 123 | parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3') 124 | parser.add_argument('--project', default='runs/detect', help='save results to project/name') 125 | parser.add_argument('--name', default='exp', help='save results to project/name') 126 | parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') 127 | parser.add_argument('--save_folder', default='./widerface_evaluate/widerface_txt/', type=str, help='Dir to save txt results') 128 | parser.add_argument('--dataset_folder', default='../WiderFace/val/images/', type=str, help='dataset path') 129 | parser.add_argument('--folder_pict', default='/yolov5-face/data/widerface/val/wider_val.txt', type=str, help='folder_pict') 130 | opt = parser.parse_args() 131 | print(opt) 132 | 133 | # changhy : read folder_pict 134 | pict_folder = {} 135 | with open(opt.folder_pict, 'r') as f: 136 | lines = f.readlines() 137 | for line in lines: 138 | line = line.strip().split('/') 139 | pict_folder[line[-1]] = line[-2] 140 | 141 | # Load model 142 | device = select_device(opt.device) 143 | model = attempt_load(opt.weights, map_location=device) # load FP32 model 144 | with torch.no_grad(): 145 | # testing dataset 146 | testset_folder = opt.dataset_folder 147 | 148 | for image_path in tqdm(glob.glob(os.path.join(testset_folder, '*'))): 149 | if image_path.endswith('.txt'): 150 | continue 151 | img0 = cv2.imread(image_path) # BGR 152 | if img0 is None: 153 | print(f'ignore : {image_path}') 154 | continue 155 | boxes = detect(model, img0) 156 | # -------------------------------------------------------------------- 157 | image_name = os.path.basename(image_path) 158 | txt_name = os.path.splitext(image_name)[0] + ".txt" 159 | save_name = os.path.join(opt.save_folder, pict_folder[image_name], txt_name) 160 | dirname = os.path.dirname(save_name) 161 | if not os.path.isdir(dirname): 162 | os.makedirs(dirname) 163 | with open(save_name, "w") as fd: 164 | file_name = os.path.basename(save_name)[:-4] + "\n" 165 | bboxs_num = str(len(boxes)) + "\n" 166 | fd.write(file_name) 167 | fd.write(bboxs_num) 168 | for box in boxes: 169 | fd.write('%d %d %d %d %.03f' % (box[0], box[1], box[2], box[3], box[4] if box[4] <= 1 else 1) + '\n') 170 | print('done.') 171 | -------------------------------------------------------------------------------- /torch2trt/imgs/yolov5l-face.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/torch2trt/imgs/yolov5l-face.jpg -------------------------------------------------------------------------------- /torch2trt/imgs/yolov5m-face.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/torch2trt/imgs/yolov5m-face.jpg -------------------------------------------------------------------------------- /torch2trt/imgs/yolov5n-0.5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/torch2trt/imgs/yolov5n-0.5.jpg -------------------------------------------------------------------------------- /torch2trt/imgs/yolov5n-face.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/torch2trt/imgs/yolov5n-face.jpg -------------------------------------------------------------------------------- /torch2trt/imgs/yolov5s-face.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/torch2trt/imgs/yolov5s-face.jpg -------------------------------------------------------------------------------- /torch2trt/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import cv2 4 | import copy 5 | import torch 6 | import argparse 7 | root_path=os.path.dirname(os.path.abspath(os.path.dirname(__file__))) # 项目根路径:获取当前路径,再上级路径 8 | sys.path.append(root_path) # 将项目根路径写入系统路径 9 | from utils.general import check_img_size,non_max_suppression_face,scale_coords,xyxy2xywh 10 | from utils.datasets import letterbox 11 | from detect_face import scale_coords_landmarks,show_results 12 | from torch2trt.trt_model import TrtModel 13 | cur_path=os.path.abspath(os.path.dirname(__file__)) 14 | def img_process(img_path,long_side=640,stride_max=32): 15 | ''' 16 | 图像预处理 17 | ''' 18 | orgimg=cv2.imread(img_path) 19 | img0 = copy.deepcopy(orgimg) 20 | h0, w0 = orgimg.shape[:2] # orig hw 21 | r = long_side/ max(h0, w0) # resize image to img_size 22 | if r != 1: # always resize down, only resize up if training with augmentation 23 | interp = cv2.INTER_AREA if r < 1 else cv2.INTER_LINEAR 24 | img0 = cv2.resize(img0, (int(w0 * r), int(h0 * r)), interpolation=interp) 25 | 26 | imgsz = check_img_size(long_side, s=stride_max) # check img_size 27 | 28 | img = letterbox(img0, new_shape=imgsz,auto=False)[0] # auto True最小矩形 False固定尺度 29 | # Convert 30 | img = img[:, :, ::-1].transpose(2, 0, 1).copy() # BGR to RGB, to 3x416x416 31 | img = torch.from_numpy(img) 32 | img = img.float() # uint8 to fp16/32 33 | img /= 255.0 # 0 - 255 to 0.0 - 1.0 34 | if img.ndimension() == 3: 35 | img = img.unsqueeze(0) 36 | return img,orgimg 37 | 38 | def img_vis(img,orgimg,pred,vis_thres = 0.6): 39 | ''' 40 | 预测可视化 41 | vis_thres: 可视化阈值 42 | ''' 43 | 44 | print('img.shape: ', img.shape) 45 | print('orgimg.shape: ', orgimg.shape) 46 | 47 | no_vis_nums=0 48 | # Process detections 49 | for i, det in enumerate(pred): # detections per image 50 | gn = torch.tensor(orgimg.shape)[[1, 0, 1, 0]] # normalization gain whwh 51 | gn_lks = torch.tensor(orgimg.shape)[[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]] # normalization gain landmarks 52 | if len(det): 53 | # Rescale boxes from img_size to im0 size 54 | det[:, :4] = scale_coords(img.shape[2:], det[:, :4], orgimg.shape).round() 55 | 56 | # Print results 57 | for c in det[:, -1].unique(): 58 | n = (det[:, -1] == c).sum() # detections per class 59 | 60 | det[:, 5:15] = scale_coords_landmarks(img.shape[2:], det[:, 5:15], orgimg.shape).round() 61 | 62 | for j in range(det.size()[0]): 63 | 64 | 65 | if det[j, 4].cpu().numpy() < vis_thres: 66 | no_vis_nums+=1 67 | continue 68 | 69 | xywh = (xyxy2xywh(det[j, :4].view(1, 4)) / gn).view(-1).tolist() 70 | conf = det[j, 4].cpu().numpy() 71 | landmarks = (det[j, 5:15].view(1, 10) / gn_lks).view(-1).tolist() 72 | class_num = det[j, 15].cpu().numpy() 73 | orgimg = show_results(orgimg, xywh, conf, landmarks, class_num) 74 | 75 | cv2.imwrite(cur_path+'/result.jpg', orgimg) 76 | print('result save in '+cur_path+'/result.jpg') 77 | 78 | 79 | if __name__ == '__main__': 80 | parser = argparse.ArgumentParser() 81 | parser.add_argument('--img_path', type=str, default=cur_path+"/sample.jpg", help='img path') 82 | parser.add_argument('--trt_path', type=str, required=True, help='trt_path') 83 | parser.add_argument('--output_shape', type=list, default=[1,25200,16], help='input[1,3,640,640] -> output[1,25200,16]') 84 | opt = parser.parse_args() 85 | 86 | 87 | img,orgimg=img_process(opt.img_path) 88 | model=TrtModel(opt.trt_path) 89 | pred=model(img.numpy()).reshape(opt.output_shape) # forward 90 | model.destroy() 91 | 92 | # Apply NMS 93 | pred = non_max_suppression_face(torch.from_numpy(pred), conf_thres=0.3, iou_thres=0.5) 94 | 95 | # ============可视化================ 96 | img_vis(img,orgimg,pred) 97 | 98 | 99 | -------------------------------------------------------------------------------- /torch2trt/readme.md: -------------------------------------------------------------------------------- 1 | English | [简体中文](readme_CN.md) 2 | 3 | 4 | 5 | # Overall process 6 | 7 | ## 1.Pytorch->TensorRT 8 | 9 | ```shell 10 | python export.py --weights "torch's path" --onnx2trt --fp16_trt 11 | ``` 12 | 13 | 14 | ## 2.TensorRT inference 15 | ```shell 16 | python torch2trt/main.py --trt_path "trt's path" 17 | ``` 18 | Image preprocessing -> TensorRT inference -> visualization 19 | 20 | 21 | 22 | # Time-consuming comparison 23 | 24 | | Backbone |Pytorch(ms) |TensorRT_FP16(ms) | 25 | |:---:|:----:|:----:| 26 | |yolov5n-0.5| 7.7 | 2.1 | 27 | |yolov5n-face| 7.7 | 2.4 | 28 | |yolov5s-face| 5.6 | 2.2 | 29 | |yolov5m-face| 9.9 | 3.3 | 30 | |yolov5l-face| 15.9 | 4.5 | 31 | 32 | > Pytorch=1.10.0+cu102 TensorRT=8.2.0.6 Hardware=rtx2080ti 33 | 34 | ```shell 35 | python torch2trt/speed.py --torch_path "torch's path" --trt_path "trt's path" 36 | ``` 37 | 38 | 39 | 40 | # Visualization 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 |
yolov5n-0.5yolov5n-face
52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 |
yolov5s-faceyolov5m-faceyolov5l-face
65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /torch2trt/readme_CN.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 整体流程 4 | 5 | ## 1.Pytorch->TensorRT 6 | 7 | ```shell 8 | python export.py --weights "torch权重路径" --onnx2trt --fp16_trt 9 | ``` 10 | 11 | 12 | ## 2.TensorRT推理 13 | ```shell 14 | python torch2trt/main.py --trt_path "trt权重路径" 15 | ``` 16 | 17 | 图像预处理 -> TensorRT推理 -> 可视化结果 18 | 19 | 20 | 21 | # 耗时对比 22 | 23 | | | Pytorch(ms) | TensorRT_FP16(ms) | 24 | |:---:|:----:|:----:| 25 | | yolov5n-0.5 | 7.7 | 2.1 | 26 | | yolov5n-face | 7.7 | 2.4 | 27 | | yolov5s-face | 5.6 | 2.2 | 28 | | yolov5m-face | 9.9 | 3.3 | 29 | | yolov5l-face | 15.9 | 4.5 | 30 | 31 | > Pytorch=1.10.0+cu102 TensorRT=8.2.0.6 Hardware=rtx2080ti 32 | 33 | ```shell 34 | python torch2trt/speed.py --torch_path "torch权重路径" --trt_path "trt权重路径" 35 | ``` 36 | 37 | 38 | 39 | # 可视化 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 |
yolov5n-0.5yolov5n-face
51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |
yolov5s-faceyolov5m-faceyolov5l-face
64 | 65 | 66 | -------------------------------------------------------------------------------- /torch2trt/sample.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/torch2trt/sample.jpg -------------------------------------------------------------------------------- /torch2trt/speed.py: -------------------------------------------------------------------------------- 1 | from models.experimental import attempt_load 2 | from torch2trt.trt_model import TrtModel 3 | import argparse 4 | import torch 5 | import time 6 | from tqdm import tqdm 7 | 8 | 9 | def run(model,img,warmup_iter,iter): 10 | 11 | 12 | print('start warm up...') 13 | for _ in tqdm(range(warmup_iter)): 14 | model(img) 15 | 16 | 17 | print('start calculate...') 18 | torch.cuda.synchronize() 19 | start = time.time() 20 | for __ in tqdm(range(iter)): 21 | model(img) 22 | torch.cuda.synchronize() 23 | end = time.time() 24 | return ((end - start) * 1000)/float(iter) 25 | 26 | if __name__ == '__main__': 27 | parser = argparse.ArgumentParser() 28 | parser.add_argument('--torch_path', type=str,required=True, help='torch weights path') 29 | parser.add_argument('--trt_path', type=str,required=True, help='tensorrt weights path') 30 | 31 | parser.add_argument('--device', type=int,default=0, help='cuda device') 32 | parser.add_argument('--img_shape', type=list,default=[1,3,640,640], help='tensorrt weights path') 33 | parser.add_argument('--warmup_iter', type=int, default=100,help='warm up iter') 34 | parser.add_argument('--iter', type=int, default=300,help='average elapsed time of iterations') 35 | opt = parser.parse_args() 36 | 37 | 38 | # -----------------------torch----------------------------------------- 39 | img = torch.zeros(opt.img_shape) 40 | model = attempt_load(opt.torch_path, map_location=torch.device('cpu')) # load FP32 model 41 | model.eval() 42 | total_time=run(model.to(opt.device),img.to(opt.device),opt.warmup_iter,opt.iter) 43 | print('Pytorch is %.2f ms/img'%total_time) 44 | 45 | # -----------------------tensorrt----------------------------------------- 46 | model=TrtModel(opt.trt_path) 47 | total_time=run(model,img.numpy(),opt.warmup_iter,opt.iter) 48 | model.destroy() 49 | print('TensorRT is %.2f ms/img'%total_time) 50 | -------------------------------------------------------------------------------- /torch2trt/trt_model.py: -------------------------------------------------------------------------------- 1 | import pycuda.autoinit 2 | import pycuda.driver as cuda 3 | import tensorrt as trt 4 | import numpy as np 5 | 6 | EXPLICIT_BATCH = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) 7 | TRT_LOGGER = trt.Logger(trt.Logger.WARNING) 8 | def GiB(val): 9 | return val * 1 << 30 10 | 11 | def ONNX_to_TRT(onnx_model_path=None,trt_engine_path=None,fp16_mode=False): 12 | """ 13 | 仅适用TensorRT V8版本 14 | 生成cudaEngine,并保存引擎文件(仅支持固定输入尺度) 15 | 16 | fp16_mode: True则fp16预测 17 | onnx_model_path: 将加载的onnx权重路径 18 | trt_engine_path: trt引擎文件保存路径 19 | """ 20 | builder = trt.Builder(TRT_LOGGER) 21 | network = builder.create_network(EXPLICIT_BATCH) 22 | parser = trt.OnnxParser(network, TRT_LOGGER) 23 | 24 | config = builder.create_builder_config() 25 | config.max_workspace_size=GiB(1) 26 | if fp16_mode: 27 | config.set_flag(trt.BuilderFlag.FP16) 28 | with open(onnx_model_path, 'rb') as model: 29 | assert parser.parse(model.read()) 30 | serialized_engine=builder.build_serialized_network(network, config) 31 | 32 | 33 | with open(trt_engine_path, 'wb') as f: 34 | f.write(serialized_engine) # 序列化 35 | 36 | print('TensorRT file in ' + trt_engine_path) 37 | print('============ONNX->TensorRT SUCCESS============') 38 | 39 | class TrtModel(): 40 | ''' 41 | TensorRT infer 42 | ''' 43 | def __init__(self,trt_path): 44 | self.ctx=cuda.Device(0).make_context() 45 | stream = cuda.Stream() 46 | TRT_LOGGER = trt.Logger(trt.Logger.INFO) 47 | runtime = trt.Runtime(TRT_LOGGER) 48 | 49 | # Deserialize the engine from file 50 | with open(trt_path, "rb") as f: 51 | engine = runtime.deserialize_cuda_engine(f.read()) 52 | context = engine.create_execution_context() 53 | 54 | host_inputs = [] 55 | cuda_inputs = [] 56 | host_outputs = [] 57 | cuda_outputs = [] 58 | bindings = [] 59 | 60 | for binding in engine: 61 | print('bingding:', binding, engine.get_binding_shape(binding)) 62 | size = trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_size 63 | dtype = trt.nptype(engine.get_binding_dtype(binding)) 64 | # Allocate host and device buffers 65 | host_mem = cuda.pagelocked_empty(size, dtype) 66 | cuda_mem = cuda.mem_alloc(host_mem.nbytes) 67 | # Append the device buffer to device bindings. 68 | bindings.append(int(cuda_mem)) 69 | # Append to the appropriate list. 70 | if engine.binding_is_input(binding): 71 | self.input_w = engine.get_binding_shape(binding)[-1] 72 | self.input_h = engine.get_binding_shape(binding)[-2] 73 | host_inputs.append(host_mem) 74 | cuda_inputs.append(cuda_mem) 75 | else: 76 | host_outputs.append(host_mem) 77 | cuda_outputs.append(cuda_mem) 78 | 79 | # Store 80 | self.stream = stream 81 | self.context = context 82 | self.engine = engine 83 | self.host_inputs = host_inputs 84 | self.cuda_inputs = cuda_inputs 85 | self.host_outputs = host_outputs 86 | self.cuda_outputs = cuda_outputs 87 | self.bindings = bindings 88 | self.batch_size = engine.max_batch_size 89 | 90 | def __call__(self,img_np_nchw): 91 | ''' 92 | TensorRT推理 93 | :param img_np_nchw: 输入图像 94 | ''' 95 | self.ctx.push() 96 | 97 | # Restore 98 | stream = self.stream 99 | context = self.context 100 | engine = self.engine 101 | host_inputs = self.host_inputs 102 | cuda_inputs = self.cuda_inputs 103 | host_outputs = self.host_outputs 104 | cuda_outputs = self.cuda_outputs 105 | bindings = self.bindings 106 | 107 | np.copyto(host_inputs[0], img_np_nchw.ravel()) 108 | cuda.memcpy_htod_async(cuda_inputs[0], host_inputs[0], stream) 109 | context.execute_async(batch_size=self.batch_size, bindings=bindings, stream_handle=stream.handle) 110 | cuda.memcpy_dtoh_async(host_outputs[0], cuda_outputs[0], stream) 111 | stream.synchronize() 112 | self.ctx.pop() 113 | return host_outputs[0] 114 | 115 | 116 | def destroy(self): 117 | # Remove any context from the top of the context stack, deactivating it. 118 | self.ctx.pop() 119 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/utils/__init__.py -------------------------------------------------------------------------------- /utils/activations.py: -------------------------------------------------------------------------------- 1 | # Activation functions 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | 8 | # SiLU https://arxiv.org/pdf/1606.08415.pdf ---------------------------------------------------------------------------- 9 | class SiLU(nn.Module): # export-friendly version of nn.SiLU() 10 | @staticmethod 11 | def forward(x): 12 | return x * torch.sigmoid(x) 13 | 14 | 15 | class Hardswish(nn.Module): # export-friendly version of nn.Hardswish() 16 | @staticmethod 17 | def forward(x): 18 | # return x * F.hardsigmoid(x) # for torchscript and CoreML 19 | return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX 20 | 21 | 22 | class MemoryEfficientSwish(nn.Module): 23 | class F(torch.autograd.Function): 24 | @staticmethod 25 | def forward(ctx, x): 26 | ctx.save_for_backward(x) 27 | return x * torch.sigmoid(x) 28 | 29 | @staticmethod 30 | def backward(ctx, grad_output): 31 | x = ctx.saved_tensors[0] 32 | sx = torch.sigmoid(x) 33 | return grad_output * (sx * (1 + x * (1 - sx))) 34 | 35 | def forward(self, x): 36 | return self.F.apply(x) 37 | 38 | 39 | # Mish https://github.com/digantamisra98/Mish -------------------------------------------------------------------------- 40 | class Mish(nn.Module): 41 | @staticmethod 42 | def forward(x): 43 | return x * F.softplus(x).tanh() 44 | 45 | 46 | class MemoryEfficientMish(nn.Module): 47 | class F(torch.autograd.Function): 48 | @staticmethod 49 | def forward(ctx, x): 50 | ctx.save_for_backward(x) 51 | return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x))) 52 | 53 | @staticmethod 54 | def backward(ctx, grad_output): 55 | x = ctx.saved_tensors[0] 56 | sx = torch.sigmoid(x) 57 | fx = F.softplus(x).tanh() 58 | return grad_output * (fx + x * sx * (1 - fx * fx)) 59 | 60 | def forward(self, x): 61 | return self.F.apply(x) 62 | 63 | 64 | # FReLU https://arxiv.org/abs/2007.11824 ------------------------------------------------------------------------------- 65 | class FReLU(nn.Module): 66 | def __init__(self, c1, k=3): # ch_in, kernel 67 | super().__init__() 68 | self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False) 69 | self.bn = nn.BatchNorm2d(c1) 70 | 71 | def forward(self, x): 72 | return torch.max(x, self.bn(self.conv(x))) 73 | -------------------------------------------------------------------------------- /utils/autoanchor.py: -------------------------------------------------------------------------------- 1 | # Auto-anchor utils 2 | 3 | import numpy as np 4 | import torch 5 | import yaml 6 | from scipy.cluster.vq import kmeans 7 | from tqdm import tqdm 8 | 9 | from utils.general import colorstr 10 | 11 | 12 | def check_anchor_order(m): 13 | # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary 14 | a = m.anchor_grid.prod(-1).view(-1) # anchor area 15 | da = a[-1] - a[0] # delta a 16 | ds = m.stride[-1] - m.stride[0] # delta s 17 | if da.sign() != ds.sign(): # same order 18 | print('Reversing anchor order') 19 | m.anchors[:] = m.anchors.flip(0) 20 | m.anchor_grid[:] = m.anchor_grid.flip(0) 21 | 22 | 23 | def check_anchors(dataset, model, thr=4.0, imgsz=640): 24 | # Check anchor fit to data, recompute if necessary 25 | prefix = colorstr('autoanchor: ') 26 | print(f'\n{prefix}Analyzing anchors... ', end='') 27 | m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect() 28 | shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True) 29 | scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale 30 | wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh 31 | 32 | def metric(k): # compute metric 33 | r = wh[:, None] / k[None] 34 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric 35 | best = x.max(1)[0] # best_x 36 | aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold 37 | bpr = (best > 1. / thr).float().mean() # best possible recall 38 | return bpr, aat 39 | 40 | bpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2)) 41 | print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='') 42 | if bpr < 0.98: # threshold to recompute 43 | print('. Attempting to improve anchors, please wait...') 44 | na = m.anchor_grid.numel() // 2 # number of anchors 45 | new_anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False) 46 | new_bpr = metric(new_anchors.reshape(-1, 2))[0] 47 | if new_bpr > bpr: # replace anchors 48 | new_anchors = torch.tensor(new_anchors, device=m.anchors.device).type_as(m.anchors) 49 | m.anchor_grid[:] = new_anchors.clone().view_as(m.anchor_grid) # for inference 50 | m.anchors[:] = new_anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss 51 | check_anchor_order(m) 52 | print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.') 53 | else: 54 | print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.') 55 | print('') # newline 56 | 57 | 58 | def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): 59 | """ Creates kmeans-evolved anchors from training dataset 60 | 61 | Arguments: 62 | path: path to dataset *.yaml, or a loaded dataset 63 | n: number of anchors 64 | img_size: image size used for training 65 | thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0 66 | gen: generations to evolve anchors using genetic algorithm 67 | verbose: print all results 68 | 69 | Return: 70 | k: kmeans evolved anchors 71 | 72 | Usage: 73 | from utils.autoanchor import *; _ = kmean_anchors() 74 | """ 75 | thr = 1. / thr 76 | prefix = colorstr('autoanchor: ') 77 | 78 | def metric(k, wh): # compute metrics 79 | r = wh[:, None] / k[None] 80 | x = torch.min(r, 1. / r).min(2)[0] # ratio metric 81 | # x = wh_iou(wh, torch.tensor(k)) # iou metric 82 | return x, x.max(1)[0] # x, best_x 83 | 84 | def anchor_fitness(k): # mutation fitness 85 | _, best = metric(torch.tensor(k, dtype=torch.float32), wh) 86 | return (best * (best > thr).float()).mean() # fitness 87 | 88 | def print_results(k): 89 | k = k[np.argsort(k.prod(1))] # sort small to large 90 | x, best = metric(k, wh0) 91 | bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr 92 | print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr') 93 | print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' 94 | f'past_thr={x[x > thr].mean():.3f}-mean: ', end='') 95 | for i, x in enumerate(k): 96 | print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg 97 | return k 98 | 99 | if isinstance(path, str): # *.yaml file 100 | with open(path) as f: 101 | data_dict = yaml.load(f, Loader=yaml.SafeLoader) # model dict 102 | from utils.datasets import LoadImagesAndLabels 103 | dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True) 104 | else: 105 | dataset = path # dataset 106 | 107 | # Get label wh 108 | shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True) 109 | wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh 110 | 111 | # Filter 112 | i = (wh0 < 3.0).any(1).sum() 113 | if i: 114 | print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.') 115 | wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels 116 | # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1 117 | 118 | # Kmeans calculation 119 | print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...') 120 | s = wh.std(0) # sigmas for whitening 121 | k, dist = kmeans(wh / s, n, iter=30) # points, mean distance 122 | k *= s 123 | wh = torch.tensor(wh, dtype=torch.float32) # filtered 124 | wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered 125 | k = print_results(k) 126 | 127 | # Plot 128 | # k, d = [None] * 20, [None] * 20 129 | # for i in tqdm(range(1, 21)): 130 | # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance 131 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True) 132 | # ax = ax.ravel() 133 | # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.') 134 | # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh 135 | # ax[0].hist(wh[wh[:, 0]<100, 0],400) 136 | # ax[1].hist(wh[wh[:, 1]<100, 1],400) 137 | # fig.savefig('wh.png', dpi=200) 138 | 139 | # Evolve 140 | npr = np.random 141 | f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma 142 | pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar 143 | for _ in pbar: 144 | v = np.ones(sh) 145 | while (v == 1).all(): # mutate until a change occurs (prevent duplicates) 146 | v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0) 147 | kg = (k.copy() * v).clip(min=2.0) 148 | fg = anchor_fitness(kg) 149 | if fg > f: 150 | f, k = fg, kg.copy() 151 | pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}' 152 | if verbose: 153 | print_results(k) 154 | 155 | return print_results(k) 156 | -------------------------------------------------------------------------------- /utils/aws/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/utils/aws/__init__.py -------------------------------------------------------------------------------- /utils/aws/mime.sh: -------------------------------------------------------------------------------- 1 | # AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/ 2 | # This script will run on every instance restart, not only on first start 3 | # --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA --- 4 | 5 | Content-Type: multipart/mixed; boundary="//" 6 | MIME-Version: 1.0 7 | 8 | --// 9 | Content-Type: text/cloud-config; charset="us-ascii" 10 | MIME-Version: 1.0 11 | Content-Transfer-Encoding: 7bit 12 | Content-Disposition: attachment; filename="cloud-config.txt" 13 | 14 | #cloud-config 15 | cloud_final_modules: 16 | - [scripts-user, always] 17 | 18 | --// 19 | Content-Type: text/x-shellscript; charset="us-ascii" 20 | MIME-Version: 1.0 21 | Content-Transfer-Encoding: 7bit 22 | Content-Disposition: attachment; filename="userdata.txt" 23 | 24 | #!/bin/bash 25 | # --- paste contents of userdata.sh here --- 26 | --// 27 | -------------------------------------------------------------------------------- /utils/aws/resume.py: -------------------------------------------------------------------------------- 1 | # Resume all interrupted trainings in yolov5/ dir including DDP trainings 2 | # Usage: $ python utils/aws/resume.py 3 | 4 | import os 5 | import sys 6 | from pathlib import Path 7 | 8 | import torch 9 | import yaml 10 | 11 | sys.path.append('./') # to run '$ python *.py' files in subdirectories 12 | 13 | port = 0 # --master_port 14 | path = Path('').resolve() 15 | for last in path.rglob('*/**/last.pt'): 16 | ckpt = torch.load(last) 17 | if ckpt['optimizer'] is None: 18 | continue 19 | 20 | # Load opt.yaml 21 | with open(last.parent.parent / 'opt.yaml') as f: 22 | opt = yaml.load(f, Loader=yaml.SafeLoader) 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 && sudo chmod -R 777 yolov5 11 | cd yolov5 12 | bash data/scripts/get_coco.sh && echo "Data 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/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==18.1 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 | # Google utils: https://cloud.google.com/storage/docs/reference/libraries 2 | 3 | import os 4 | import platform 5 | import subprocess 6 | import time 7 | from pathlib import Path 8 | 9 | import requests 10 | import torch 11 | 12 | 13 | def gsutil_getsize(url=''): 14 | # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du 15 | s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8') 16 | return eval(s.split(' ')[0]) if len(s) else 0 # bytes 17 | 18 | 19 | def attempt_download(file, repo='ultralytics/yolov5'): 20 | # Attempt file download if does not exist 21 | file = Path(str(file).strip().replace("'", '').lower()) 22 | 23 | if not file.exists(): 24 | try: 25 | response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api 26 | assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...] 27 | tag = response['tag_name'] # i.e. 'v1.0' 28 | except: # fallback plan 29 | assets = ['yolov5.pt', 'yolov5.pt', 'yolov5l.pt', 'yolov5x.pt'] 30 | tag = subprocess.check_output('git tag', shell=True).decode('utf-8').split('\n')[-2] 31 | 32 | name = file.name 33 | if name in assets: 34 | msg = f'{file} missing, try downloading from https://github.com/{repo}/releases/' 35 | redundant = False # second download option 36 | try: # GitHub 37 | url = f'https://github.com/{repo}/releases/download/{tag}/{name}' 38 | print(f'Downloading {url} to {file}...') 39 | torch.hub.download_url_to_file(url, file) 40 | assert file.exists() and file.stat().st_size > 1E6 # check 41 | except Exception as e: # GCP 42 | print(f'Download error: {e}') 43 | assert redundant, 'No secondary mirror' 44 | url = f'https://storage.googleapis.com/{repo}/ckpt/{name}' 45 | print(f'Downloading {url} to {file}...') 46 | os.system(f'curl -L {url} -o {file}') # torch.hub.download_url_to_file(url, weights) 47 | finally: 48 | if not file.exists() or file.stat().st_size < 1E6: # check 49 | file.unlink(missing_ok=True) # remove partial downloads 50 | print(f'ERROR: Download failure: {msg}') 51 | print('') 52 | return 53 | 54 | 55 | def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'): 56 | # Downloads a file from Google Drive. from yolov5.utils.google_utils import *; gdrive_download() 57 | t = time.time() 58 | file = Path(file) 59 | cookie = Path('cookie') # gdrive cookie 60 | print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='') 61 | file.unlink(missing_ok=True) # remove existing file 62 | cookie.unlink(missing_ok=True) # remove existing cookie 63 | 64 | # Attempt file download 65 | out = "NUL" if platform.system() == "Windows" else "/dev/null" 66 | os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}') 67 | if os.path.exists('cookie'): # large file 68 | s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}' 69 | else: # small file 70 | s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"' 71 | r = os.system(s) # execute, capture return 72 | cookie.unlink(missing_ok=True) # remove existing cookie 73 | 74 | # Error check 75 | if r != 0: 76 | file.unlink(missing_ok=True) # remove partial 77 | print('Download error ') # raise Exception('Download error') 78 | return r 79 | 80 | # Unzip if archive 81 | if file.suffix == '.zip': 82 | print('unzipping... ', end='') 83 | os.system(f'unzip -q {file}') # unzip 84 | file.unlink() # remove zip to free space 85 | 86 | print(f'Done ({time.time() - t:.1f}s)') 87 | return r 88 | 89 | 90 | def get_token(cookie="./cookie"): 91 | with open(cookie) as f: 92 | for line in f: 93 | if "download" in line: 94 | return line.split()[-1] 95 | return "" 96 | 97 | # def upload_blob(bucket_name, source_file_name, destination_blob_name): 98 | # # Uploads a file to a bucket 99 | # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python 100 | # 101 | # storage_client = storage.Client() 102 | # bucket = storage_client.get_bucket(bucket_name) 103 | # blob = bucket.blob(destination_blob_name) 104 | # 105 | # blob.upload_from_filename(source_file_name) 106 | # 107 | # print('File {} uploaded to {}.'.format( 108 | # source_file_name, 109 | # destination_blob_name)) 110 | # 111 | # 112 | # def download_blob(bucket_name, source_blob_name, destination_file_name): 113 | # # Uploads a blob from a bucket 114 | # storage_client = storage.Client() 115 | # bucket = storage_client.get_bucket(bucket_name) 116 | # blob = bucket.blob(source_blob_name) 117 | # 118 | # blob.download_to_filename(destination_file_name) 119 | # 120 | # print('Blob {} downloaded to {}.'.format( 121 | # source_blob_name, 122 | # destination_file_name)) 123 | -------------------------------------------------------------------------------- /utils/infer_utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | 4 | 5 | def decode_infer(output, stride): 6 | # logging.info(torch.tensor(output.shape[0])) 7 | # logging.info(output.shape) 8 | # # bz is batch-size 9 | # bz = tuple(torch.tensor(output.shape[0])) 10 | # gridsize = tuple(torch.tensor(output.shape[-1])) 11 | # logging.info(gridsize) 12 | sh = torch.tensor(output.shape) 13 | bz = sh[0] 14 | gridsize = sh[-1] 15 | 16 | output = output.permute(0, 2, 3, 1) 17 | output = output.view(bz, gridsize, gridsize, self.gt_per_grid, 5+self.numclass) 18 | x1y1, x2y2, conf, prob = torch.split( 19 | output, [2, 2, 1, self.numclass], dim=4) 20 | 21 | shiftx = torch.arange(0, gridsize, dtype=torch.float32) 22 | shifty = torch.arange(0, gridsize, dtype=torch.float32) 23 | shifty, shiftx = torch.meshgrid([shiftx, shifty]) 24 | shiftx = shiftx.unsqueeze(-1).repeat(bz, 1, 1, self.gt_per_grid) 25 | shifty = shifty.unsqueeze(-1).repeat(bz, 1, 1, self.gt_per_grid) 26 | 27 | xy_grid = torch.stack([shiftx, shifty], dim=4).cuda() 28 | x1y1 = (xy_grid+0.5-torch.exp(x1y1))*stride 29 | x2y2 = (xy_grid+0.5+torch.exp(x2y2))*stride 30 | 31 | xyxy = torch.cat((x1y1, x2y2), dim=4) 32 | conf = torch.sigmoid(conf) 33 | prob = torch.sigmoid(prob) 34 | output = torch.cat((xyxy, conf, prob), 4) 35 | output = output.view(bz, -1, 5+self.numclass) 36 | return output -------------------------------------------------------------------------------- /utils/loss.py: -------------------------------------------------------------------------------- 1 | # Loss functions 2 | 3 | import torch 4 | import torch.nn as nn 5 | import numpy as np 6 | from utils.general import bbox_iou 7 | from utils.torch_utils import is_parallel 8 | 9 | 10 | def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441 11 | # return positive, negative label smoothing BCE targets 12 | return 1.0 - 0.5 * eps, 0.5 * eps 13 | 14 | 15 | class BCEBlurWithLogitsLoss(nn.Module): 16 | # BCEwithLogitLoss() with reduced missing label effects. 17 | def __init__(self, alpha=0.05): 18 | super(BCEBlurWithLogitsLoss, self).__init__() 19 | self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss() 20 | self.alpha = alpha 21 | 22 | def forward(self, pred, true): 23 | loss = self.loss_fcn(pred, true) 24 | pred = torch.sigmoid(pred) # prob from logits 25 | dx = pred - true # reduce only missing label effects 26 | # dx = (pred - true).abs() # reduce missing label and false label effects 27 | alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4)) 28 | loss *= alpha_factor 29 | return loss.mean() 30 | 31 | 32 | class FocalLoss(nn.Module): 33 | # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) 34 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): 35 | super(FocalLoss, self).__init__() 36 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() 37 | self.gamma = gamma 38 | self.alpha = alpha 39 | self.reduction = loss_fcn.reduction 40 | self.loss_fcn.reduction = 'none' # required to apply FL to each element 41 | 42 | def forward(self, pred, true): 43 | loss = self.loss_fcn(pred, true) 44 | # p_t = torch.exp(-loss) 45 | # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability 46 | 47 | # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py 48 | pred_prob = torch.sigmoid(pred) # prob from logits 49 | p_t = true * pred_prob + (1 - true) * (1 - pred_prob) 50 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) 51 | modulating_factor = (1.0 - p_t) ** self.gamma 52 | loss *= alpha_factor * modulating_factor 53 | 54 | if self.reduction == 'mean': 55 | return loss.mean() 56 | elif self.reduction == 'sum': 57 | return loss.sum() 58 | else: # 'none' 59 | return loss 60 | 61 | 62 | class QFocalLoss(nn.Module): 63 | # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5) 64 | def __init__(self, loss_fcn, gamma=1.5, alpha=0.25): 65 | super(QFocalLoss, self).__init__() 66 | self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss() 67 | self.gamma = gamma 68 | self.alpha = alpha 69 | self.reduction = loss_fcn.reduction 70 | self.loss_fcn.reduction = 'none' # required to apply FL to each element 71 | 72 | def forward(self, pred, true): 73 | loss = self.loss_fcn(pred, true) 74 | 75 | pred_prob = torch.sigmoid(pred) # prob from logits 76 | alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha) 77 | modulating_factor = torch.abs(true - pred_prob) ** self.gamma 78 | loss *= alpha_factor * modulating_factor 79 | 80 | if self.reduction == 'mean': 81 | return loss.mean() 82 | elif self.reduction == 'sum': 83 | return loss.sum() 84 | else: # 'none' 85 | return loss 86 | 87 | class WingLoss(nn.Module): 88 | def __init__(self, w=10, e=2): 89 | super(WingLoss, self).__init__() 90 | # https://arxiv.org/pdf/1711.06753v4.pdf Figure 5 91 | self.w = w 92 | self.e = e 93 | self.C = self.w - self.w * np.log(1 + self.w / self.e) 94 | 95 | def forward(self, x, t, sigma=1): 96 | weight = torch.ones_like(t) 97 | weight[torch.where(t==-1)] = 0 98 | diff = weight * (x - t) 99 | abs_diff = diff.abs() 100 | flag = (abs_diff.data < self.w).float() 101 | y = flag * self.w * torch.log(1 + abs_diff / self.e) + (1 - flag) * (abs_diff - self.C) 102 | return y.sum() 103 | 104 | class LandmarksLoss(nn.Module): 105 | # BCEwithLogitLoss() with reduced missing label effects. 106 | def __init__(self, alpha=1.0): 107 | super(LandmarksLoss, self).__init__() 108 | self.loss_fcn = WingLoss()#nn.SmoothL1Loss(reduction='sum') 109 | self.alpha = alpha 110 | 111 | def forward(self, pred, truel, mask): 112 | loss = self.loss_fcn(pred*mask, truel*mask) 113 | return loss / (torch.sum(mask) + 10e-14) 114 | 115 | 116 | def compute_loss(p, targets, model): # predictions, targets, model 117 | device = targets.device 118 | lcls, lbox, lobj, lmark = torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device), torch.zeros(1, device=device) 119 | tcls, tbox, indices, anchors, tlandmarks, lmks_mask = build_targets(p, targets, model) # targets 120 | h = model.hyp # hyperparameters 121 | 122 | # Define criteria 123 | BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device)) # weight=model.class_weights) 124 | BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device)) 125 | 126 | landmarks_loss = LandmarksLoss(1.0) 127 | 128 | # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3 129 | cp, cn = smooth_BCE(eps=0.0) 130 | 131 | # Focal loss 132 | g = h['fl_gamma'] # focal loss gamma 133 | if g > 0: 134 | BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g) 135 | 136 | # Losses 137 | nt = 0 # number of targets 138 | no = len(p) # number of outputs 139 | balance = [4.0, 1.0, 0.4] if no == 3 else [4.0, 1.0, 0.4, 0.1] # P3-5 or P3-6 140 | for i, pi in enumerate(p): # layer index, layer predictions 141 | b, a, gj, gi = indices[i] # image, anchor, gridy, gridx 142 | tobj = torch.zeros_like(pi[..., 0], device=device) # target obj 143 | 144 | n = b.shape[0] # number of targets 145 | if n: 146 | nt += n # cumulative targets 147 | ps = pi[b, a, gj, gi] # prediction subset corresponding to targets 148 | 149 | # Regression 150 | pxy = ps[:, :2].sigmoid() * 2. - 0.5 151 | pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i] 152 | pbox = torch.cat((pxy, pwh), 1) # predicted box 153 | iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target) 154 | lbox += (1.0 - iou).mean() # iou loss 155 | 156 | # Objectness 157 | tobj[b, a, gj, gi] = (1.0 - model.gr) + model.gr * iou.detach().clamp(0).type(tobj.dtype) # iou ratio 158 | 159 | # Classification 160 | if model.nc > 1: # cls loss (only if multiple classes) 161 | t = torch.full_like(ps[:, 15:], cn, device=device) # targets 162 | t[range(n), tcls[i]] = cp 163 | lcls += BCEcls(ps[:, 15:], t) # BCE 164 | 165 | # Append targets to text file 166 | # with open('targets.txt', 'a') as file: 167 | # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)] 168 | 169 | #landmarks loss 170 | #plandmarks = ps[:,5:15].sigmoid() * 8. - 4. 171 | plandmarks = ps[:,5:15] 172 | 173 | plandmarks[:, 0:2] = plandmarks[:, 0:2] * anchors[i] 174 | plandmarks[:, 2:4] = plandmarks[:, 2:4] * anchors[i] 175 | plandmarks[:, 4:6] = plandmarks[:, 4:6] * anchors[i] 176 | plandmarks[:, 6:8] = plandmarks[:, 6:8] * anchors[i] 177 | plandmarks[:, 8:10] = plandmarks[:,8:10] * anchors[i] 178 | 179 | lmark += landmarks_loss(plandmarks, tlandmarks[i], lmks_mask[i]) 180 | 181 | 182 | lobj += BCEobj(pi[..., 4], tobj) * balance[i] # obj loss 183 | 184 | s = 3 / no # output count scaling 185 | lbox *= h['box'] * s 186 | lobj *= h['obj'] * s * (1.4 if no == 4 else 1.) 187 | lcls *= h['cls'] * s 188 | lmark *= h['landmark'] * s 189 | 190 | bs = tobj.shape[0] # batch size 191 | 192 | loss = lbox + lobj + lcls + lmark 193 | return loss * bs, torch.cat((lbox, lobj, lcls, lmark, loss)).detach() 194 | 195 | 196 | def build_targets(p, targets, model): 197 | # Build targets for compute_loss(), input targets(image,class,x,y,w,h) 198 | det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module 199 | na, nt = det.na, targets.shape[0] # number of anchors, targets 200 | tcls, tbox, indices, anch, landmarks, lmks_mask = [], [], [], [], [], [] 201 | #gain = torch.ones(7, device=targets.device) # normalized to gridspace gain 202 | gain = torch.ones(17, device=targets.device) 203 | ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt) 204 | targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices 205 | 206 | g = 0.5 # bias 207 | off = torch.tensor([[0, 0], 208 | [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m 209 | # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm 210 | ], device=targets.device).float() * g # offsets 211 | 212 | for i in range(det.nl): 213 | anchors = det.anchors[i] 214 | gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]] # xyxy gain 215 | #landmarks 10 216 | gain[6:16] = torch.tensor(p[i].shape)[[3, 2, 3, 2, 3, 2, 3, 2, 3, 2]] # xyxy gain 217 | 218 | # Match targets to anchors 219 | t = targets * gain 220 | if nt: 221 | # Matches 222 | r = t[:, :, 4:6] / anchors[:, None] # wh ratio 223 | j = torch.max(r, 1. / r).max(2)[0] < model.hyp['anchor_t'] # compare 224 | # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2)) 225 | t = t[j] # filter 226 | 227 | # Offsets 228 | gxy = t[:, 2:4] # grid xy 229 | gxi = gain[[2, 3]] - gxy # inverse 230 | j, k = ((gxy % 1. < g) & (gxy > 1.)).T 231 | l, m = ((gxi % 1. < g) & (gxi > 1.)).T 232 | j = torch.stack((torch.ones_like(j), j, k, l, m)) 233 | t = t.repeat((5, 1, 1))[j] 234 | offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j] 235 | else: 236 | t = targets[0] 237 | offsets = 0 238 | 239 | # Define 240 | b, c = t[:, :2].long().T # image, class 241 | gxy = t[:, 2:4] # grid xy 242 | gwh = t[:, 4:6] # grid wh 243 | gij = (gxy - offsets).long() 244 | gi, gj = gij.T # grid xy indices 245 | 246 | # Append 247 | a = t[:, 16].long() # anchor indices 248 | indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices 249 | tbox.append(torch.cat((gxy - gij, gwh), 1)) # box 250 | anch.append(anchors[a]) # anchors 251 | tcls.append(c) # class 252 | 253 | #landmarks 254 | lks = t[:,6:16] 255 | #lks_mask = lks > 0 256 | #lks_mask = lks_mask.float() 257 | lks_mask = torch.where(lks < 0, torch.full_like(lks, 0.), torch.full_like(lks, 1.0)) 258 | 259 | #应该是关键点的坐标除以anch的宽高才对,便于模型学习。使用gwh会导致不同关键点的编码不同,没有统一的参考标准 260 | 261 | lks[:, [0, 1]] = (lks[:, [0, 1]] - gij) 262 | lks[:, [2, 3]] = (lks[:, [2, 3]] - gij) 263 | lks[:, [4, 5]] = (lks[:, [4, 5]] - gij) 264 | lks[:, [6, 7]] = (lks[:, [6, 7]] - gij) 265 | lks[:, [8, 9]] = (lks[:, [8, 9]] - gij) 266 | 267 | ''' 268 | #anch_w = torch.ones(5, device=targets.device).fill_(anchors[0][0]) 269 | #anch_wh = torch.ones(5, device=targets.device) 270 | anch_f_0 = (a == 0).unsqueeze(1).repeat(1, 5) 271 | anch_f_1 = (a == 1).unsqueeze(1).repeat(1, 5) 272 | anch_f_2 = (a == 2).unsqueeze(1).repeat(1, 5) 273 | lks[:, [0, 2, 4, 6, 8]] = torch.where(anch_f_0, lks[:, [0, 2, 4, 6, 8]] / anchors[0][0], lks[:, [0, 2, 4, 6, 8]]) 274 | lks[:, [0, 2, 4, 6, 8]] = torch.where(anch_f_1, lks[:, [0, 2, 4, 6, 8]] / anchors[1][0], lks[:, [0, 2, 4, 6, 8]]) 275 | lks[:, [0, 2, 4, 6, 8]] = torch.where(anch_f_2, lks[:, [0, 2, 4, 6, 8]] / anchors[2][0], lks[:, [0, 2, 4, 6, 8]]) 276 | 277 | lks[:, [1, 3, 5, 7, 9]] = torch.where(anch_f_0, lks[:, [1, 3, 5, 7, 9]] / anchors[0][1], lks[:, [1, 3, 5, 7, 9]]) 278 | lks[:, [1, 3, 5, 7, 9]] = torch.where(anch_f_1, lks[:, [1, 3, 5, 7, 9]] / anchors[1][1], lks[:, [1, 3, 5, 7, 9]]) 279 | lks[:, [1, 3, 5, 7, 9]] = torch.where(anch_f_2, lks[:, [1, 3, 5, 7, 9]] / anchors[2][1], lks[:, [1, 3, 5, 7, 9]]) 280 | 281 | #new_lks = lks[lks_mask>0] 282 | #print('new_lks: min --- ', torch.min(new_lks), ' max --- ', torch.max(new_lks)) 283 | 284 | lks_mask_1 = torch.where(lks < -3, torch.full_like(lks, 0.), torch.full_like(lks, 1.0)) 285 | lks_mask_2 = torch.where(lks > 3, torch.full_like(lks, 0.), torch.full_like(lks, 1.0)) 286 | 287 | lks_mask_new = lks_mask * lks_mask_1 * lks_mask_2 288 | lks_mask_new[:, 0] = lks_mask_new[:, 0] * lks_mask_new[:, 1] 289 | lks_mask_new[:, 1] = lks_mask_new[:, 0] * lks_mask_new[:, 1] 290 | lks_mask_new[:, 2] = lks_mask_new[:, 2] * lks_mask_new[:, 3] 291 | lks_mask_new[:, 3] = lks_mask_new[:, 2] * lks_mask_new[:, 3] 292 | lks_mask_new[:, 4] = lks_mask_new[:, 4] * lks_mask_new[:, 5] 293 | lks_mask_new[:, 5] = lks_mask_new[:, 4] * lks_mask_new[:, 5] 294 | lks_mask_new[:, 6] = lks_mask_new[:, 6] * lks_mask_new[:, 7] 295 | lks_mask_new[:, 7] = lks_mask_new[:, 6] * lks_mask_new[:, 7] 296 | lks_mask_new[:, 8] = lks_mask_new[:, 8] * lks_mask_new[:, 9] 297 | lks_mask_new[:, 9] = lks_mask_new[:, 8] * lks_mask_new[:, 9] 298 | ''' 299 | lks_mask_new = lks_mask 300 | lmks_mask.append(lks_mask_new) 301 | landmarks.append(lks) 302 | #print('lks: ', lks.size()) 303 | 304 | return tcls, tbox, indices, anch, landmarks, lmks_mask 305 | -------------------------------------------------------------------------------- /utils/metrics.py: -------------------------------------------------------------------------------- 1 | # Model validation metrics 2 | 3 | from pathlib import Path 4 | 5 | import matplotlib.pyplot as plt 6 | import numpy as np 7 | import torch 8 | 9 | from . import general 10 | 11 | 12 | def fitness(x): 13 | # Model fitness as a weighted combination of metrics 14 | w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95] 15 | return (x[:, :4] * w).sum(1) 16 | 17 | 18 | def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='precision-recall_curve.png', names=[]): 19 | """ Compute the average precision, given the recall and precision curves. 20 | Source: https://github.com/rafaelpadilla/Object-Detection-Metrics. 21 | # Arguments 22 | tp: True positives (nparray, nx1 or nx10). 23 | conf: Objectness value from 0-1 (nparray). 24 | pred_cls: Predicted object classes (nparray). 25 | target_cls: True object classes (nparray). 26 | plot: Plot precision-recall curve at mAP@0.5 27 | save_dir: Plot save directory 28 | # Returns 29 | The average precision as computed in py-faster-rcnn. 30 | """ 31 | 32 | # Sort by objectness 33 | i = np.argsort(-conf) 34 | tp, conf, pred_cls = tp[i], conf[i], pred_cls[i] 35 | 36 | # Find unique classes 37 | unique_classes = np.unique(target_cls) 38 | 39 | # Create Precision-Recall curve and compute AP for each class 40 | px, py = np.linspace(0, 1, 1000), [] # for plotting 41 | pr_score = 0.1 # score to evaluate P and R https://github.com/ultralytics/yolov3/issues/898 42 | s = [unique_classes.shape[0], tp.shape[1]] # number class, number iou thresholds (i.e. 10 for mAP0.5...0.95) 43 | ap, p, r = np.zeros(s), np.zeros(s), np.zeros(s) 44 | for ci, c in enumerate(unique_classes): 45 | i = pred_cls == c 46 | n_l = (target_cls == c).sum() # number of labels 47 | n_p = i.sum() # number of predictions 48 | 49 | if n_p == 0 or n_l == 0: 50 | continue 51 | else: 52 | # Accumulate FPs and TPs 53 | fpc = (1 - tp[i]).cumsum(0) 54 | tpc = tp[i].cumsum(0) 55 | 56 | # Recall 57 | recall = tpc / (n_l + 1e-16) # recall curve 58 | r[ci] = np.interp(-pr_score, -conf[i], recall[:, 0]) # r at pr_score, negative x, xp because xp decreases 59 | 60 | # Precision 61 | precision = tpc / (tpc + fpc) # precision curve 62 | p[ci] = np.interp(-pr_score, -conf[i], precision[:, 0]) # p at pr_score 63 | 64 | # AP from recall-precision curve 65 | for j in range(tp.shape[1]): 66 | ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j]) 67 | if plot and (j == 0): 68 | py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5 69 | 70 | # Compute F1 score (harmonic mean of precision and recall) 71 | f1 = 2 * p * r / (p + r + 1e-16) 72 | 73 | if plot: 74 | plot_pr_curve(px, py, ap, save_dir, names) 75 | 76 | return p, r, ap, f1, unique_classes.astype('int32') 77 | 78 | 79 | def compute_ap(recall, precision): 80 | """ Compute the average precision, given the recall and precision curves 81 | # Arguments 82 | recall: The recall curve (list) 83 | precision: The precision curve (list) 84 | # Returns 85 | Average precision, precision curve, recall curve 86 | """ 87 | 88 | # Append sentinel values to beginning and end 89 | mrec = np.concatenate(([0.], recall, [recall[-1] + 0.01])) 90 | mpre = np.concatenate(([1.], precision, [0.])) 91 | 92 | # Compute the precision envelope 93 | mpre = np.flip(np.maximum.accumulate(np.flip(mpre))) 94 | 95 | # Integrate area under curve 96 | method = 'interp' # methods: 'continuous', 'interp' 97 | if method == 'interp': 98 | x = np.linspace(0, 1, 101) # 101-point interp (COCO) 99 | ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate 100 | else: # 'continuous' 101 | i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes 102 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve 103 | 104 | return ap, mpre, mrec 105 | 106 | 107 | class ConfusionMatrix: 108 | # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix 109 | def __init__(self, nc, conf=0.25, iou_thres=0.45): 110 | self.matrix = np.zeros((nc + 1, nc + 1)) 111 | self.nc = nc # number of classes 112 | self.conf = conf 113 | self.iou_thres = iou_thres 114 | 115 | def process_batch(self, detections, labels): 116 | """ 117 | Return intersection-over-union (Jaccard index) of boxes. 118 | Both sets of boxes are expected to be in (x1, y1, x2, y2) format. 119 | Arguments: 120 | detections (Array[N, 6]), x1, y1, x2, y2, conf, class 121 | labels (Array[M, 5]), class, x1, y1, x2, y2 122 | Returns: 123 | None, updates confusion matrix accordingly 124 | """ 125 | detections = detections[detections[:, 4] > self.conf] 126 | gt_classes = labels[:, 0].int() 127 | detection_classes = detections[:, 5].int() 128 | iou = general.box_iou(labels[:, 1:], detections[:, :4]) 129 | 130 | x = torch.where(iou > self.iou_thres) 131 | if x[0].shape[0]: 132 | matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() 133 | if x[0].shape[0] > 1: 134 | matches = matches[matches[:, 2].argsort()[::-1]] 135 | matches = matches[np.unique(matches[:, 1], return_index=True)[1]] 136 | matches = matches[matches[:, 2].argsort()[::-1]] 137 | matches = matches[np.unique(matches[:, 0], return_index=True)[1]] 138 | else: 139 | matches = np.zeros((0, 3)) 140 | 141 | n = matches.shape[0] > 0 142 | m0, m1, _ = matches.transpose().astype(np.int16) 143 | for i, gc in enumerate(gt_classes): 144 | j = m0 == i 145 | if n and sum(j) == 1: 146 | self.matrix[gc, detection_classes[m1[j]]] += 1 # correct 147 | else: 148 | self.matrix[gc, self.nc] += 1 # background FP 149 | 150 | if n: 151 | for i, dc in enumerate(detection_classes): 152 | if not any(m1 == i): 153 | self.matrix[self.nc, dc] += 1 # background FN 154 | 155 | def matrix(self): 156 | return self.matrix 157 | 158 | def plot(self, save_dir='', names=()): 159 | try: 160 | import seaborn as sn 161 | 162 | array = self.matrix / (self.matrix.sum(0).reshape(1, self.nc + 1) + 1E-6) # normalize 163 | array[array < 0.005] = np.nan # don't annotate (would appear as 0.00) 164 | 165 | fig = plt.figure(figsize=(12, 9), tight_layout=True) 166 | sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size 167 | labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels 168 | sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True, 169 | xticklabels=names + ['background FN'] if labels else "auto", 170 | yticklabels=names + ['background FP'] if labels else "auto").set_facecolor((1, 1, 1)) 171 | fig.axes[0].set_xlabel('True') 172 | fig.axes[0].set_ylabel('Predicted') 173 | fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250) 174 | except Exception as e: 175 | pass 176 | 177 | def print(self): 178 | for i in range(self.nc + 1): 179 | print(' '.join(map(str, self.matrix[i]))) 180 | 181 | 182 | # Plots ---------------------------------------------------------------------------------------------------------------- 183 | 184 | def plot_pr_curve(px, py, ap, save_dir='.', names=()): 185 | fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True) 186 | py = np.stack(py, axis=1) 187 | 188 | if 0 < len(names) < 21: # show mAP in legend if < 10 classes 189 | for i, y in enumerate(py.T): 190 | ax.plot(px, y, linewidth=1, label=f'{names[i]} %.3f' % ap[i, 0]) # plot(recall, precision) 191 | else: 192 | ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision) 193 | 194 | ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean()) 195 | ax.set_xlabel('Recall') 196 | ax.set_ylabel('Precision') 197 | ax.set_xlim(0, 1) 198 | ax.set_ylim(0, 1) 199 | plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left") 200 | fig.savefig(Path(save_dir) / 'precision_recall_curve.png', dpi=250) 201 | -------------------------------------------------------------------------------- /utils/torch_utils.py: -------------------------------------------------------------------------------- 1 | # PyTorch utils 2 | 3 | import logging 4 | import math 5 | import os 6 | import subprocess 7 | import time 8 | from contextlib import contextmanager 9 | from copy import deepcopy 10 | from pathlib import Path 11 | 12 | import torch 13 | import torch.backends.cudnn as cudnn 14 | import torch.nn as nn 15 | import torch.nn.functional as F 16 | import torchvision 17 | 18 | try: 19 | import thop # for FLOPS computation 20 | except ImportError: 21 | thop = None 22 | logger = logging.getLogger(__name__) 23 | 24 | 25 | @contextmanager 26 | def torch_distributed_zero_first(local_rank: int): 27 | """ 28 | Decorator to make all processes in distributed training wait for each local_master to do something. 29 | """ 30 | if local_rank not in [-1, 0]: 31 | torch.distributed.barrier() 32 | yield 33 | if local_rank == 0: 34 | torch.distributed.barrier() 35 | 36 | 37 | def init_torch_seeds(seed=0): 38 | # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html 39 | torch.manual_seed(seed) 40 | if seed == 0: # slower, more reproducible 41 | cudnn.benchmark, cudnn.deterministic = False, True 42 | else: # faster, less reproducible 43 | cudnn.benchmark, cudnn.deterministic = True, False 44 | 45 | 46 | def git_describe(): 47 | # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe 48 | if Path('.git').exists(): 49 | return subprocess.check_output('git describe --tags --long --always', shell=True).decode('utf-8')[:-1] 50 | else: 51 | return '' 52 | 53 | 54 | def select_device(device='', batch_size=None): 55 | # device = 'cpu' or '0' or '0,1,2,3' 56 | s = f'YOLOv5 {git_describe()} torch {torch.__version__} ' # string 57 | cpu = device.lower() == 'cpu' 58 | if cpu: 59 | os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False 60 | elif device: # non-cpu device requested 61 | os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable 62 | assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability 63 | 64 | cuda = not cpu and torch.cuda.is_available() 65 | if cuda: 66 | n = torch.cuda.device_count() 67 | if n > 1 and batch_size: # check that batch_size is compatible with device_count 68 | assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}' 69 | space = ' ' * len(s) 70 | for i, d in enumerate(device.split(',') if device else range(n)): 71 | p = torch.cuda.get_device_properties(i) 72 | s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB 73 | else: 74 | s += 'CPU\n' 75 | 76 | logger.info(s) # skip a line 77 | return torch.device('cuda:0' if cuda else 'cpu') 78 | 79 | 80 | def time_synchronized(): 81 | # pytorch-accurate time 82 | if torch.cuda.is_available(): 83 | torch.cuda.synchronize() 84 | return time.time() 85 | 86 | 87 | def profile(x, ops, n=100, device=None): 88 | # profile a pytorch module or list of modules. Example usage: 89 | # x = torch.randn(16, 3, 640, 640) # input 90 | # m1 = lambda x: x * torch.sigmoid(x) 91 | # m2 = nn.SiLU() 92 | # profile(x, [m1, m2], n=100) # profile speed over 100 iterations 93 | 94 | device = device or torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') 95 | x = x.to(device) 96 | x.requires_grad = True 97 | print(torch.__version__, device.type, torch.cuda.get_device_properties(0) if device.type == 'cuda' else '') 98 | print(f"\n{'Params':>12s}{'GFLOPS':>12s}{'forward (ms)':>16s}{'backward (ms)':>16s}{'input':>24s}{'output':>24s}") 99 | for m in ops if isinstance(ops, list) else [ops]: 100 | m = m.to(device) if hasattr(m, 'to') else m # device 101 | m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m # type 102 | dtf, dtb, t = 0., 0., [0., 0., 0.] # dt forward, backward 103 | try: 104 | flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPS 105 | except: 106 | flops = 0 107 | 108 | for _ in range(n): 109 | t[0] = time_synchronized() 110 | y = m(x) 111 | t[1] = time_synchronized() 112 | try: 113 | _ = y.sum().backward() 114 | t[2] = time_synchronized() 115 | except: # no backward method 116 | t[2] = float('nan') 117 | dtf += (t[1] - t[0]) * 1000 / n # ms per op forward 118 | dtb += (t[2] - t[1]) * 1000 / n # ms per op backward 119 | 120 | s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' 121 | s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list' 122 | p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters 123 | print(f'{p:12.4g}{flops:12.4g}{dtf:16.4g}{dtb:16.4g}{str(s_in):>24s}{str(s_out):>24s}') 124 | 125 | 126 | def is_parallel(model): 127 | return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel) 128 | 129 | 130 | def intersect_dicts(da, db, exclude=()): 131 | # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values 132 | return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape} 133 | 134 | 135 | def initialize_weights(model): 136 | for m in model.modules(): 137 | t = type(m) 138 | if t is nn.Conv2d: 139 | pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 140 | elif t is nn.BatchNorm2d: 141 | m.eps = 1e-3 142 | m.momentum = 0.03 143 | elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]: 144 | m.inplace = True 145 | 146 | 147 | def find_modules(model, mclass=nn.Conv2d): 148 | # Finds layer indices matching module class 'mclass' 149 | return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)] 150 | 151 | 152 | def sparsity(model): 153 | # Return global model sparsity 154 | a, b = 0., 0. 155 | for p in model.parameters(): 156 | a += p.numel() 157 | b += (p == 0).sum() 158 | return b / a 159 | 160 | 161 | def prune(model, amount=0.3): 162 | # Prune model to requested global sparsity 163 | import torch.nn.utils.prune as prune 164 | print('Pruning model... ', end='') 165 | for name, m in model.named_modules(): 166 | if isinstance(m, nn.Conv2d): 167 | prune.l1_unstructured(m, name='weight', amount=amount) # prune 168 | prune.remove(m, 'weight') # make permanent 169 | print(' %.3g global sparsity' % sparsity(model)) 170 | 171 | 172 | def fuse_conv_and_bn(conv, bn): 173 | # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/ 174 | fusedconv = nn.Conv2d(conv.in_channels, 175 | conv.out_channels, 176 | kernel_size=conv.kernel_size, 177 | stride=conv.stride, 178 | padding=conv.padding, 179 | groups=conv.groups, 180 | bias=True).requires_grad_(False).to(conv.weight.device) 181 | 182 | # prepare filters 183 | w_conv = conv.weight.clone().view(conv.out_channels, -1) 184 | w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var))) 185 | fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.size())) 186 | 187 | # prepare spatial bias 188 | b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias 189 | b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps)) 190 | fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn) 191 | 192 | return fusedconv 193 | 194 | 195 | def model_info(model, verbose=False, img_size=640): 196 | # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320] 197 | n_p = sum(x.numel() for x in model.parameters()) # number parameters 198 | n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients 199 | if verbose: 200 | print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma')) 201 | for i, (name, p) in enumerate(model.named_parameters()): 202 | name = name.replace('module_list.', '') 203 | print('%5g %40s %9s %12g %20s %10.3g %10.3g' % 204 | (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())) 205 | 206 | try: # FLOPS 207 | from thop import profile 208 | stride = int(model.stride.max()) if hasattr(model, 'stride') else 32 209 | img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input 210 | flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPS 211 | img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float 212 | fs = ', %.1f GFLOPS' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPS 213 | except (ImportError, Exception): 214 | fs = '' 215 | 216 | logger.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}") 217 | 218 | 219 | def load_classifier(name='resnet101', n=2): 220 | # Loads a pretrained model reshaped to n-class output 221 | model = torchvision.models.__dict__[name](pretrained=True) 222 | 223 | # ResNet model properties 224 | # input_size = [3, 224, 224] 225 | # input_space = 'RGB' 226 | # input_range = [0, 1] 227 | # mean = [0.485, 0.456, 0.406] 228 | # std = [0.229, 0.224, 0.225] 229 | 230 | # Reshape output to n classes 231 | filters = model.fc.weight.shape[1] 232 | model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True) 233 | model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True) 234 | model.fc.out_features = n 235 | return model 236 | 237 | 238 | def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416) 239 | # scales img(bs,3,y,x) by ratio constrained to gs-multiple 240 | if ratio == 1.0: 241 | return img 242 | else: 243 | h, w = img.shape[2:] 244 | s = (int(h * ratio), int(w * ratio)) # new size 245 | img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize 246 | if not same_shape: # pad/crop img 247 | h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)] 248 | return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean 249 | 250 | 251 | def copy_attr(a, b, include=(), exclude=()): 252 | # Copy attributes from b to a, options to only include [...] and to exclude [...] 253 | for k, v in b.__dict__.items(): 254 | if (len(include) and k not in include) or k.startswith('_') or k in exclude: 255 | continue 256 | else: 257 | setattr(a, k, v) 258 | 259 | 260 | class ModelEMA: 261 | """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models 262 | Keep a moving average of everything in the model state_dict (parameters and buffers). 263 | This is intended to allow functionality like 264 | https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage 265 | A smoothed version of the weights is necessary for some training schemes to perform well. 266 | This class is sensitive where it is initialized in the sequence of model init, 267 | GPU assignment and distributed training wrappers. 268 | """ 269 | 270 | def __init__(self, model, decay=0.9999, updates=0): 271 | # Create EMA 272 | self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA 273 | # if next(model.parameters()).device.type != 'cpu': 274 | # self.ema.half() # FP16 EMA 275 | self.updates = updates # number of EMA updates 276 | self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs) 277 | for p in self.ema.parameters(): 278 | p.requires_grad_(False) 279 | 280 | def update(self, model): 281 | # Update EMA parameters 282 | with torch.no_grad(): 283 | self.updates += 1 284 | d = self.decay(self.updates) 285 | 286 | msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict 287 | for k, v in self.ema.state_dict().items(): 288 | if v.dtype.is_floating_point: 289 | v *= d 290 | v += (1. - d) * msd[k].detach() 291 | 292 | def update_attr(self, model, include=(), exclude=('process_group', 'reducer')): 293 | # Update EMA attributes 294 | copy_attr(self.ema, model, include, exclude) 295 | -------------------------------------------------------------------------------- /utils/wandb_logging/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/utils/wandb_logging/__init__.py -------------------------------------------------------------------------------- /utils/wandb_logging/log_dataset.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import yaml 4 | 5 | from wandb_utils import WandbLogger 6 | 7 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' 8 | 9 | 10 | def create_dataset_artifact(opt): 11 | with open(opt.data) as f: 12 | data = yaml.load(f, Loader=yaml.SafeLoader) # 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 | opt = parser.parse_args() 22 | opt.resume = False # Explicitly disallow resume check for dataset upload job 23 | 24 | create_dataset_artifact(opt) 25 | -------------------------------------------------------------------------------- /utils/wandb_logging/wandb_utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | from pathlib import Path 4 | 5 | import torch 6 | import yaml 7 | from tqdm import tqdm 8 | 9 | sys.path.append(str(Path(__file__).parent.parent.parent)) # add utils/ to path 10 | from utils.datasets import LoadImagesAndLabels 11 | from utils.datasets import img2label_paths 12 | from utils.general import colorstr, xywh2xyxy, check_dataset 13 | 14 | try: 15 | import wandb 16 | from wandb import init, finish 17 | except ImportError: 18 | wandb = None 19 | 20 | WANDB_ARTIFACT_PREFIX = 'wandb-artifact://' 21 | 22 | 23 | def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX): 24 | return from_string[len(prefix):] 25 | 26 | 27 | def check_wandb_config_file(data_config_file): 28 | wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path 29 | if Path(wandb_config).is_file(): 30 | return wandb_config 31 | return data_config_file 32 | 33 | 34 | def get_run_info(run_path): 35 | run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX)) 36 | run_id = run_path.stem 37 | project = run_path.parent.stem 38 | model_artifact_name = 'run_' + run_id + '_model' 39 | return run_id, project, model_artifact_name 40 | 41 | 42 | def check_wandb_resume(opt): 43 | process_wandb_config_ddp_mode(opt) if opt.global_rank not in [-1, 0] else None 44 | if isinstance(opt.resume, str): 45 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): 46 | if opt.global_rank not in [-1, 0]: # For resuming DDP runs 47 | run_id, project, model_artifact_name = get_run_info(opt.resume) 48 | api = wandb.Api() 49 | artifact = api.artifact(project + '/' + model_artifact_name + ':latest') 50 | modeldir = artifact.download() 51 | opt.weights = str(Path(modeldir) / "last.pt") 52 | return True 53 | return None 54 | 55 | 56 | def process_wandb_config_ddp_mode(opt): 57 | with open(opt.data) as f: 58 | data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict 59 | train_dir, val_dir = None, None 60 | if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX): 61 | api = wandb.Api() 62 | train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias) 63 | train_dir = train_artifact.download() 64 | train_path = Path(train_dir) / 'data/images/' 65 | data_dict['train'] = str(train_path) 66 | 67 | if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX): 68 | api = wandb.Api() 69 | val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias) 70 | val_dir = val_artifact.download() 71 | val_path = Path(val_dir) / 'data/images/' 72 | data_dict['val'] = str(val_path) 73 | if train_dir or val_dir: 74 | ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml') 75 | with open(ddp_data_path, 'w') as f: 76 | yaml.dump(data_dict, f) 77 | opt.data = ddp_data_path 78 | 79 | 80 | class WandbLogger(): 81 | def __init__(self, opt, name, run_id, data_dict, job_type='Training'): 82 | # Pre-training routine -- 83 | self.job_type = job_type 84 | self.wandb, self.wandb_run, self.data_dict = wandb, None if not wandb else wandb.run, data_dict 85 | # It's more elegant to stick to 1 wandb.init call, but useful config data is overwritten in the WandbLogger's wandb.init call 86 | if isinstance(opt.resume, str): # checks resume from artifact 87 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): 88 | run_id, project, model_artifact_name = get_run_info(opt.resume) 89 | model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name 90 | assert wandb, 'install wandb to resume wandb runs' 91 | # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config 92 | self.wandb_run = wandb.init(id=run_id, project=project, resume='allow') 93 | opt.resume = model_artifact_name 94 | elif self.wandb: 95 | self.wandb_run = wandb.init(config=opt, 96 | resume="allow", 97 | project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem, 98 | name=name, 99 | job_type=job_type, 100 | id=run_id) if not wandb.run else wandb.run 101 | if self.wandb_run: 102 | if self.job_type == 'Training': 103 | if not opt.resume: 104 | wandb_data_dict = self.check_and_upload_dataset(opt) if opt.upload_dataset else data_dict 105 | # Info useful for resuming from artifacts 106 | self.wandb_run.config.opt = vars(opt) 107 | self.wandb_run.config.data_dict = wandb_data_dict 108 | self.data_dict = self.setup_training(opt, data_dict) 109 | if self.job_type == 'Dataset Creation': 110 | self.data_dict = self.check_and_upload_dataset(opt) 111 | else: 112 | prefix = colorstr('wandb: ') 113 | print(f"{prefix}Install Weights & Biases for YOLOv5 logging with 'pip install wandb' (recommended)") 114 | 115 | def check_and_upload_dataset(self, opt): 116 | assert wandb, 'Install wandb to upload dataset' 117 | check_dataset(self.data_dict) 118 | config_path = self.log_dataset_artifact(opt.data, 119 | opt.single_cls, 120 | 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem) 121 | print("Created dataset config file ", config_path) 122 | with open(config_path) as f: 123 | wandb_data_dict = yaml.load(f, Loader=yaml.SafeLoader) 124 | return wandb_data_dict 125 | 126 | def setup_training(self, opt, data_dict): 127 | self.log_dict, self.current_epoch, self.log_imgs = {}, 0, 16 # Logging Constants 128 | self.bbox_interval = opt.bbox_interval 129 | if isinstance(opt.resume, str): 130 | modeldir, _ = self.download_model_artifact(opt) 131 | if modeldir: 132 | self.weights = Path(modeldir) / "last.pt" 133 | config = self.wandb_run.config 134 | opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str( 135 | self.weights), config.save_period, config.total_batch_size, config.bbox_interval, config.epochs, \ 136 | config.opt['hyp'] 137 | data_dict = dict(self.wandb_run.config.data_dict) # eliminates the need for config file to resume 138 | if 'val_artifact' not in self.__dict__: # If --upload_dataset is set, use the existing artifact, don't download 139 | self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'), 140 | opt.artifact_alias) 141 | self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'), 142 | opt.artifact_alias) 143 | self.result_artifact, self.result_table, self.val_table, self.weights = None, None, None, None 144 | if self.train_artifact_path is not None: 145 | train_path = Path(self.train_artifact_path) / 'data/images/' 146 | data_dict['train'] = str(train_path) 147 | if self.val_artifact_path is not None: 148 | val_path = Path(self.val_artifact_path) / 'data/images/' 149 | data_dict['val'] = str(val_path) 150 | self.val_table = self.val_artifact.get("val") 151 | self.map_val_table_path() 152 | if self.val_artifact is not None: 153 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") 154 | self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"]) 155 | if opt.bbox_interval == -1: 156 | self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1 157 | return data_dict 158 | 159 | def download_dataset_artifact(self, path, alias): 160 | if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX): 161 | dataset_artifact = wandb.use_artifact(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias) 162 | assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'" 163 | datadir = dataset_artifact.download() 164 | return datadir, dataset_artifact 165 | return None, None 166 | 167 | def download_model_artifact(self, opt): 168 | if opt.resume.startswith(WANDB_ARTIFACT_PREFIX): 169 | model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest") 170 | assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist' 171 | modeldir = model_artifact.download() 172 | epochs_trained = model_artifact.metadata.get('epochs_trained') 173 | total_epochs = model_artifact.metadata.get('total_epochs') 174 | assert epochs_trained < total_epochs, 'training to %g epochs is finished, nothing to resume.' % ( 175 | total_epochs) 176 | return modeldir, model_artifact 177 | return None, None 178 | 179 | def log_model(self, path, opt, epoch, fitness_score, best_model=False): 180 | model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={ 181 | 'original_url': str(path), 182 | 'epochs_trained': epoch + 1, 183 | 'save period': opt.save_period, 184 | 'project': opt.project, 185 | 'total_epochs': opt.epochs, 186 | 'fitness_score': fitness_score 187 | }) 188 | model_artifact.add_file(str(path / 'last.pt'), name='last.pt') 189 | wandb.log_artifact(model_artifact, 190 | aliases=['latest', 'epoch ' + str(self.current_epoch), 'best' if best_model else '']) 191 | print("Saving model artifact on epoch ", epoch + 1) 192 | 193 | def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False): 194 | with open(data_file) as f: 195 | data = yaml.load(f, Loader=yaml.SafeLoader) # data dict 196 | nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names']) 197 | names = {k: v for k, v in enumerate(names)} # to index dictionary 198 | self.train_artifact = self.create_dataset_table(LoadImagesAndLabels( 199 | data['train']), names, name='train') if data.get('train') else None 200 | self.val_artifact = self.create_dataset_table(LoadImagesAndLabels( 201 | data['val']), names, name='val') if data.get('val') else None 202 | if data.get('train'): 203 | data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train') 204 | if data.get('val'): 205 | data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val') 206 | path = data_file if overwrite_config else '_wandb.'.join(data_file.rsplit('.', 1)) # updated data.yaml path 207 | data.pop('download', None) 208 | with open(path, 'w') as f: 209 | yaml.dump(data, f) 210 | 211 | if self.job_type == 'Training': # builds correct artifact pipeline graph 212 | self.wandb_run.use_artifact(self.val_artifact) 213 | self.wandb_run.use_artifact(self.train_artifact) 214 | self.val_artifact.wait() 215 | self.val_table = self.val_artifact.get('val') 216 | self.map_val_table_path() 217 | else: 218 | self.wandb_run.log_artifact(self.train_artifact) 219 | self.wandb_run.log_artifact(self.val_artifact) 220 | return path 221 | 222 | def map_val_table_path(self): 223 | self.val_table_map = {} 224 | print("Mapping dataset") 225 | for i, data in enumerate(tqdm(self.val_table.data)): 226 | self.val_table_map[data[3]] = data[0] 227 | 228 | def create_dataset_table(self, dataset, class_to_id, name='dataset'): 229 | # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging 230 | artifact = wandb.Artifact(name=name, type="dataset") 231 | img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None 232 | img_files = tqdm(dataset.img_files) if not img_files else img_files 233 | for img_file in img_files: 234 | if Path(img_file).is_dir(): 235 | artifact.add_dir(img_file, name='data/images') 236 | labels_path = 'labels'.join(dataset.path.rsplit('images', 1)) 237 | artifact.add_dir(labels_path, name='data/labels') 238 | else: 239 | artifact.add_file(img_file, name='data/images/' + Path(img_file).name) 240 | label_file = Path(img2label_paths([img_file])[0]) 241 | artifact.add_file(str(label_file), 242 | name='data/labels/' + label_file.name) if label_file.exists() else None 243 | table = wandb.Table(columns=["id", "train_image", "Classes", "name"]) 244 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()]) 245 | for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)): 246 | height, width = shapes[0] 247 | labels[:, 2:] = (xywh2xyxy(labels[:, 2:].view(-1, 4))) * torch.Tensor([width, height, width, height]) 248 | box_data, img_classes = [], {} 249 | for cls, *xyxy in labels[:, 1:].tolist(): 250 | cls = int(cls) 251 | box_data.append({"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]}, 252 | "class_id": cls, 253 | "box_caption": "%s" % (class_to_id[cls]), 254 | "scores": {"acc": 1}, 255 | "domain": "pixel"}) 256 | img_classes[cls] = class_to_id[cls] 257 | boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space 258 | table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), json.dumps(img_classes), 259 | Path(paths).name) 260 | artifact.add(table, name) 261 | return artifact 262 | 263 | def log_training_progress(self, predn, path, names): 264 | if self.val_table and self.result_table: 265 | class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()]) 266 | box_data = [] 267 | total_conf = 0 268 | for *xyxy, conf, cls in predn.tolist(): 269 | if conf >= 0.25: 270 | box_data.append( 271 | {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]}, 272 | "class_id": int(cls), 273 | "box_caption": "%s %.3f" % (names[cls], conf), 274 | "scores": {"class_score": conf}, 275 | "domain": "pixel"}) 276 | total_conf = total_conf + conf 277 | boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space 278 | id = self.val_table_map[Path(path).name] 279 | self.result_table.add_data(self.current_epoch, 280 | id, 281 | wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set), 282 | total_conf / max(1, len(box_data)) 283 | ) 284 | 285 | def log(self, log_dict): 286 | if self.wandb_run: 287 | for key, value in log_dict.items(): 288 | self.log_dict[key] = value 289 | 290 | def end_epoch(self, best_result=False): 291 | if self.wandb_run: 292 | wandb.log(self.log_dict) 293 | self.log_dict = {} 294 | if self.result_artifact: 295 | train_results = wandb.JoinedTable(self.val_table, self.result_table, "id") 296 | self.result_artifact.add(train_results, 'result') 297 | wandb.log_artifact(self.result_artifact, aliases=['latest', 'epoch ' + str(self.current_epoch), 298 | ('best' if best_result else '')]) 299 | self.result_table = wandb.Table(["epoch", "id", "prediction", "avg_confidence"]) 300 | self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation") 301 | 302 | def finish_run(self): 303 | if self.wandb_run: 304 | if self.log_dict: 305 | wandb.log(self.log_dict) 306 | wandb.run.finish() 307 | -------------------------------------------------------------------------------- /weights/download_weights.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Download latest models from https://github.com/ultralytics/yolov5/releases 3 | # Usage: 4 | # $ bash weights/download_weights.sh 5 | 6 | python3 - < -g 20 | ```` 21 | 22 | ## Bugs & Problems 23 | please issue 24 | 25 | ## Acknowledgements 26 | 27 | some code borrowed from Sergey Karayev 28 | -------------------------------------------------------------------------------- /widerface_evaluate/bbox.cpython-37m-x86_64-linux-gnu.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/widerface_evaluate/bbox.cpython-37m-x86_64-linux-gnu.so -------------------------------------------------------------------------------- /widerface_evaluate/bbox.cpython-38-x86_64-linux-gnu.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/widerface_evaluate/bbox.cpython-38-x86_64-linux-gnu.so -------------------------------------------------------------------------------- /widerface_evaluate/box_overlaps.pyx: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Fast R-CNN 3 | # Copyright (c) 2015 Microsoft 4 | # Licensed under The MIT License [see LICENSE for details] 5 | # Written by Sergey Karayev 6 | # -------------------------------------------------------- 7 | 8 | cimport cython 9 | import numpy as np 10 | cimport numpy as np 11 | 12 | DTYPE = np.float 13 | ctypedef np.float_t DTYPE_t 14 | 15 | def bbox_overlaps( 16 | np.ndarray[DTYPE_t, ndim=2] boxes, 17 | np.ndarray[DTYPE_t, ndim=2] query_boxes): 18 | """ 19 | Parameters 20 | ---------- 21 | boxes: (N, 4) ndarray of float 22 | query_boxes: (K, 4) ndarray of float 23 | Returns 24 | ------- 25 | overlaps: (N, K) ndarray of overlap between boxes and query_boxes 26 | """ 27 | cdef unsigned int N = boxes.shape[0] 28 | cdef unsigned int K = query_boxes.shape[0] 29 | cdef np.ndarray[DTYPE_t, ndim=2] overlaps = np.zeros((N, K), dtype=DTYPE) 30 | cdef DTYPE_t iw, ih, box_area 31 | cdef DTYPE_t ua 32 | cdef unsigned int k, n 33 | for k in range(K): 34 | box_area = ( 35 | (query_boxes[k, 2] - query_boxes[k, 0] + 1) * 36 | (query_boxes[k, 3] - query_boxes[k, 1] + 1) 37 | ) 38 | for n in range(N): 39 | iw = ( 40 | min(boxes[n, 2], query_boxes[k, 2]) - 41 | max(boxes[n, 0], query_boxes[k, 0]) + 1 42 | ) 43 | if iw > 0: 44 | ih = ( 45 | min(boxes[n, 3], query_boxes[k, 3]) - 46 | max(boxes[n, 1], query_boxes[k, 1]) + 1 47 | ) 48 | if ih > 0: 49 | ua = float( 50 | (boxes[n, 2] - boxes[n, 0] + 1) * 51 | (boxes[n, 3] - boxes[n, 1] + 1) + 52 | box_area - iw * ih 53 | ) 54 | overlaps[n, k] = iw * ih / ua 55 | return overlaps -------------------------------------------------------------------------------- /widerface_evaluate/build/temp.linux-x86_64-3.7/box_overlaps.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/widerface_evaluate/build/temp.linux-x86_64-3.7/box_overlaps.o -------------------------------------------------------------------------------- /widerface_evaluate/build/temp.linux-x86_64-3.8/box_overlaps.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/widerface_evaluate/build/temp.linux-x86_64-3.8/box_overlaps.o -------------------------------------------------------------------------------- /widerface_evaluate/evaluation.py: -------------------------------------------------------------------------------- 1 | """ 2 | WiderFace evaluation code 3 | author: wondervictor 4 | mail: tianhengcheng@gmail.com 5 | copyright@wondervictor 6 | """ 7 | 8 | import os 9 | import tqdm 10 | import pickle 11 | import argparse 12 | import numpy as np 13 | from scipy.io import loadmat 14 | from bbox import bbox_overlaps 15 | from IPython import embed 16 | 17 | 18 | def get_gt_boxes(gt_dir): 19 | """ gt dir: (wider_face_val.mat, wider_easy_val.mat, wider_medium_val.mat, wider_hard_val.mat)""" 20 | 21 | gt_mat = loadmat(os.path.join(gt_dir, 'wider_face_val.mat')) 22 | hard_mat = loadmat(os.path.join(gt_dir, 'wider_hard_val.mat')) 23 | medium_mat = loadmat(os.path.join(gt_dir, 'wider_medium_val.mat')) 24 | easy_mat = loadmat(os.path.join(gt_dir, 'wider_easy_val.mat')) 25 | 26 | facebox_list = gt_mat['face_bbx_list'] 27 | event_list = gt_mat['event_list'] 28 | file_list = gt_mat['file_list'] 29 | 30 | hard_gt_list = hard_mat['gt_list'] 31 | medium_gt_list = medium_mat['gt_list'] 32 | easy_gt_list = easy_mat['gt_list'] 33 | 34 | return facebox_list, event_list, file_list, hard_gt_list, medium_gt_list, easy_gt_list 35 | 36 | 37 | def get_gt_boxes_from_txt(gt_path, cache_dir): 38 | 39 | cache_file = os.path.join(cache_dir, 'gt_cache.pkl') 40 | if os.path.exists(cache_file): 41 | f = open(cache_file, 'rb') 42 | boxes = pickle.load(f) 43 | f.close() 44 | return boxes 45 | 46 | f = open(gt_path, 'r') 47 | state = 0 48 | lines = f.readlines() 49 | lines = list(map(lambda x: x.rstrip('\r\n'), lines)) 50 | boxes = {} 51 | print(len(lines)) 52 | f.close() 53 | current_boxes = [] 54 | current_name = None 55 | for line in lines: 56 | if state == 0 and '--' in line: 57 | state = 1 58 | current_name = line 59 | continue 60 | if state == 1: 61 | state = 2 62 | continue 63 | 64 | if state == 2 and '--' in line: 65 | state = 1 66 | boxes[current_name] = np.array(current_boxes).astype('float32') 67 | current_name = line 68 | current_boxes = [] 69 | continue 70 | 71 | if state == 2: 72 | box = [float(x) for x in line.split(' ')[:4]] 73 | current_boxes.append(box) 74 | continue 75 | 76 | f = open(cache_file, 'wb') 77 | pickle.dump(boxes, f) 78 | f.close() 79 | return boxes 80 | 81 | 82 | def read_pred_file(filepath): 83 | 84 | with open(filepath, 'r') as f: 85 | lines = f.readlines() 86 | img_file = lines[0].rstrip('\n\r') 87 | lines = lines[2:] 88 | 89 | # b = lines[0].rstrip('\r\n').split(' ')[:-1] 90 | # c = float(b) 91 | # a = map(lambda x: [[float(a[0]), float(a[1]), float(a[2]), float(a[3]), float(a[4])] for a in x.rstrip('\r\n').split(' ')], lines) 92 | boxes = [] 93 | for line in lines: 94 | line = line.rstrip('\r\n').split(' ') 95 | if line[0] == '': 96 | continue 97 | # a = float(line[4]) 98 | boxes.append([float(line[0]), float(line[1]), float(line[2]), float(line[3]), float(line[4])]) 99 | boxes = np.array(boxes) 100 | # boxes = np.array(list(map(lambda x: [float(a) for a in x.rstrip('\r\n').split(' ')], lines))).astype('float') 101 | return img_file.split('/')[-1], boxes 102 | 103 | 104 | def get_preds(pred_dir): 105 | events = os.listdir(pred_dir) 106 | boxes = dict() 107 | pbar = tqdm.tqdm(events) 108 | 109 | for event in pbar: 110 | pbar.set_description('Reading Predictions ') 111 | event_dir = os.path.join(pred_dir, event) 112 | event_images = os.listdir(event_dir) 113 | current_event = dict() 114 | for imgtxt in event_images: 115 | imgname, _boxes = read_pred_file(os.path.join(event_dir, imgtxt)) 116 | current_event[imgname.rstrip('.jpg')] = _boxes 117 | boxes[event] = current_event 118 | return boxes 119 | 120 | 121 | def norm_score(pred): 122 | """ norm score 123 | pred {key: [[x1,y1,x2,y2,s]]} 124 | """ 125 | 126 | max_score = 0 127 | min_score = 1 128 | 129 | for _, k in pred.items(): 130 | for _, v in k.items(): 131 | if len(v) == 0: 132 | continue 133 | _min = np.min(v[:, -1]) 134 | _max = np.max(v[:, -1]) 135 | max_score = max(_max, max_score) 136 | min_score = min(_min, min_score) 137 | 138 | diff = max_score - min_score 139 | for _, k in pred.items(): 140 | for _, v in k.items(): 141 | if len(v) == 0: 142 | continue 143 | v[:, -1] = (v[:, -1] - min_score)/diff 144 | 145 | 146 | def image_eval(pred, gt, ignore, iou_thresh): 147 | """ single image evaluation 148 | pred: Nx5 149 | gt: Nx4 150 | ignore: 151 | """ 152 | 153 | _pred = pred.copy() 154 | _gt = gt.copy() 155 | pred_recall = np.zeros(_pred.shape[0]) 156 | recall_list = np.zeros(_gt.shape[0]) 157 | proposal_list = np.ones(_pred.shape[0]) 158 | 159 | _pred[:, 2] = _pred[:, 2] + _pred[:, 0] 160 | _pred[:, 3] = _pred[:, 3] + _pred[:, 1] 161 | _gt[:, 2] = _gt[:, 2] + _gt[:, 0] 162 | _gt[:, 3] = _gt[:, 3] + _gt[:, 1] 163 | 164 | overlaps = bbox_overlaps(_pred[:, :4], _gt) 165 | 166 | for h in range(_pred.shape[0]): 167 | 168 | gt_overlap = overlaps[h] 169 | max_overlap, max_idx = gt_overlap.max(), gt_overlap.argmax() 170 | if max_overlap >= iou_thresh: 171 | if ignore[max_idx] == 0: 172 | recall_list[max_idx] = -1 173 | proposal_list[h] = -1 174 | elif recall_list[max_idx] == 0: 175 | recall_list[max_idx] = 1 176 | 177 | r_keep_index = np.where(recall_list == 1)[0] 178 | pred_recall[h] = len(r_keep_index) 179 | return pred_recall, proposal_list 180 | 181 | 182 | def img_pr_info(thresh_num, pred_info, proposal_list, pred_recall): 183 | pr_info = np.zeros((thresh_num, 2)).astype('float') 184 | for t in range(thresh_num): 185 | 186 | thresh = 1 - (t+1)/thresh_num 187 | r_index = np.where(pred_info[:, 4] >= thresh)[0] 188 | if len(r_index) == 0: 189 | pr_info[t, 0] = 0 190 | pr_info[t, 1] = 0 191 | else: 192 | r_index = r_index[-1] 193 | p_index = np.where(proposal_list[:r_index+1] == 1)[0] 194 | pr_info[t, 0] = len(p_index) 195 | pr_info[t, 1] = pred_recall[r_index] 196 | return pr_info 197 | 198 | 199 | def dataset_pr_info(thresh_num, pr_curve, count_face): 200 | _pr_curve = np.zeros((thresh_num, 2)) 201 | for i in range(thresh_num): 202 | _pr_curve[i, 0] = pr_curve[i, 1] / pr_curve[i, 0] 203 | _pr_curve[i, 1] = pr_curve[i, 1] / count_face 204 | return _pr_curve 205 | 206 | 207 | def voc_ap(rec, prec): 208 | 209 | # correct AP calculation 210 | # first append sentinel values at the end 211 | mrec = np.concatenate(([0.], rec, [1.])) 212 | mpre = np.concatenate(([0.], prec, [0.])) 213 | 214 | # compute the precision envelope 215 | for i in range(mpre.size - 1, 0, -1): 216 | mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) 217 | 218 | # to calculate area under PR curve, look for points 219 | # where X axis (recall) changes value 220 | i = np.where(mrec[1:] != mrec[:-1])[0] 221 | 222 | # and sum (\Delta recall) * prec 223 | ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) 224 | return ap 225 | 226 | 227 | def evaluation(pred, gt_path, iou_thresh=0.5): 228 | pred = get_preds(pred) 229 | norm_score(pred) 230 | facebox_list, event_list, file_list, hard_gt_list, medium_gt_list, easy_gt_list = get_gt_boxes(gt_path) 231 | event_num = len(event_list) 232 | thresh_num = 1000 233 | settings = ['easy', 'medium', 'hard'] 234 | setting_gts = [easy_gt_list, medium_gt_list, hard_gt_list] 235 | aps = [] 236 | for setting_id in range(3): 237 | # different setting 238 | gt_list = setting_gts[setting_id] 239 | count_face = 0 240 | pr_curve = np.zeros((thresh_num, 2)).astype('float') 241 | # [hard, medium, easy] 242 | pbar = tqdm.tqdm(range(event_num)) 243 | for i in pbar: 244 | pbar.set_description('Processing {}'.format(settings[setting_id])) 245 | event_name = str(event_list[i][0][0]) 246 | img_list = file_list[i][0] 247 | pred_list = pred[event_name] 248 | sub_gt_list = gt_list[i][0] 249 | # img_pr_info_list = np.zeros((len(img_list), thresh_num, 2)) 250 | gt_bbx_list = facebox_list[i][0] 251 | 252 | for j in range(len(img_list)): 253 | pred_info = pred_list[str(img_list[j][0][0])] 254 | 255 | gt_boxes = gt_bbx_list[j][0].astype('float') 256 | keep_index = sub_gt_list[j][0] 257 | count_face += len(keep_index) 258 | 259 | if len(gt_boxes) == 0 or len(pred_info) == 0: 260 | continue 261 | ignore = np.zeros(gt_boxes.shape[0]) 262 | if len(keep_index) != 0: 263 | ignore[keep_index-1] = 1 264 | pred_recall, proposal_list = image_eval(pred_info, gt_boxes, ignore, iou_thresh) 265 | 266 | _img_pr_info = img_pr_info(thresh_num, pred_info, proposal_list, pred_recall) 267 | 268 | pr_curve += _img_pr_info 269 | pr_curve = dataset_pr_info(thresh_num, pr_curve, count_face) 270 | 271 | propose = pr_curve[:, 0] 272 | recall = pr_curve[:, 1] 273 | 274 | ap = voc_ap(recall, propose) 275 | aps.append(ap) 276 | 277 | print("==================== Results ====================") 278 | print("Easy Val AP: {}".format(aps[0])) 279 | print("Medium Val AP: {}".format(aps[1])) 280 | print("Hard Val AP: {}".format(aps[2])) 281 | print("=================================================") 282 | 283 | 284 | if __name__ == '__main__': 285 | 286 | parser = argparse.ArgumentParser() 287 | parser.add_argument('-p', '--pred', default="./widerface_txt/") 288 | parser.add_argument('-g', '--gt', default='./ground_truth/') 289 | 290 | args = parser.parse_args() 291 | evaluation(args.pred, args.gt) 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | -------------------------------------------------------------------------------- /widerface_evaluate/ground_truth/wider_easy_val.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/widerface_evaluate/ground_truth/wider_easy_val.mat -------------------------------------------------------------------------------- /widerface_evaluate/ground_truth/wider_face_val.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/widerface_evaluate/ground_truth/wider_face_val.mat -------------------------------------------------------------------------------- /widerface_evaluate/ground_truth/wider_hard_val.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/widerface_evaluate/ground_truth/wider_hard_val.mat -------------------------------------------------------------------------------- /widerface_evaluate/ground_truth/wider_medium_val.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deepcam-cn/yolov5-face/152c688d551aefb973b7b589fb0691c93dab3564/widerface_evaluate/ground_truth/wider_medium_val.mat -------------------------------------------------------------------------------- /widerface_evaluate/setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | WiderFace evaluation code 3 | author: wondervictor 4 | mail: tianhengcheng@gmail.com 5 | copyright@wondervictor 6 | """ 7 | 8 | from distutils.core import setup, Extension 9 | from Cython.Build import cythonize 10 | import numpy 11 | 12 | package = Extension('bbox', ['box_overlaps.pyx'], include_dirs=[numpy.get_include()]) 13 | setup(ext_modules=cythonize([package])) 14 | --------------------------------------------------------------------------------