├── .gitignore ├── LICENSE ├── README.md ├── VOCdevkit └── VOC2007 │ ├── Annotations │ └── README.md │ ├── ImageSets │ └── Main │ │ └── README.md │ └── JPEGImages │ └── README.md ├── get_map.py ├── img └── street.jpg ├── kmeans_for_anchors.py ├── logs └── README.md ├── model_data ├── coco_classes.txt ├── simhei.ttf ├── voc_classes.txt └── yolo_anchors.txt ├── nets ├── CSPdarknet53_tiny.py ├── __init__.py ├── attention.py ├── yolo.py └── yolo_training.py ├── predict.py ├── requirements.txt ├── summary.py ├── train.py ├── utils ├── __init__.py ├── callbacks.py ├── dataloader.py ├── utils.py ├── utils_bbox.py ├── utils_fit.py └── utils_map.py ├── utils_coco ├── coco_annotation.py └── get_map_coco.py ├── voc_annotation.py ├── yolo.py └── 常见问题汇总.md /.gitignore: -------------------------------------------------------------------------------- 1 | # ignore map, miou, datasets 2 | map_out/ 3 | miou_out/ 4 | VOCdevkit/ 5 | datasets/ 6 | Medical_Datasets/ 7 | lfw/ 8 | logs/ 9 | model_data/ 10 | .temp_map_out/ 11 | 12 | # Byte-compiled / optimized / DLL files 13 | __pycache__/ 14 | *.py[cod] 15 | *$py.class 16 | 17 | # C extensions 18 | *.so 19 | 20 | # Distribution / packaging 21 | .Python 22 | build/ 23 | develop-eggs/ 24 | dist/ 25 | downloads/ 26 | eggs/ 27 | .eggs/ 28 | lib/ 29 | lib64/ 30 | parts/ 31 | sdist/ 32 | var/ 33 | wheels/ 34 | pip-wheel-metadata/ 35 | share/python-wheels/ 36 | *.egg-info/ 37 | .installed.cfg 38 | *.egg 39 | MANIFEST 40 | 41 | # PyInstaller 42 | # Usually these files are written by a python script from a template 43 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 44 | *.manifest 45 | *.spec 46 | 47 | # Installer logs 48 | pip-log.txt 49 | pip-delete-this-directory.txt 50 | 51 | # Unit test / coverage reports 52 | htmlcov/ 53 | .tox/ 54 | .nox/ 55 | .coverage 56 | .coverage.* 57 | .cache 58 | nosetests.xml 59 | coverage.xml 60 | *.cover 61 | *.py,cover 62 | .hypothesis/ 63 | .pytest_cache/ 64 | 65 | # Translations 66 | *.mo 67 | *.pot 68 | 69 | # Django stuff: 70 | *.log 71 | local_settings.py 72 | db.sqlite3 73 | db.sqlite3-journal 74 | 75 | # Flask stuff: 76 | instance/ 77 | .webassets-cache 78 | 79 | # Scrapy stuff: 80 | .scrapy 81 | 82 | # Sphinx documentation 83 | docs/_build/ 84 | 85 | # PyBuilder 86 | target/ 87 | 88 | # Jupyter Notebook 89 | .ipynb_checkpoints 90 | 91 | # IPython 92 | profile_default/ 93 | ipython_config.py 94 | 95 | # pyenv 96 | .python-version 97 | 98 | # pipenv 99 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 100 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 101 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 102 | # install all needed dependencies. 103 | #Pipfile.lock 104 | 105 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 106 | __pypackages__/ 107 | 108 | # Celery stuff 109 | celerybeat-schedule 110 | celerybeat.pid 111 | 112 | # SageMath parsed files 113 | *.sage.py 114 | 115 | # Environments 116 | .env 117 | .venv 118 | env/ 119 | venv/ 120 | ENV/ 121 | env.bak/ 122 | venv.bak/ 123 | 124 | # Spyder project settings 125 | .spyderproject 126 | .spyproject 127 | 128 | # Rope project settings 129 | .ropeproject 130 | 131 | # mkdocs documentation 132 | /site 133 | 134 | # mypy 135 | .mypy_cache/ 136 | .dmypy.json 137 | dmypy.json 138 | 139 | # Pyre type checker 140 | .pyre/ 141 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 JiaQi Xu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## YOLOV4-Tiny:You Only Look Once-Tiny目标检测模型在TF2当中的实现 2 | --- 3 | 4 | ## 目录 5 | 1. [仓库更新 Top News](#仓库更新) 6 | 2. [相关仓库 Related code](#相关仓库) 7 | 3. [性能情况 Performance](#性能情况) 8 | 4. [所需环境 Environment](#所需环境) 9 | 5. [文件下载 Download](#文件下载) 10 | 6. [训练步骤 How2train](#训练步骤) 11 | 7. [预测步骤 How2predict](#预测步骤) 12 | 8. [评估步骤 How2eval](#评估步骤) 13 | 9. [参考资料 Reference](#Reference) 14 | 15 | ## Top News 16 | **`2022-04`**:**支持多GPU训练,新增各个种类目标数量计算,新增heatmap。** 17 | 18 | **`2022-03`**:**进行了大幅度的更新,修改了loss组成,使得分类、目标、回归loss的比例合适、支持step、cos学习率下降法、支持adam、sgd优化器选择、支持学习率根据batch_size自适应调整、新增图片裁剪。** 19 | BiliBili视频中的原仓库地址为:https://github.com/bubbliiiing/yolov4-tiny-tf2/tree/bilibili 20 | 21 | **`2021-10`**:**进行了大幅度的更新,增加了大量注释、增加了大量可调整参数、对代码的组成模块进行修改、增加fps、视频预测、批量预测等功能。** 22 | 23 | ## 相关仓库 24 | | 模型 | 路径 | 25 | | :----- | :----- | 26 | YoloV3 | https://github.com/bubbliiiing/yolo3-tf2 27 | Efficientnet-Yolo3 | https://github.com/bubbliiiing/efficientnet-yolo3-tf2 28 | YoloV4 | https://github.com/bubbliiiing/yolov4-tf2 29 | YoloV4-tiny | https://github.com/bubbliiiing/yolov4-tiny-tf2 30 | Mobilenet-Yolov4 | https://github.com/bubbliiiing/mobilenet-yolov4-tf2 31 | YoloV5-V5.0 | https://github.com/bubbliiiing/yolov5-tf2 32 | YoloV5-V6.1 | https://github.com/bubbliiiing/yolov5-v6.1-tf2 33 | YoloX | https://github.com/bubbliiiing/yolox-tf2 34 | Yolov7 | https://github.com/bubbliiiing/yolov7-tf2 35 | Yolov7-tiny | https://github.com/bubbliiiing/yolov7-tiny-tf2 36 | 37 | ## 性能情况 38 | | 训练数据集 | 权值文件名称 | 测试数据集 | 输入图片大小 | mAP 0.5:0.95 | mAP 0.5 | 39 | | :-----: | :-----: | :------: | :------: | :------: | :-----: | 40 | | VOC07+12+COCO | [yolov4_tiny_weights_voc.h5](https://github.com/bubbliiiing/yolov4-tiny-tf2/releases/download/v1.0/yolov4_tiny_weights_voc.h5) | VOC-Test07 | 416x416 | - | 77.5 41 | | VOC07+12+COCO | [yolov4_tiny_weights_voc_SE.h5](https://github.com/bubbliiiing/yolov4-tiny-tf2/releases/download/v1.0/yolov4_tiny_weights_voc_SE.h5) | VOC-Test07 | 416x416 | - | 78.6 42 | | VOC07+12+COCO | [yolov4_tiny_weights_voc_CBAM.h5](https://github.com/bubbliiiing/yolov4-tiny-tf2/releases/download/v1.0/yolov4_tiny_weights_voc_CBAM.h5) | VOC-Test07 | 416x416 | - | 78.9 43 | | VOC07+12+COCO | [yolov4_tiny_weights_voc_ECA.h5](https://github.com/bubbliiiing/yolov4-tiny-tf2/releases/download/v1.0/yolov4_tiny_weights_voc_ECA.h5) | VOC-Test07 | 416x416 | - | 78.2 44 | | COCO-Train2017 | [yolov4_tiny_weights_coco.h5](https://github.com/bubbliiiing/yolov4-tiny-tf2/releases/download/v1.0/yolov4_tiny_weights_coco.h5) | COCO-Val2017 | 416x416 | 21.8 | 41.3 45 | 46 | ## 所需环境 47 | tensorflow-gpu==2.2.0 48 | 49 | ## 文件下载 50 | 训练所需的各类权值均可在百度网盘中下载。 51 | 链接: https://pan.baidu.com/s/1v6jWj3bPK-DVp4U19zyWHg 52 | 提取码: yixn 53 | 54 | VOC数据集下载地址如下,里面已经包括了训练集、测试集、验证集(与测试集一样),无需再次划分: 55 | 链接: https://pan.baidu.com/s/19Mw2u_df_nBzsC2lg20fQA 56 | 提取码: j5ge 57 | 58 | ## 训练步骤 59 | ### a、训练VOC07+12数据集 60 | 1. 数据集的准备 61 | **本文使用VOC格式进行训练,训练前需要下载好VOC07+12的数据集,解压后放在根目录** 62 | 63 | 2. 数据集的处理 64 | 修改voc_annotation.py里面的annotation_mode=2,运行voc_annotation.py生成根目录下的2007_train.txt和2007_val.txt。 65 | 66 | 3. 开始网络训练 67 | train.py的默认参数用于训练VOC数据集,直接运行train.py即可开始训练。 68 | 69 | 4. 训练结果预测 70 | 训练结果预测需要用到两个文件,分别是yolo.py和predict.py。我们首先需要去yolo.py里面修改model_path以及classes_path,这两个参数必须要修改。 71 | **model_path指向训练好的权值文件,在logs文件夹里。 72 | classes_path指向检测类别所对应的txt。** 73 | 完成修改后就可以运行predict.py进行检测了。运行后输入图片路径即可检测。 74 | 75 | ### b、训练自己的数据集 76 | 1. 数据集的准备 77 | **本文使用VOC格式进行训练,训练前需要自己制作好数据集,** 78 | 训练前将标签文件放在VOCdevkit文件夹下的VOC2007文件夹下的Annotation中。 79 | 训练前将图片文件放在VOCdevkit文件夹下的VOC2007文件夹下的JPEGImages中。 80 | 81 | 2. 数据集的处理 82 | 在完成数据集的摆放之后,我们需要利用voc_annotation.py获得训练用的2007_train.txt和2007_val.txt。 83 | 修改voc_annotation.py里面的参数。第一次训练可以仅修改classes_path,classes_path用于指向检测类别所对应的txt。 84 | 训练自己的数据集时,可以自己建立一个cls_classes.txt,里面写自己所需要区分的类别。 85 | model_data/cls_classes.txt文件内容为: 86 | ```python 87 | cat 88 | dog 89 | ... 90 | ``` 91 | 修改voc_annotation.py中的classes_path,使其对应cls_classes.txt,并运行voc_annotation.py。 92 | 93 | 3. 开始网络训练 94 | **训练的参数较多,均在train.py中,大家可以在下载库后仔细看注释,其中最重要的部分依然是train.py里的classes_path。** 95 | **classes_path用于指向检测类别所对应的txt,这个txt和voc_annotation.py里面的txt一样!训练自己的数据集必须要修改!** 96 | 修改完classes_path后就可以运行train.py开始训练了,在训练多个epoch后,权值会生成在logs文件夹中。 97 | 98 | 4. 训练结果预测 99 | 训练结果预测需要用到两个文件,分别是yolo.py和predict.py。在yolo.py里面修改model_path以及classes_path。 100 | **model_path指向训练好的权值文件,在logs文件夹里。 101 | classes_path指向检测类别所对应的txt。** 102 | 完成修改后就可以运行predict.py进行检测了。运行后输入图片路径即可检测。 103 | 104 | ## 预测步骤 105 | ### a、使用预训练权重 106 | 1. 下载完库后解压,在百度网盘下载yolo_weights.pth,放入model_data,运行predict.py,输入 107 | ```python 108 | img/street.jpg 109 | ``` 110 | 2. 在predict.py里面进行设置可以进行fps测试和video视频检测。 111 | ### b、使用自己训练的权重 112 | 1. 按照训练步骤训练。 113 | 2. 在yolo.py文件里面,在如下部分修改model_path和classes_path使其对应训练好的文件;**model_path对应logs文件夹下面的权值文件,classes_path是model_path对应分的类**。 114 | ```python 115 | _defaults = { 116 | #--------------------------------------------------------------------------# 117 | # 使用自己训练好的模型进行预测一定要修改model_path和classes_path! 118 | # model_path指向logs文件夹下的权值文件,classes_path指向model_data下的txt 119 | # 如果出现shape不匹配,同时要注意训练时的model_path和classes_path参数的修改 120 | #--------------------------------------------------------------------------# 121 | "model_path" : 'model_data/yolov4_tiny_weights_coco.h5', 122 | "classes_path" : 'model_data/coco_classes.txt', 123 | #---------------------------------------------------------------------# 124 | # anchors_path代表先验框对应的txt文件,一般不修改。 125 | # anchors_mask用于帮助代码找到对应的先验框,一般不修改。 126 | #---------------------------------------------------------------------# 127 | "anchors_path" : 'model_data/yolo_anchors.txt', 128 | "anchors_mask" : [[3, 4, 5], [1, 2, 3]], 129 | #-------------------------------# 130 | # 所使用的注意力机制的类型 131 | # phi = 0为不使用注意力机制 132 | # phi = 1为SE 133 | # phi = 2为CBAM 134 | # phi = 3为ECA 135 | #-------------------------------# 136 | "phi" : 0, 137 | #---------------------------------------------------------------------# 138 | # 输入图片的大小,必须为32的倍数。 139 | #---------------------------------------------------------------------# 140 | "input_shape" : [416, 416], 141 | #---------------------------------------------------------------------# 142 | # 只有得分大于置信度的预测框会被保留下来 143 | #---------------------------------------------------------------------# 144 | "confidence" : 0.5, 145 | #---------------------------------------------------------------------# 146 | # 非极大抑制所用到的nms_iou大小 147 | #---------------------------------------------------------------------# 148 | "nms_iou" : 0.3, 149 | "max_boxes" : 100, 150 | #---------------------------------------------------------------------# 151 | # 该变量用于控制是否使用letterbox_image对输入图像进行不失真的resize, 152 | # 在多次测试后,发现关闭letterbox_image直接resize的效果更好 153 | #---------------------------------------------------------------------# 154 | "letterbox_image" : True, 155 | } 156 | ``` 157 | 3. 运行predict.py,输入 158 | ```python 159 | img/street.jpg 160 | ``` 161 | 4. 在predict.py里面进行设置可以进行fps测试和video视频检测。 162 | 163 | ## 评估步骤 164 | ### a、评估VOC07+12的测试集 165 | 1. 本文使用VOC格式进行评估。VOC07+12已经划分好了测试集,无需利用voc_annotation.py生成ImageSets文件夹下的txt。 166 | 2. 在yolo.py里面修改model_path以及classes_path。**model_path指向训练好的权值文件,在logs文件夹里。classes_path指向检测类别所对应的txt。** 167 | 3. 运行get_map.py即可获得评估结果,评估结果会保存在map_out文件夹中。 168 | 169 | ### b、评估自己的数据集 170 | 1. 本文使用VOC格式进行评估。 171 | 2. 如果在训练前已经运行过voc_annotation.py文件,代码会自动将数据集划分成训练集、验证集和测试集。如果想要修改测试集的比例,可以修改voc_annotation.py文件下的trainval_percent。trainval_percent用于指定(训练集+验证集)与测试集的比例,默认情况下 (训练集+验证集):测试集 = 9:1。train_percent用于指定(训练集+验证集)中训练集与验证集的比例,默认情况下 训练集:验证集 = 9:1。 172 | 3. 利用voc_annotation.py划分测试集后,前往get_map.py文件修改classes_path,classes_path用于指向检测类别所对应的txt,这个txt和训练时的txt一样。评估自己的数据集必须要修改。 173 | 4. 在yolo.py里面修改model_path以及classes_path。**model_path指向训练好的权值文件,在logs文件夹里。classes_path指向检测类别所对应的txt。** 174 | 5. 运行get_map.py即可获得评估结果,评估结果会保存在map_out文件夹中。 175 | 176 | ## Reference 177 | https://github.com/qqwweee/keras-yolo3/ 178 | https://github.com/Cartucho/mAP 179 | https://github.com/Ma-Dan/keras-yolo4 180 | 181 | -------------------------------------------------------------------------------- /VOCdevkit/VOC2007/Annotations/README.md: -------------------------------------------------------------------------------- 1 | 存放标签文件 -------------------------------------------------------------------------------- /VOCdevkit/VOC2007/ImageSets/Main/README.md: -------------------------------------------------------------------------------- 1 | 存放训练索引文件 -------------------------------------------------------------------------------- /VOCdevkit/VOC2007/JPEGImages/README.md: -------------------------------------------------------------------------------- 1 | 存放图片文件 -------------------------------------------------------------------------------- /get_map.py: -------------------------------------------------------------------------------- 1 | import os 2 | import xml.etree.ElementTree as ET 3 | 4 | import tensorflow as tf 5 | from PIL import Image 6 | from tqdm import tqdm 7 | 8 | from utils.utils import get_classes 9 | from utils.utils_map import get_coco_map, get_map 10 | from yolo import YOLO 11 | 12 | gpus = tf.config.experimental.list_physical_devices(device_type='GPU') 13 | for gpu in gpus: 14 | tf.config.experimental.set_memory_growth(gpu, True) 15 | 16 | if __name__ == "__main__": 17 | ''' 18 | Recall和Precision不像AP是一个面积的概念,因此在门限值(Confidence)不同时,网络的Recall和Precision值是不同的。 19 | 默认情况下,本代码计算的Recall和Precision代表的是当门限值(Confidence)为0.5时,所对应的Recall和Precision值。 20 | 21 | 受到mAP计算原理的限制,网络在计算mAP时需要获得近乎所有的预测框,这样才可以计算不同门限条件下的Recall和Precision值 22 | 因此,本代码获得的map_out/detection-results/里面的txt的框的数量一般会比直接predict多一些,目的是列出所有可能的预测框, 23 | ''' 24 | #------------------------------------------------------------------------------------------------------------------# 25 | # map_mode用于指定该文件运行时计算的内容 26 | # map_mode为0代表整个map计算流程,包括获得预测结果、获得真实框、计算VOC_map。 27 | # map_mode为1代表仅仅获得预测结果。 28 | # map_mode为2代表仅仅获得真实框。 29 | # map_mode为3代表仅仅计算VOC_map。 30 | # map_mode为4代表利用COCO工具箱计算当前数据集的0.50:0.95map。需要获得预测结果、获得真实框后并安装pycocotools才行 31 | #-------------------------------------------------------------------------------------------------------------------# 32 | map_mode = 0 33 | #--------------------------------------------------------------------------------------# 34 | # 此处的classes_path用于指定需要测量VOC_map的类别 35 | # 一般情况下与训练和预测所用的classes_path一致即可 36 | #--------------------------------------------------------------------------------------# 37 | classes_path = 'model_data/voc_classes.txt' 38 | #--------------------------------------------------------------------------------------# 39 | # MINOVERLAP用于指定想要获得的mAP0.x,mAP0.x的意义是什么请同学们百度一下。 40 | # 比如计算mAP0.75,可以设定MINOVERLAP = 0.75。 41 | # 42 | # 当某一预测框与真实框重合度大于MINOVERLAP时,该预测框被认为是正样本,否则为负样本。 43 | # 因此MINOVERLAP的值越大,预测框要预测的越准确才能被认为是正样本,此时算出来的mAP值越低, 44 | #--------------------------------------------------------------------------------------# 45 | MINOVERLAP = 0.5 46 | #--------------------------------------------------------------------------------------# 47 | # 受到mAP计算原理的限制,网络在计算mAP时需要获得近乎所有的预测框,这样才可以计算mAP 48 | # 因此,confidence的值应当设置的尽量小进而获得全部可能的预测框。 49 | # 50 | # 该值一般不调整。因为计算mAP需要获得近乎所有的预测框,此处的confidence不能随便更改。 51 | # 想要获得不同门限值下的Recall和Precision值,请修改下方的score_threhold。 52 | #--------------------------------------------------------------------------------------# 53 | confidence = 0.001 54 | #--------------------------------------------------------------------------------------# 55 | # 预测时使用到的非极大抑制值的大小,越大表示非极大抑制越不严格。 56 | # 57 | # 该值一般不调整。 58 | #--------------------------------------------------------------------------------------# 59 | nms_iou = 0.5 60 | #---------------------------------------------------------------------------------------------------------------# 61 | # Recall和Precision不像AP是一个面积的概念,因此在门限值不同时,网络的Recall和Precision值是不同的。 62 | # 63 | # 默认情况下,本代码计算的Recall和Precision代表的是当门限值为0.5(此处定义为score_threhold)时所对应的Recall和Precision值。 64 | # 因为计算mAP需要获得近乎所有的预测框,上面定义的confidence不能随便更改。 65 | # 这里专门定义一个score_threhold用于代表门限值,进而在计算mAP时找到门限值对应的Recall和Precision值。 66 | #---------------------------------------------------------------------------------------------------------------# 67 | score_threhold = 0.5 68 | #-------------------------------------------------------# 69 | # map_vis用于指定是否开启VOC_map计算的可视化 70 | #-------------------------------------------------------# 71 | map_vis = False 72 | #-------------------------------------------------------# 73 | # 指向VOC数据集所在的文件夹 74 | # 默认指向根目录下的VOC数据集 75 | #-------------------------------------------------------# 76 | VOCdevkit_path = 'VOCdevkit' 77 | #-------------------------------------------------------# 78 | # 结果输出的文件夹,默认为map_out 79 | #-------------------------------------------------------# 80 | map_out_path = 'map_out' 81 | 82 | image_ids = open(os.path.join(VOCdevkit_path, "VOC2007/ImageSets/Main/test.txt")).read().strip().split() 83 | 84 | if not os.path.exists(map_out_path): 85 | os.makedirs(map_out_path) 86 | if not os.path.exists(os.path.join(map_out_path, 'ground-truth')): 87 | os.makedirs(os.path.join(map_out_path, 'ground-truth')) 88 | if not os.path.exists(os.path.join(map_out_path, 'detection-results')): 89 | os.makedirs(os.path.join(map_out_path, 'detection-results')) 90 | if not os.path.exists(os.path.join(map_out_path, 'images-optional')): 91 | os.makedirs(os.path.join(map_out_path, 'images-optional')) 92 | 93 | class_names, _ = get_classes(classes_path) 94 | 95 | if map_mode == 0 or map_mode == 1: 96 | print("Load model.") 97 | yolo = YOLO(confidence = confidence, nms_iou = nms_iou) 98 | print("Load model done.") 99 | 100 | print("Get predict result.") 101 | for image_id in tqdm(image_ids): 102 | image_path = os.path.join(VOCdevkit_path, "VOC2007/JPEGImages/"+image_id+".jpg") 103 | image = Image.open(image_path) 104 | if map_vis: 105 | image.save(os.path.join(map_out_path, "images-optional/" + image_id + ".jpg")) 106 | yolo.get_map_txt(image_id, image, class_names, map_out_path) 107 | print("Get predict result done.") 108 | 109 | if map_mode == 0 or map_mode == 2: 110 | print("Get ground truth result.") 111 | for image_id in tqdm(image_ids): 112 | with open(os.path.join(map_out_path, "ground-truth/"+image_id+".txt"), "w") as new_f: 113 | root = ET.parse(os.path.join(VOCdevkit_path, "VOC2007/Annotations/"+image_id+".xml")).getroot() 114 | for obj in root.findall('object'): 115 | difficult_flag = False 116 | if obj.find('difficult')!=None: 117 | difficult = obj.find('difficult').text 118 | if int(difficult)==1: 119 | difficult_flag = True 120 | obj_name = obj.find('name').text 121 | if obj_name not in class_names: 122 | continue 123 | bndbox = obj.find('bndbox') 124 | left = bndbox.find('xmin').text 125 | top = bndbox.find('ymin').text 126 | right = bndbox.find('xmax').text 127 | bottom = bndbox.find('ymax').text 128 | 129 | if difficult_flag: 130 | new_f.write("%s %s %s %s %s difficult\n" % (obj_name, left, top, right, bottom)) 131 | else: 132 | new_f.write("%s %s %s %s %s\n" % (obj_name, left, top, right, bottom)) 133 | print("Get ground truth result done.") 134 | 135 | if map_mode == 0 or map_mode == 3: 136 | print("Get map.") 137 | get_map(MINOVERLAP, True, score_threhold = score_threhold, path = map_out_path) 138 | print("Get map done.") 139 | 140 | if map_mode == 4: 141 | print("Get map.") 142 | get_coco_map(class_names = class_names, path = map_out_path) 143 | print("Get map done.") 144 | -------------------------------------------------------------------------------- /img/street.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bubbliiiing/yolov4-tiny-tf2/b3e32e22687821e1028200f071b2fa4bc8a93029/img/street.jpg -------------------------------------------------------------------------------- /kmeans_for_anchors.py: -------------------------------------------------------------------------------- 1 | #-------------------------------------------------------------------------------------------------------# 2 | # kmeans虽然会对数据集中的框进行聚类,但是很多数据集由于框的大小相近,聚类出来的9个框相差不大, 3 | # 这样的框反而不利于模型的训练。因为不同的特征层适合不同大小的先验框,shape越小的特征层适合越大的先验框 4 | # 原始网络的先验框已经按大中小比例分配好了,不进行聚类也会有非常好的效果。 5 | #-------------------------------------------------------------------------------------------------------# 6 | import glob 7 | import xml.etree.ElementTree as ET 8 | 9 | import matplotlib.pyplot as plt 10 | import numpy as np 11 | from tqdm import tqdm 12 | 13 | 14 | def cas_iou(box, cluster): 15 | x = np.minimum(cluster[:, 0], box[0]) 16 | y = np.minimum(cluster[:, 1], box[1]) 17 | 18 | intersection = x * y 19 | area1 = box[0] * box[1] 20 | 21 | area2 = cluster[:,0] * cluster[:,1] 22 | iou = intersection / (area1 + area2 - intersection) 23 | 24 | return iou 25 | 26 | def avg_iou(box, cluster): 27 | return np.mean([np.max(cas_iou(box[i], cluster)) for i in range(box.shape[0])]) 28 | 29 | def kmeans(box, k): 30 | #-------------------------------------------------------------# 31 | # 取出一共有多少框 32 | #-------------------------------------------------------------# 33 | row = box.shape[0] 34 | 35 | #-------------------------------------------------------------# 36 | # 每个框各个点的位置 37 | #-------------------------------------------------------------# 38 | distance = np.empty((row, k)) 39 | 40 | #-------------------------------------------------------------# 41 | # 最后的聚类位置 42 | #-------------------------------------------------------------# 43 | last_clu = np.zeros((row, )) 44 | 45 | np.random.seed() 46 | 47 | #-------------------------------------------------------------# 48 | # 随机选5个当聚类中心 49 | #-------------------------------------------------------------# 50 | cluster = box[np.random.choice(row, k, replace = False)] 51 | 52 | iter = 0 53 | while True: 54 | #-------------------------------------------------------------# 55 | # 计算当前框和先验框的宽高比例 56 | #-------------------------------------------------------------# 57 | for i in range(row): 58 | distance[i] = 1 - cas_iou(box[i], cluster) 59 | 60 | #-------------------------------------------------------------# 61 | # 取出最小点 62 | #-------------------------------------------------------------# 63 | near = np.argmin(distance, axis=1) 64 | 65 | if (last_clu == near).all(): 66 | break 67 | 68 | #-------------------------------------------------------------# 69 | # 求每一个类的中位点 70 | #-------------------------------------------------------------# 71 | for j in range(k): 72 | cluster[j] = np.median( 73 | box[near == j],axis=0) 74 | 75 | last_clu = near 76 | if iter % 5 == 0: 77 | print('iter: {:d}. avg_iou:{:.2f}'.format(iter, avg_iou(box, cluster))) 78 | iter += 1 79 | 80 | return cluster, near 81 | 82 | def load_data(path): 83 | data = [] 84 | #-------------------------------------------------------------# 85 | # 对于每一个xml都寻找box 86 | #-------------------------------------------------------------# 87 | for xml_file in tqdm(glob.glob('{}/*xml'.format(path))): 88 | tree = ET.parse(xml_file) 89 | height = int(tree.findtext('./size/height')) 90 | width = int(tree.findtext('./size/width')) 91 | if height<=0 or width<=0: 92 | continue 93 | 94 | #-------------------------------------------------------------# 95 | # 对于每一个目标都获得它的宽高 96 | #-------------------------------------------------------------# 97 | for obj in tree.iter('object'): 98 | xmin = int(float(obj.findtext('bndbox/xmin'))) / width 99 | ymin = int(float(obj.findtext('bndbox/ymin'))) / height 100 | xmax = int(float(obj.findtext('bndbox/xmax'))) / width 101 | ymax = int(float(obj.findtext('bndbox/ymax'))) / height 102 | 103 | xmin = np.float64(xmin) 104 | ymin = np.float64(ymin) 105 | xmax = np.float64(xmax) 106 | ymax = np.float64(ymax) 107 | # 得到宽高 108 | data.append([xmax - xmin, ymax - ymin]) 109 | return np.array(data) 110 | 111 | if __name__ == '__main__': 112 | np.random.seed(0) 113 | #-------------------------------------------------------------# 114 | # 运行该程序会计算'./VOCdevkit/VOC2007/Annotations'的xml 115 | # 会生成yolo_anchors.txt 116 | #-------------------------------------------------------------# 117 | input_shape = [416, 416] 118 | anchors_num = 6 119 | #-------------------------------------------------------------# 120 | # 载入数据集,可以使用VOC的xml 121 | #-------------------------------------------------------------# 122 | path = 'VOCdevkit/VOC2007/Annotations' 123 | 124 | #-------------------------------------------------------------# 125 | # 载入所有的xml 126 | # 存储格式为转化为比例后的width,height 127 | #-------------------------------------------------------------# 128 | print('Load xmls.') 129 | data = load_data(path) 130 | print('Load xmls done.') 131 | 132 | #-------------------------------------------------------------# 133 | # 使用k聚类算法 134 | #-------------------------------------------------------------# 135 | print('K-means boxes.') 136 | cluster, near = kmeans(data, anchors_num) 137 | print('K-means boxes done.') 138 | data = data * np.array([input_shape[1], input_shape[0]]) 139 | cluster = cluster * np.array([input_shape[1], input_shape[0]]) 140 | 141 | #-------------------------------------------------------------# 142 | # 绘图 143 | #-------------------------------------------------------------# 144 | for j in range(anchors_num): 145 | plt.scatter(data[near == j][:,0], data[near == j][:,1]) 146 | plt.scatter(cluster[j][0], cluster[j][1], marker='x', c='black') 147 | plt.savefig("kmeans_for_anchors.jpg") 148 | plt.show() 149 | print('Save kmeans_for_anchors.jpg in root dir.') 150 | 151 | cluster = cluster[np.argsort(cluster[:, 0] * cluster[:, 1])] 152 | print('avg_ratio:{:.2f}'.format(avg_iou(data, cluster))) 153 | print(cluster) 154 | 155 | f = open("yolo_anchors.txt", 'w') 156 | row = np.shape(cluster)[0] 157 | for i in range(row): 158 | if i == 0: 159 | x_y = "%d,%d" % (cluster[i][0], cluster[i][1]) 160 | else: 161 | x_y = ", %d,%d" % (cluster[i][0], cluster[i][1]) 162 | f.write(x_y) 163 | f.close() 164 | -------------------------------------------------------------------------------- /logs/README.md: -------------------------------------------------------------------------------- 1 | 训练好的权重会保存在这里 2 | -------------------------------------------------------------------------------- /model_data/coco_classes.txt: -------------------------------------------------------------------------------- 1 | person 2 | bicycle 3 | car 4 | motorbike 5 | aeroplane 6 | bus 7 | train 8 | truck 9 | boat 10 | traffic light 11 | fire hydrant 12 | stop sign 13 | parking meter 14 | bench 15 | bird 16 | cat 17 | dog 18 | horse 19 | sheep 20 | cow 21 | elephant 22 | bear 23 | zebra 24 | giraffe 25 | backpack 26 | umbrella 27 | handbag 28 | tie 29 | suitcase 30 | frisbee 31 | skis 32 | snowboard 33 | sports ball 34 | kite 35 | baseball bat 36 | baseball glove 37 | skateboard 38 | surfboard 39 | tennis racket 40 | bottle 41 | wine glass 42 | cup 43 | fork 44 | knife 45 | spoon 46 | bowl 47 | banana 48 | apple 49 | sandwich 50 | orange 51 | broccoli 52 | carrot 53 | hot dog 54 | pizza 55 | donut 56 | cake 57 | chair 58 | sofa 59 | pottedplant 60 | bed 61 | diningtable 62 | toilet 63 | tvmonitor 64 | laptop 65 | mouse 66 | remote 67 | keyboard 68 | cell phone 69 | microwave 70 | oven 71 | toaster 72 | sink 73 | refrigerator 74 | book 75 | clock 76 | vase 77 | scissors 78 | teddy bear 79 | hair drier 80 | toothbrush 81 | -------------------------------------------------------------------------------- /model_data/simhei.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bubbliiiing/yolov4-tiny-tf2/b3e32e22687821e1028200f071b2fa4bc8a93029/model_data/simhei.ttf -------------------------------------------------------------------------------- /model_data/voc_classes.txt: -------------------------------------------------------------------------------- 1 | aeroplane 2 | bicycle 3 | bird 4 | boat 5 | bottle 6 | bus 7 | car 8 | cat 9 | chair 10 | cow 11 | diningtable 12 | dog 13 | horse 14 | motorbike 15 | person 16 | pottedplant 17 | sheep 18 | sofa 19 | train 20 | tvmonitor 21 | -------------------------------------------------------------------------------- /model_data/yolo_anchors.txt: -------------------------------------------------------------------------------- 1 | 10,14, 23,27, 37,58, 81,82, 135,169, 344,319 -------------------------------------------------------------------------------- /nets/CSPdarknet53_tiny.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | 3 | import tensorflow as tf 4 | from tensorflow.keras.initializers import RandomNormal 5 | from tensorflow.keras.layers import (BatchNormalization, Concatenate, 6 | Conv2D, Lambda, LeakyReLU, 7 | MaxPooling2D, ZeroPadding2D) 8 | from tensorflow.keras.regularizers import l2 9 | from utils.utils import compose 10 | 11 | 12 | def route_group(input_layer, groups, group_id): 13 | # 对通道数进行均等分割,我们取第二部分 14 | convs = tf.split(input_layer, num_or_size_splits=groups, axis=-1) 15 | return convs[group_id] 16 | 17 | #------------------------------------------------------# 18 | # 单次卷积DarknetConv2D 19 | # 如果步长为2则自己设定padding方式。 20 | #------------------------------------------------------# 21 | @wraps(Conv2D) 22 | def DarknetConv2D(*args, **kwargs): 23 | darknet_conv_kwargs = {'kernel_initializer' : RandomNormal(stddev=0.02), 'kernel_regularizer' : l2(kwargs.get('weight_decay', 5e-4))} 24 | darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides')==(2, 2) else 'same' 25 | try: 26 | del kwargs['weight_decay'] 27 | except: 28 | pass 29 | darknet_conv_kwargs.update(kwargs) 30 | return Conv2D(*args, **darknet_conv_kwargs) 31 | 32 | #---------------------------------------------------# 33 | # 卷积块 34 | # DarknetConv2D + BatchNormalization + LeakyReLU 35 | #---------------------------------------------------# 36 | def DarknetConv2D_BN_Leaky(*args, **kwargs): 37 | no_bias_kwargs = {'use_bias': False} 38 | no_bias_kwargs.update(kwargs) 39 | return compose( 40 | DarknetConv2D(*args, **no_bias_kwargs), 41 | BatchNormalization(), 42 | LeakyReLU(alpha=0.1)) 43 | 44 | ''' 45 | input 46 | | 47 | DarknetConv2D_BN_Leaky 48 | ----------------------- 49 | | | 50 | route_group route 51 | | | 52 | DarknetConv2D_BN_Leaky | 53 | | | 54 | ------------------- | 55 | | | | 56 | route_1 DarknetConv2D_BN_Leaky | 57 | | | | 58 | -------------Concatenate | 59 | | | 60 | ----DarknetConv2D_BN_Leaky | 61 | | | | 62 | feat Concatenate----------------- 63 | | 64 | MaxPooling2D 65 | ''' 66 | #---------------------------------------------------# 67 | # CSPdarknet_tiny的结构块 68 | # 存在一个大残差边 69 | # 这个大残差边绕过了很多的残差结构 70 | #---------------------------------------------------# 71 | def resblock_body(x, num_filters, weight_decay=5e-4): 72 | # 利用一个3x3卷积进行特征整合 73 | x = DarknetConv2D_BN_Leaky(num_filters, (3,3), weight_decay=weight_decay)(x) 74 | # 引出一个大的残差边route 75 | route = x 76 | 77 | # 对特征层的通道进行分割,取第二部分作为主干部分。 78 | x = Lambda(route_group,arguments={'groups':2, 'group_id':1})(x) 79 | # 对主干部分进行3x3卷积 80 | x = DarknetConv2D_BN_Leaky(int(num_filters/2), (3,3), weight_decay=weight_decay)(x) 81 | # 引出一个小的残差边route_1 82 | route_1 = x 83 | # 对第主干部分进行3x3卷积 84 | x = DarknetConv2D_BN_Leaky(int(num_filters/2), (3,3), weight_decay=weight_decay)(x) 85 | # 主干部分与残差部分进行相接 86 | x = Concatenate()([x, route_1]) 87 | 88 | # 对相接后的结果进行1x1卷积 89 | x = DarknetConv2D_BN_Leaky(num_filters, (1,1), weight_decay=weight_decay)(x) 90 | feat = x 91 | x = Concatenate()([route, x]) 92 | 93 | # 利用最大池化进行高和宽的压缩 94 | x = MaxPooling2D(pool_size=[2,2],)(x) 95 | 96 | return x, feat 97 | 98 | #---------------------------------------------------# 99 | # CSPdarknet_tiny的主体部分 100 | #---------------------------------------------------# 101 | def darknet_body(x, weight_decay=5e-4): 102 | # 首先利用两次步长为2x2的3x3卷积进行高和宽的压缩 103 | # 416,416,3 -> 208,208,32 -> 104,104,64 104 | x = ZeroPadding2D(((1,0),(1,0)))(x) 105 | x = DarknetConv2D_BN_Leaky(32, (3,3), strides=(2,2), weight_decay=weight_decay)(x) 106 | x = ZeroPadding2D(((1,0),(1,0)))(x) 107 | x = DarknetConv2D_BN_Leaky(64, (3,3), strides=(2,2), weight_decay=weight_decay)(x) 108 | 109 | # 104,104,64 -> 52,52,128 110 | x, _ = resblock_body(x, num_filters = 64, weight_decay=weight_decay) 111 | # 52,52,128 -> 26,26,256 112 | x, _ = resblock_body(x, num_filters = 128, weight_decay=weight_decay) 113 | # 26,26,256 -> x为13,13,512 114 | # -> feat1为26,26,256 115 | x, feat1 = resblock_body(x, num_filters = 256, weight_decay=weight_decay) 116 | # 13,13,512 -> 13,13,512 117 | x = DarknetConv2D_BN_Leaky(512, (3,3), weight_decay=weight_decay)(x) 118 | 119 | feat2 = x 120 | return feat1, feat2 121 | 122 | -------------------------------------------------------------------------------- /nets/__init__.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------------------------------- /nets/attention.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | from tensorflow.keras import backend as K 3 | from tensorflow.keras.layers import (Activation, Add, Concatenate, Conv1D, Conv2D, Dense, 4 | GlobalAveragePooling2D, GlobalMaxPooling2D, Lambda, BatchNormalization, 5 | Reshape, multiply) 6 | import math 7 | 8 | def se_block(input_feature, ratio=16, name=""): 9 | channel = K.int_shape(input_feature)[-1] 10 | 11 | se_feature = GlobalAveragePooling2D()(input_feature) 12 | se_feature = Reshape((1, 1, channel))(se_feature) 13 | 14 | se_feature = Dense(channel // ratio, 15 | activation='relu', 16 | kernel_initializer='he_normal', 17 | use_bias=False, 18 | name = "se_block_one_"+str(name))(se_feature) 19 | 20 | se_feature = Dense(channel, 21 | kernel_initializer='he_normal', 22 | use_bias=False, 23 | name = "se_block_two_"+str(name))(se_feature) 24 | se_feature = Activation('sigmoid')(se_feature) 25 | 26 | se_feature = multiply([input_feature, se_feature]) 27 | return se_feature 28 | 29 | def channel_attention(input_feature, ratio=8, name=""): 30 | channel = K.int_shape(input_feature)[-1] 31 | 32 | shared_layer_one = Dense(channel//ratio, 33 | activation='relu', 34 | kernel_initializer='he_normal', 35 | use_bias=False, 36 | bias_initializer='zeros', 37 | name = "channel_attention_shared_one_"+str(name)) 38 | shared_layer_two = Dense(channel, 39 | kernel_initializer='he_normal', 40 | use_bias=False, 41 | bias_initializer='zeros', 42 | name = "channel_attention_shared_two_"+str(name)) 43 | 44 | avg_pool = GlobalAveragePooling2D()(input_feature) 45 | max_pool = GlobalMaxPooling2D()(input_feature) 46 | 47 | avg_pool = Reshape((1,1,channel))(avg_pool) 48 | max_pool = Reshape((1,1,channel))(max_pool) 49 | 50 | avg_pool = shared_layer_one(avg_pool) 51 | max_pool = shared_layer_one(max_pool) 52 | 53 | avg_pool = shared_layer_two(avg_pool) 54 | max_pool = shared_layer_two(max_pool) 55 | 56 | cbam_feature = Add()([avg_pool,max_pool]) 57 | cbam_feature = Activation('sigmoid')(cbam_feature) 58 | 59 | 60 | return multiply([input_feature, cbam_feature]) 61 | 62 | def spatial_attention(input_feature, name=""): 63 | kernel_size = 7 64 | 65 | cbam_feature = input_feature 66 | 67 | avg_pool = Lambda(lambda x: K.mean(x, axis=3, keepdims=True))(cbam_feature) 68 | max_pool = Lambda(lambda x: K.max(x, axis=3, keepdims=True))(cbam_feature) 69 | concat = Concatenate(axis=3)([avg_pool, max_pool]) 70 | 71 | cbam_feature = Conv2D(filters = 1, 72 | kernel_size=kernel_size, 73 | strides=1, 74 | padding='same', 75 | kernel_initializer='he_normal', 76 | use_bias=False, 77 | name = "spatial_attention_"+str(name))(concat) 78 | cbam_feature = Activation('sigmoid')(cbam_feature) 79 | 80 | return multiply([input_feature, cbam_feature]) 81 | 82 | def cbam_block(cbam_feature, ratio=8, name=""): 83 | cbam_feature = channel_attention(cbam_feature, ratio, name=name) 84 | cbam_feature = spatial_attention(cbam_feature, name=name) 85 | return cbam_feature 86 | 87 | def eca_block(input_feature, b=1, gamma=2, name=""): 88 | channel = K.int_shape(input_feature)[-1] 89 | kernel_size = int(abs((math.log(channel, 2) + b) / gamma)) 90 | kernel_size = kernel_size if kernel_size % 2 else kernel_size + 1 91 | 92 | avg_pool = GlobalAveragePooling2D()(input_feature) 93 | 94 | x = Reshape((-1,1))(avg_pool) 95 | x = Conv1D(1, kernel_size=kernel_size, padding="same", name = "eca_layer_"+str(name), use_bias=False,)(x) 96 | x = Activation('sigmoid')(x) 97 | x = Reshape((1, 1, -1))(x) 98 | 99 | output = multiply([input_feature,x]) 100 | return output 101 | 102 | def ca_block(input_feature, ratio=16, name=""): 103 | channel = K.int_shape(input_feature)[-1] 104 | h = K.int_shape(input_feature)[1] 105 | w = K.int_shape(input_feature)[2] 106 | 107 | x_h = Lambda(lambda x: K.mean(x, axis=2, keepdims=True))(input_feature) 108 | x_h = Lambda(lambda x: K.permute_dimensions(x, [0, 2, 1, 3]))(x_h) 109 | x_w = Lambda(lambda x: K.max(x, axis=1, keepdims=True))(input_feature) 110 | 111 | x_cat_conv_relu = Concatenate(axis=2)([x_w, x_h]) 112 | x_cat_conv_relu = Conv2D(channel // ratio, kernel_size=1, strides=1, use_bias=False, name = "ca_block_conv1_"+str(name))(x_cat_conv_relu) 113 | x_cat_conv_relu = BatchNormalization(name = "ca_block_bn_"+str(name))(x_cat_conv_relu) 114 | x_cat_conv_relu = Activation('relu')(x_cat_conv_relu) 115 | 116 | x_cat_conv_split_h, x_cat_conv_split_w = Lambda(lambda x: tf.split(x, num_or_size_splits=[h, w], axis=2))(x_cat_conv_relu) 117 | x_cat_conv_split_h = Lambda(lambda x: K.permute_dimensions(x, [0, 2, 1, 3]))(x_cat_conv_split_h) 118 | x_cat_conv_split_h = Conv2D(channel, kernel_size=1, strides=1, use_bias=False, name = "ca_block_conv2_"+str(name))(x_cat_conv_split_h) 119 | x_cat_conv_split_h = Activation('sigmoid')(x_cat_conv_split_h) 120 | 121 | x_cat_conv_split_w = Conv2D(channel, kernel_size=1, strides=1, use_bias=False, name = "ca_block_conv3_"+str(name))(x_cat_conv_split_w) 122 | x_cat_conv_split_w = Activation('sigmoid')(x_cat_conv_split_w) 123 | 124 | output = multiply([input_feature, x_cat_conv_split_h]) 125 | output = multiply([output, x_cat_conv_split_w]) 126 | return output 127 | -------------------------------------------------------------------------------- /nets/yolo.py: -------------------------------------------------------------------------------- 1 | from tensorflow.keras.layers import Concatenate, Input, Lambda, UpSampling2D 2 | from tensorflow.keras.models import Model 3 | from utils.utils import compose 4 | 5 | from nets.attention import cbam_block, eca_block, se_block, ca_block 6 | from nets.CSPdarknet53_tiny import (DarknetConv2D, DarknetConv2D_BN_Leaky, 7 | darknet_body) 8 | from nets.yolo_training import yolo_loss 9 | 10 | attention = [se_block, cbam_block, eca_block, ca_block] 11 | 12 | #---------------------------------------------------# 13 | # 特征层->最后的输出 14 | #---------------------------------------------------# 15 | def yolo_body(input_shape, anchors_mask, num_classes, phi = 0, weight_decay=5e-4): 16 | inputs = Input(input_shape) 17 | #---------------------------------------------------# 18 | # 生成CSPdarknet53_tiny的主干模型 19 | # feat1的shape为26,26,256 20 | # feat2的shape为13,13,512 21 | #---------------------------------------------------# 22 | feat1, feat2 = darknet_body(inputs, weight_decay=weight_decay) 23 | if phi >= 1 and phi <= 4: 24 | feat1 = attention[phi - 1](feat1, name='feat1') 25 | feat2 = attention[phi - 1](feat2, name='feat2') 26 | 27 | # 13,13,512 -> 13,13,256 28 | P5 = DarknetConv2D_BN_Leaky(256, (1,1), weight_decay=weight_decay)(feat2) 29 | # 13,13,256 -> 13,13,512 -> 13,13,255 30 | P5_output = DarknetConv2D_BN_Leaky(512, (3,3), weight_decay=weight_decay)(P5) 31 | P5_output = DarknetConv2D(len(anchors_mask[0]) * (num_classes+5), (1,1), weight_decay=weight_decay)(P5_output) 32 | 33 | # 13,13,256 -> 13,13,128 -> 26,26,128 34 | P5_upsample = compose(DarknetConv2D_BN_Leaky(128, (1,1), weight_decay=weight_decay), UpSampling2D(2))(P5) 35 | if phi >= 1 and phi <= 4: 36 | P5_upsample = attention[phi - 1](P5_upsample, name='P5_upsample') 37 | 38 | # 26,26,256 + 26,26,128 -> 26,26,384 39 | P4 = Concatenate()([P5_upsample, feat1]) 40 | 41 | # 26,26,384 -> 26,26,256 -> 26,26,255 42 | P4_output = DarknetConv2D_BN_Leaky(256, (3,3), weight_decay=weight_decay)(P4) 43 | P4_output = DarknetConv2D(len(anchors_mask[1]) * (num_classes+5), (1,1), weight_decay=weight_decay)(P4_output) 44 | 45 | return Model(inputs, [P5_output, P4_output]) 46 | 47 | def get_train_model(model_body, input_shape, num_classes, anchors, anchors_mask, label_smoothing): 48 | y_true = [Input(shape = (input_shape[0] // {0:32, 1:16, 2:8}[l], input_shape[1] // {0:32, 1:16, 2:8}[l], \ 49 | len(anchors_mask[l]), num_classes + 5)) for l in range(len(anchors_mask))] 50 | model_loss = Lambda( 51 | yolo_loss, 52 | output_shape = (1, ), 53 | name = 'yolo_loss', 54 | arguments = { 55 | 'input_shape' : input_shape, 56 | 'anchors' : anchors, 57 | 'anchors_mask' : anchors_mask, 58 | 'num_classes' : num_classes, 59 | 'balance' : [0.4, 1.0, 4], 60 | 'box_ratio' : 0.05, 61 | 'obj_ratio' : 5 * (input_shape[0] * input_shape[1]) / (416 ** 2), 62 | 'cls_ratio' : 1 * (num_classes / 80), 63 | 'label_smoothing' : label_smoothing 64 | } 65 | )([*model_body.output, *y_true]) 66 | model = Model([model_body.input, *y_true], model_loss) 67 | return model 68 | -------------------------------------------------------------------------------- /nets/yolo_training.py: -------------------------------------------------------------------------------- 1 | import math 2 | from functools import partial 3 | 4 | import tensorflow as tf 5 | from tensorflow.keras import backend as K 6 | from utils.utils_bbox import get_anchors_and_decode 7 | 8 | 9 | def box_ciou(b1, b2): 10 | """ 11 | 输入为: 12 | ---------- 13 | b1: tensor, shape=(batch, feat_w, feat_h, anchor_num, 4), xywh 14 | b2: tensor, shape=(batch, feat_w, feat_h, anchor_num, 4), xywh 15 | 16 | 返回为: 17 | ------- 18 | ciou: tensor, shape=(batch, feat_w, feat_h, anchor_num, 1) 19 | """ 20 | #-----------------------------------------------------------# 21 | # 求出预测框左上角右下角 22 | # b1_mins (batch, feat_w, feat_h, anchor_num, 2) 23 | # b1_maxes (batch, feat_w, feat_h, anchor_num, 2) 24 | #-----------------------------------------------------------# 25 | b1_xy = b1[..., :2] 26 | b1_wh = b1[..., 2:4] 27 | b1_wh_half = b1_wh/2. 28 | b1_mins = b1_xy - b1_wh_half 29 | b1_maxes = b1_xy + b1_wh_half 30 | #-----------------------------------------------------------# 31 | # 求出真实框左上角右下角 32 | # b2_mins (batch, feat_w, feat_h, anchor_num, 2) 33 | # b2_maxes (batch, feat_w, feat_h, anchor_num, 2) 34 | #-----------------------------------------------------------# 35 | b2_xy = b2[..., :2] 36 | b2_wh = b2[..., 2:4] 37 | b2_wh_half = b2_wh/2. 38 | b2_mins = b2_xy - b2_wh_half 39 | b2_maxes = b2_xy + b2_wh_half 40 | 41 | #-----------------------------------------------------------# 42 | # 求真实框和预测框所有的iou 43 | # iou (batch, feat_w, feat_h, anchor_num) 44 | #-----------------------------------------------------------# 45 | intersect_mins = K.maximum(b1_mins, b2_mins) 46 | intersect_maxes = K.minimum(b1_maxes, b2_maxes) 47 | intersect_wh = K.maximum(intersect_maxes - intersect_mins, 0.) 48 | intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] 49 | b1_area = b1_wh[..., 0] * b1_wh[..., 1] 50 | b2_area = b2_wh[..., 0] * b2_wh[..., 1] 51 | union_area = b1_area + b2_area - intersect_area 52 | iou = intersect_area / K.maximum(union_area, K.epsilon()) 53 | 54 | #-----------------------------------------------------------# 55 | # 计算中心的差距 56 | # center_distance (batch, feat_w, feat_h, anchor_num) 57 | #-----------------------------------------------------------# 58 | center_distance = K.sum(K.square(b1_xy - b2_xy), axis=-1) 59 | enclose_mins = K.minimum(b1_mins, b2_mins) 60 | enclose_maxes = K.maximum(b1_maxes, b2_maxes) 61 | enclose_wh = K.maximum(enclose_maxes - enclose_mins, 0.0) 62 | #-----------------------------------------------------------# 63 | # 计算对角线距离 64 | # enclose_diagonal (batch, feat_w, feat_h, anchor_num) 65 | #-----------------------------------------------------------# 66 | enclose_diagonal = K.sum(K.square(enclose_wh), axis=-1) 67 | ciou = iou - 1.0 * (center_distance) / K.maximum(enclose_diagonal ,K.epsilon()) 68 | 69 | v = 4 * K.square(tf.math.atan2(b1_wh[..., 0], K.maximum(b1_wh[..., 1], K.epsilon())) - tf.math.atan2(b2_wh[..., 0], K.maximum(b2_wh[..., 1],K.epsilon()))) / (math.pi * math.pi) 70 | alpha = v / K.maximum((1.0 - iou + v), K.epsilon()) 71 | ciou = ciou - alpha * v 72 | 73 | ciou = K.expand_dims(ciou, -1) 74 | return ciou 75 | 76 | #---------------------------------------------------# 77 | # 平滑标签 78 | #---------------------------------------------------# 79 | def _smooth_labels(y_true, label_smoothing): 80 | num_classes = tf.cast(K.shape(y_true)[-1], dtype=K.floatx()) 81 | label_smoothing = K.constant(label_smoothing, dtype=K.floatx()) 82 | return y_true * (1.0 - label_smoothing) + label_smoothing / num_classes 83 | 84 | #---------------------------------------------------# 85 | # 用于计算每个预测框与真实框的iou 86 | #---------------------------------------------------# 87 | def box_iou(b1, b2): 88 | #---------------------------------------------------# 89 | # num_anchor,1,4 90 | # 计算左上角的坐标和右下角的坐标 91 | #---------------------------------------------------# 92 | b1 = K.expand_dims(b1, -2) 93 | b1_xy = b1[..., :2] 94 | b1_wh = b1[..., 2:4] 95 | b1_wh_half = b1_wh/2. 96 | b1_mins = b1_xy - b1_wh_half 97 | b1_maxes = b1_xy + b1_wh_half 98 | 99 | #---------------------------------------------------# 100 | # 1,n,4 101 | # 计算左上角和右下角的坐标 102 | #---------------------------------------------------# 103 | b2 = K.expand_dims(b2, 0) 104 | b2_xy = b2[..., :2] 105 | b2_wh = b2[..., 2:4] 106 | b2_wh_half = b2_wh/2. 107 | b2_mins = b2_xy - b2_wh_half 108 | b2_maxes = b2_xy + b2_wh_half 109 | 110 | #---------------------------------------------------# 111 | # 计算重合面积 112 | #---------------------------------------------------# 113 | intersect_mins = K.maximum(b1_mins, b2_mins) 114 | intersect_maxes = K.minimum(b1_maxes, b2_maxes) 115 | intersect_wh = K.maximum(intersect_maxes - intersect_mins, 0.) 116 | intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] 117 | b1_area = b1_wh[..., 0] * b1_wh[..., 1] 118 | b2_area = b2_wh[..., 0] * b2_wh[..., 1] 119 | iou = intersect_area / (b1_area + b2_area - intersect_area) 120 | 121 | return iou 122 | 123 | #---------------------------------------------------# 124 | # loss值计算 125 | #---------------------------------------------------# 126 | def yolo_loss( 127 | args, 128 | input_shape, 129 | anchors, 130 | anchors_mask, 131 | num_classes, 132 | ignore_thresh = 0.5, 133 | balance = [0.4, 1.0, 4], 134 | box_ratio = 0.05, 135 | obj_ratio = 1, 136 | cls_ratio = 0.5 / 4, 137 | label_smoothing = 0.1, 138 | print_loss = False 139 | ): 140 | num_layers = len(anchors_mask) 141 | #---------------------------------------------------------------------------------------------------# 142 | # 将预测结果和实际ground truth分开,args是[*model_body.output, *y_true] 143 | # y_true是一个列表,包含三个特征层,shape分别为: 144 | # (m,13,13,3,85) 145 | # (m,26,26,3,85) 146 | # yolo_outputs是一个列表,包含三个特征层,shape分别为: 147 | # (m,13,13,3,85) 148 | # (m,26,26,3,85) 149 | #---------------------------------------------------------------------------------------------------# 150 | y_true = args[num_layers:] 151 | yolo_outputs = args[:num_layers] 152 | 153 | #-----------------------------------------------------------# 154 | # 得到input_shpae为416,416 155 | #-----------------------------------------------------------# 156 | input_shape = K.cast(input_shape, K.dtype(y_true[0])) 157 | 158 | #-----------------------------------------------------------# 159 | # 取出每一张图片 160 | # m的值就是batch_size 161 | #-----------------------------------------------------------# 162 | m = K.shape(yolo_outputs[0])[0] 163 | 164 | loss = 0 165 | #---------------------------------------------------------------------------------------------------# 166 | # y_true是一个列表,包含三个特征层,shape分别为(m,13,13,3,85),(m,26,26,3,85) 167 | # yolo_outputs是一个列表,包含三个特征层,shape分别为(m,13,13,3,85),(m,26,26,3,85) 168 | #---------------------------------------------------------------------------------------------------# 169 | for l in range(num_layers): 170 | #-----------------------------------------------------------# 171 | # 以第一个特征层(m,13,13,3,85)为例子 172 | # 取出该特征层中存在目标的点的位置。(m,13,13,3,1) 173 | #-----------------------------------------------------------# 174 | object_mask = y_true[l][..., 4:5] 175 | #-----------------------------------------------------------# 176 | # 取出其对应的种类(m,13,13,3,80) 177 | #-----------------------------------------------------------# 178 | true_class_probs = y_true[l][..., 5:] 179 | if label_smoothing: 180 | true_class_probs = _smooth_labels(true_class_probs, label_smoothing) 181 | 182 | #-----------------------------------------------------------# 183 | # 将yolo_outputs的特征层输出进行处理、获得四个返回值 184 | # 其中: 185 | # grid (13,13,1,2) 网格坐标 186 | # raw_pred (m,13,13,3,85) 尚未处理的预测结果 187 | # pred_xy (m,13,13,3,2) 解码后的中心坐标 188 | # pred_wh (m,13,13,3,2) 解码后的宽高坐标 189 | #-----------------------------------------------------------# 190 | grid, raw_pred, pred_xy, pred_wh = get_anchors_and_decode(yolo_outputs[l], 191 | anchors[anchors_mask[l]], num_classes, input_shape, calc_loss=True) 192 | 193 | #-----------------------------------------------------------# 194 | # pred_box是解码后的预测的box的位置 195 | # (m,13,13,3,4) 196 | #-----------------------------------------------------------# 197 | pred_box = K.concatenate([pred_xy, pred_wh]) 198 | 199 | #-----------------------------------------------------------# 200 | # 找到负样本群组,第一步是创建一个数组,[] 201 | #-----------------------------------------------------------# 202 | ignore_mask = tf.TensorArray(K.dtype(y_true[0]), size=1, dynamic_size=True) 203 | object_mask_bool = K.cast(object_mask, 'bool') 204 | 205 | #-----------------------------------------------------------# 206 | # 对每一张图片计算ignore_mask 207 | #-----------------------------------------------------------# 208 | def loop_body(b, ignore_mask): 209 | #-----------------------------------------------------------# 210 | # 取出n个真实框:n,4 211 | #-----------------------------------------------------------# 212 | true_box = tf.boolean_mask(y_true[l][b,...,0:4], object_mask_bool[b,...,0]) 213 | #-----------------------------------------------------------# 214 | # 计算预测框与真实框的iou 215 | # pred_box 13,13,3,4 预测框的坐标 216 | # true_box n,4 真实框的坐标 217 | # iou 13,13,3,n 预测框和真实框的iou 218 | #-----------------------------------------------------------# 219 | iou = box_iou(pred_box[b], true_box) 220 | 221 | #-----------------------------------------------------------# 222 | # best_iou 13,13,3 每个特征点与真实框的最大重合程度 223 | #-----------------------------------------------------------# 224 | best_iou = K.max(iou, axis=-1) 225 | 226 | #-----------------------------------------------------------# 227 | # 判断预测框和真实框的最大iou小于ignore_thresh 228 | # 则认为该预测框没有与之对应的真实框 229 | # 该操作的目的是: 230 | # 忽略预测结果与真实框非常对应特征点,因为这些框已经比较准了 231 | # 不适合当作负样本,所以忽略掉。 232 | #-----------------------------------------------------------# 233 | ignore_mask = ignore_mask.write(b, K.cast(best_iou= total_iters - no_aug_iter: 301 | lr = min_lr 302 | else: 303 | lr = min_lr + 0.5 * (lr - min_lr) * ( 304 | 1.0 305 | + math.cos( 306 | math.pi 307 | * (iters - warmup_total_iters) 308 | / (total_iters - warmup_total_iters - no_aug_iter) 309 | ) 310 | ) 311 | return lr 312 | 313 | def step_lr(lr, decay_rate, step_size, iters): 314 | if step_size < 1: 315 | raise ValueError("step_size must above 1.") 316 | n = iters // step_size 317 | out_lr = lr * decay_rate ** n 318 | return out_lr 319 | 320 | if lr_decay_type == "cos": 321 | warmup_total_iters = min(max(warmup_iters_ratio * total_iters, 1), 3) 322 | warmup_lr_start = max(warmup_lr_ratio * lr, 1e-6) 323 | no_aug_iter = min(max(no_aug_iter_ratio * total_iters, 1), 15) 324 | func = partial(yolox_warm_cos_lr ,lr, min_lr, total_iters, warmup_total_iters, warmup_lr_start, no_aug_iter) 325 | else: 326 | decay_rate = (min_lr / lr) ** (1 / (step_num - 1)) 327 | step_size = total_iters / step_num 328 | func = partial(step_lr, lr, decay_rate, step_size) 329 | 330 | return func 331 | 332 | -------------------------------------------------------------------------------- /predict.py: -------------------------------------------------------------------------------- 1 | #-----------------------------------------------------------------------# 2 | # predict.py将单张图片预测、摄像头检测、FPS测试和目录遍历检测等功能 3 | # 整合到了一个py文件中,通过指定mode进行模式的修改。 4 | #-----------------------------------------------------------------------# 5 | import time 6 | 7 | import cv2 8 | import numpy as np 9 | import tensorflow as tf 10 | from PIL import Image 11 | 12 | from yolo import YOLO, YOLO_ONNX 13 | 14 | gpus = tf.config.experimental.list_physical_devices(device_type='GPU') 15 | for gpu in gpus: 16 | tf.config.experimental.set_memory_growth(gpu, True) 17 | 18 | if __name__ == "__main__": 19 | #----------------------------------------------------------------------------------------------------------# 20 | # mode用于指定测试的模式: 21 | # 'predict' 表示单张图片预测,如果想对预测过程进行修改,如保存图片,截取对象等,可以先看下方详细的注释 22 | # 'video' 表示视频检测,可调用摄像头或者视频进行检测,详情查看下方注释。 23 | # 'fps' 表示测试fps,使用的图片是img里面的street.jpg,详情查看下方注释。 24 | # 'dir_predict' 表示遍历文件夹进行检测并保存。默认遍历img文件夹,保存img_out文件夹,详情查看下方注释。 25 | # 'heatmap' 表示进行预测结果的热力图可视化,详情查看下方注释。 26 | # 'export_onnx' 表示将模型导出为onnx,需要pytorch1.7.1以上。 27 | # 'predict_onnx' 表示利用导出的onnx模型进行预测,相关参数的修改在yolo.py_360行左右处的YOLO_ONNX 28 | #----------------------------------------------------------------------------------------------------------# 29 | mode = "predict" 30 | #-------------------------------------------------------------------------# 31 | # crop 指定了是否在单张图片预测后对目标进行截取 32 | # count 指定了是否进行目标的计数 33 | # crop、count仅在mode='predict'时有效 34 | #-------------------------------------------------------------------------# 35 | crop = False 36 | count = False 37 | #----------------------------------------------------------------------------------------------------------# 38 | # video_path 用于指定视频的路径,当video_path=0时表示检测摄像头 39 | # 想要检测视频,则设置如video_path = "xxx.mp4"即可,代表读取出根目录下的xxx.mp4文件。 40 | # video_save_path 表示视频保存的路径,当video_save_path=""时表示不保存 41 | # 想要保存视频,则设置如video_save_path = "yyy.mp4"即可,代表保存为根目录下的yyy.mp4文件。 42 | # video_fps 用于保存的视频的fps 43 | # 44 | # video_path、video_save_path和video_fps仅在mode='video'时有效 45 | # 保存视频时需要ctrl+c退出或者运行到最后一帧才会完成完整的保存步骤。 46 | #----------------------------------------------------------------------------------------------------------# 47 | video_path = 0 48 | video_save_path = "" 49 | video_fps = 25.0 50 | #----------------------------------------------------------------------------------------------------------# 51 | # test_interval 用于指定测量fps的时候,图片检测的次数。理论上test_interval越大,fps越准确。 52 | # fps_image_path 用于指定测试的fps图片 53 | # 54 | # test_interval和fps_image_path仅在mode='fps'有效 55 | #----------------------------------------------------------------------------------------------------------# 56 | test_interval = 100 57 | fps_image_path = "img/street.jpg" 58 | #-------------------------------------------------------------------------# 59 | # dir_origin_path 指定了用于检测的图片的文件夹路径 60 | # dir_save_path 指定了检测完图片的保存路径 61 | # 62 | # dir_origin_path和dir_save_path仅在mode='dir_predict'时有效 63 | #-------------------------------------------------------------------------# 64 | dir_origin_path = "img/" 65 | dir_save_path = "img_out/" 66 | #-------------------------------------------------------------------------# 67 | # heatmap_save_path 热力图的保存路径,默认保存在model_data下 68 | # 69 | # heatmap_save_path仅在mode='heatmap'有效 70 | #-------------------------------------------------------------------------# 71 | heatmap_save_path = "model_data/heatmap_vision.png" 72 | #-------------------------------------------------------------------------# 73 | # simplify 使用Simplify onnx 74 | # onnx_save_path 指定了onnx的保存路径 75 | #-------------------------------------------------------------------------# 76 | simplify = True 77 | onnx_save_path = "model_data/models.onnx" 78 | 79 | if mode != "predict_onnx": 80 | yolo = YOLO() 81 | else: 82 | yolo = YOLO_ONNX() 83 | 84 | if mode == "predict": 85 | ''' 86 | 1、如果想要进行检测完的图片的保存,利用r_image.save("img.jpg")即可保存,直接在predict.py里进行修改即可。 87 | 2、如果想要获得预测框的坐标,可以进入yolo.detect_image函数,在绘图部分读取top,left,bottom,right这四个值。 88 | 3、如果想要利用预测框截取下目标,可以进入yolo.detect_image函数,在绘图部分利用获取到的top,left,bottom,right这四个值 89 | 在原图上利用矩阵的方式进行截取。 90 | 4、如果想要在预测图上写额外的字,比如检测到的特定目标的数量,可以进入yolo.detect_image函数,在绘图部分对predicted_class进行判断, 91 | 比如判断if predicted_class == 'car': 即可判断当前目标是否为车,然后记录数量即可。利用draw.text即可写字。 92 | ''' 93 | while True: 94 | img = input('Input image filename:') 95 | try: 96 | image = Image.open(img) 97 | except: 98 | print('Open Error! Try again!') 99 | continue 100 | else: 101 | r_image = yolo.detect_image(image, crop = crop, count=count) 102 | r_image.show() 103 | 104 | elif mode == "video": 105 | capture = cv2.VideoCapture(video_path) 106 | if video_save_path!="": 107 | fourcc = cv2.VideoWriter_fourcc(*'XVID') 108 | size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))) 109 | out = cv2.VideoWriter(video_save_path, fourcc, video_fps, size) 110 | 111 | ref, frame = capture.read() 112 | if not ref: 113 | raise ValueError("未能正确读取摄像头(视频),请注意是否正确安装摄像头(是否正确填写视频路径)。") 114 | 115 | fps = 0.0 116 | while(True): 117 | t1 = time.time() 118 | # 读取某一帧 119 | ref, frame = capture.read() 120 | if not ref: 121 | break 122 | # 格式转变,BGRtoRGB 123 | frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) 124 | # 转变成Image 125 | frame = Image.fromarray(np.uint8(frame)) 126 | # 进行检测 127 | frame = np.array(yolo.detect_image(frame)) 128 | # RGBtoBGR满足opencv显示格式 129 | frame = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR) 130 | 131 | fps = ( fps + (1./(time.time()-t1)) ) / 2 132 | print("fps= %.2f"%(fps)) 133 | frame = cv2.putText(frame, "fps= %.2f"%(fps), (0, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) 134 | 135 | cv2.imshow("video",frame) 136 | c= cv2.waitKey(1) & 0xff 137 | if video_save_path!="": 138 | out.write(frame) 139 | 140 | if c==27: 141 | capture.release() 142 | break 143 | 144 | print("Video Detection Done!") 145 | capture.release() 146 | if video_save_path!="": 147 | print("Save processed video to the path :" + video_save_path) 148 | out.release() 149 | cv2.destroyAllWindows() 150 | 151 | elif mode == "fps": 152 | img = Image.open(fps_image_path) 153 | tact_time = yolo.get_FPS(img, test_interval) 154 | print(str(tact_time) + ' seconds, ' + str(1/tact_time) + 'FPS, @batch_size 1') 155 | 156 | elif mode == "dir_predict": 157 | import os 158 | 159 | from tqdm import tqdm 160 | 161 | img_names = os.listdir(dir_origin_path) 162 | for img_name in tqdm(img_names): 163 | if img_name.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.tif', '.tiff')): 164 | image_path = os.path.join(dir_origin_path, img_name) 165 | image = Image.open(image_path) 166 | r_image = yolo.detect_image(image) 167 | if not os.path.exists(dir_save_path): 168 | os.makedirs(dir_save_path) 169 | r_image.save(os.path.join(dir_save_path, img_name.replace(".jpg", ".png")), quality=95, subsampling=0) 170 | 171 | elif mode == "heatmap": 172 | while True: 173 | img = input('Input image filename:') 174 | try: 175 | image = Image.open(img) 176 | except: 177 | print('Open Error! Try again!') 178 | continue 179 | else: 180 | yolo.detect_heatmap(image, heatmap_save_path) 181 | 182 | elif mode == "export_onnx": 183 | yolo.convert_to_onnx(simplify, onnx_save_path) 184 | 185 | elif mode == "predict_onnx": 186 | while True: 187 | img = input('Input image filename:') 188 | try: 189 | image = Image.open(img) 190 | except: 191 | print('Open Error! Try again!') 192 | continue 193 | else: 194 | r_image = yolo.detect_image(image) 195 | r_image.show() 196 | 197 | else: 198 | raise AssertionError("Please specify the correct mode: 'predict', 'video', 'fps' or 'dir_predict'.") 199 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | scipy==1.4.1 2 | numpy==1.18.4 3 | matplotlib==3.2.1 4 | opencv_python==4.2.0.34 5 | tensorflow_gpu==2.2.0 6 | tqdm==4.46.1 7 | Pillow==8.2.0 8 | h5py==2.10.0 9 | -------------------------------------------------------------------------------- /summary.py: -------------------------------------------------------------------------------- 1 | #--------------------------------------------# 2 | # 该部分代码用于看网络结构 3 | #--------------------------------------------# 4 | from nets.yolo import yolo_body 5 | from utils.utils import net_flops 6 | 7 | if __name__ == "__main__": 8 | input_shape = [416, 416, 3] 9 | anchors_mask = [[3, 4, 5], [1, 2, 3]] 10 | num_classes = 80 11 | phi = 0 12 | 13 | model = yolo_body([input_shape[0], input_shape[1], 3], anchors_mask, num_classes, phi=phi) 14 | #--------------------------------------------# 15 | # 查看网络结构网络结构 16 | #--------------------------------------------# 17 | model.summary() 18 | #--------------------------------------------# 19 | # 计算网络的FLOPS 20 | #--------------------------------------------# 21 | net_flops(model, table=False) 22 | 23 | #--------------------------------------------# 24 | # 获得网络每个层的名称与序号 25 | #--------------------------------------------# 26 | # for i,layer in enumerate(model.layers): 27 | # print(i,layer.name) 28 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------------------------------- /utils/callbacks.py: -------------------------------------------------------------------------------- 1 | import os 2 | import math 3 | import warnings 4 | 5 | import matplotlib 6 | matplotlib.use('Agg') 7 | from matplotlib import pyplot as plt 8 | import scipy.signal 9 | 10 | import shutil 11 | import numpy as np 12 | import tensorflow as tf 13 | 14 | from tensorflow import keras 15 | from tensorflow.keras import backend as K 16 | from tensorflow.keras.layers import Input, Lambda 17 | from tensorflow.keras.models import Model 18 | from PIL import Image 19 | from tqdm import tqdm 20 | from .utils import cvtColor, preprocess_input, resize_image 21 | from .utils_bbox import DecodeBox 22 | from .utils_map import get_coco_map, get_map 23 | 24 | 25 | class LossHistory(keras.callbacks.Callback): 26 | def __init__(self, log_dir): 27 | self.log_dir = log_dir 28 | self.losses = [] 29 | self.val_loss = [] 30 | 31 | os.makedirs(self.log_dir) 32 | 33 | def on_epoch_end(self, epoch, logs={}): 34 | if not os.path.exists(self.log_dir): 35 | os.makedirs(self.log_dir) 36 | 37 | self.losses.append(logs.get('loss')) 38 | self.val_loss.append(logs.get('val_loss')) 39 | 40 | with open(os.path.join(self.log_dir, "epoch_loss.txt"), 'a') as f: 41 | f.write(str(logs.get('loss'))) 42 | f.write("\n") 43 | with open(os.path.join(self.log_dir, "epoch_val_loss.txt"), 'a') as f: 44 | f.write(str(logs.get('val_loss'))) 45 | f.write("\n") 46 | self.loss_plot() 47 | 48 | def loss_plot(self): 49 | iters = range(len(self.losses)) 50 | 51 | plt.figure() 52 | plt.plot(iters, self.losses, 'red', linewidth = 2, label='train loss') 53 | plt.plot(iters, self.val_loss, 'coral', linewidth = 2, label='val loss') 54 | try: 55 | if len(self.losses) < 25: 56 | num = 5 57 | else: 58 | num = 15 59 | 60 | plt.plot(iters, scipy.signal.savgol_filter(self.losses, num, 3), 'green', linestyle = '--', linewidth = 2, label='smooth train loss') 61 | plt.plot(iters, scipy.signal.savgol_filter(self.val_loss, num, 3), '#8B4513', linestyle = '--', linewidth = 2, label='smooth val loss') 62 | except: 63 | pass 64 | 65 | plt.grid(True) 66 | plt.xlabel('Epoch') 67 | plt.ylabel('Loss') 68 | plt.title('A Loss Curve') 69 | plt.legend(loc="upper right") 70 | 71 | plt.savefig(os.path.join(self.log_dir, "epoch_loss.png")) 72 | 73 | plt.cla() 74 | plt.close("all") 75 | 76 | class ExponentDecayScheduler(keras.callbacks.Callback): 77 | def __init__(self, 78 | decay_rate, 79 | verbose=0): 80 | super(ExponentDecayScheduler, self).__init__() 81 | self.decay_rate = decay_rate 82 | self.verbose = verbose 83 | self.learning_rates = [] 84 | 85 | def on_epoch_end(self, batch, logs=None): 86 | learning_rate = K.get_value(self.model.optimizer.lr) * self.decay_rate 87 | K.set_value(self.model.optimizer.lr, learning_rate) 88 | if self.verbose > 0: 89 | print('Setting learning rate to %s.' % (learning_rate)) 90 | 91 | class WarmUpCosineDecayScheduler(keras.callbacks.Callback): 92 | def __init__(self, T_max, eta_min=0, verbose=0): 93 | super(WarmUpCosineDecayScheduler, self).__init__() 94 | self.T_max = T_max 95 | self.eta_min = eta_min 96 | self.verbose = verbose 97 | self.init_lr = 0 98 | self.last_epoch = 0 99 | 100 | def on_train_begin(self, batch, logs=None): 101 | self.init_lr = K.get_value(self.model.optimizer.lr) 102 | 103 | def on_epoch_end(self, batch, logs=None): 104 | learning_rate = self.eta_min + (self.init_lr - self.eta_min) * (1 + math.cos(math.pi * self.last_epoch / self.T_max)) / 2 105 | self.last_epoch += 1 106 | 107 | K.set_value(self.model.optimizer.lr, learning_rate) 108 | if self.verbose > 0: 109 | print('Setting learning rate to %s.' % (learning_rate)) 110 | 111 | class EvalCallback(keras.callbacks.Callback): 112 | def __init__(self, model_body, input_shape, anchors, anchors_mask, class_names, num_classes, val_lines, log_dir,\ 113 | map_out_path=".temp_map_out", max_boxes=100, confidence=0.05, nms_iou=0.5, letterbox_image=True, MINOVERLAP=0.5, eval_flag=True, period=1): 114 | super(EvalCallback, self).__init__() 115 | 116 | self.model_body = model_body 117 | self.input_shape = input_shape 118 | self.anchors = anchors 119 | self.anchors_mask = anchors_mask 120 | self.class_names = class_names 121 | self.num_classes = num_classes 122 | self.val_lines = val_lines 123 | self.log_dir = log_dir 124 | self.map_out_path = map_out_path 125 | self.max_boxes = max_boxes 126 | self.confidence = confidence 127 | self.nms_iou = nms_iou 128 | self.letterbox_image = letterbox_image 129 | self.MINOVERLAP = MINOVERLAP 130 | self.eval_flag = eval_flag 131 | self.period = period 132 | 133 | #---------------------------------------------------------# 134 | # 在DecodeBox函数中,我们会对预测结果进行后处理 135 | # 后处理的内容包括,解码、非极大抑制、门限筛选等 136 | #---------------------------------------------------------# 137 | self.input_image_shape = Input([2,],batch_size=1) 138 | inputs = [*self.model_body.output, self.input_image_shape] 139 | outputs = Lambda( 140 | DecodeBox, 141 | output_shape = (1,), 142 | name = 'yolo_eval', 143 | arguments = { 144 | 'anchors' : self.anchors, 145 | 'num_classes' : self.num_classes, 146 | 'input_shape' : self.input_shape, 147 | 'anchor_mask' : self.anchors_mask, 148 | 'confidence' : self.confidence, 149 | 'nms_iou' : self.nms_iou, 150 | 'max_boxes' : self.max_boxes, 151 | 'letterbox_image' : self.letterbox_image 152 | } 153 | )(inputs) 154 | self.yolo_model = Model([self.model_body.input, self.input_image_shape], outputs) 155 | 156 | self.maps = [0] 157 | self.epoches = [0] 158 | if self.eval_flag: 159 | with open(os.path.join(self.log_dir, "epoch_map.txt"), 'a') as f: 160 | f.write(str(0)) 161 | f.write("\n") 162 | 163 | @tf.function 164 | def get_pred(self, image_data, input_image_shape): 165 | out_boxes, out_scores, out_classes = self.yolo_model([image_data, input_image_shape], training=False) 166 | return out_boxes, out_scores, out_classes 167 | 168 | def get_map_txt(self, image_id, image, class_names, map_out_path): 169 | f = open(os.path.join(map_out_path, "detection-results/"+image_id+".txt"),"w") 170 | #---------------------------------------------------------# 171 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 172 | #---------------------------------------------------------# 173 | image = cvtColor(image) 174 | #---------------------------------------------------------# 175 | # 给图像增加灰条,实现不失真的resize 176 | # 也可以直接resize进行识别 177 | #---------------------------------------------------------# 178 | image_data = resize_image(image, (self.input_shape[1], self.input_shape[0]), self.letterbox_image) 179 | #---------------------------------------------------------# 180 | # 添加上batch_size维度,并进行归一化 181 | #---------------------------------------------------------# 182 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 183 | 184 | #---------------------------------------------------------# 185 | # 将图像输入网络当中进行预测! 186 | #---------------------------------------------------------# 187 | input_image_shape = np.expand_dims(np.array([image.size[1], image.size[0]], dtype='float32'), 0) 188 | outputs = self.get_pred(image_data, input_image_shape) 189 | out_boxes, out_scores, out_classes = [out.numpy() for out in outputs] 190 | 191 | top_100 = np.argsort(out_scores)[::-1][:self.max_boxes] 192 | out_boxes = out_boxes[top_100] 193 | out_scores = out_scores[top_100] 194 | out_classes = out_classes[top_100] 195 | 196 | for i, c in enumerate(out_classes): 197 | predicted_class = self.class_names[int(c)] 198 | try: 199 | score = str(out_scores[i].numpy()) 200 | except: 201 | score = str(out_scores[i]) 202 | top, left, bottom, right = out_boxes[i] 203 | if predicted_class not in class_names: 204 | continue 205 | 206 | f.write("%s %s %s %s %s %s\n" % (predicted_class, score[:6], str(int(left)), str(int(top)), str(int(right)),str(int(bottom)))) 207 | 208 | f.close() 209 | return 210 | 211 | def on_epoch_end(self, epoch, logs=None): 212 | temp_epoch = epoch + 1 213 | if temp_epoch % self.period == 0 and self.eval_flag: 214 | if not os.path.exists(self.map_out_path): 215 | os.makedirs(self.map_out_path) 216 | if not os.path.exists(os.path.join(self.map_out_path, "ground-truth")): 217 | os.makedirs(os.path.join(self.map_out_path, "ground-truth")) 218 | if not os.path.exists(os.path.join(self.map_out_path, "detection-results")): 219 | os.makedirs(os.path.join(self.map_out_path, "detection-results")) 220 | print("Get map.") 221 | for annotation_line in tqdm(self.val_lines): 222 | line = annotation_line.split() 223 | image_id = os.path.basename(line[0]).split('.')[0] 224 | #------------------------------# 225 | # 读取图像并转换成RGB图像 226 | #------------------------------# 227 | image = Image.open(line[0]) 228 | #------------------------------# 229 | # 获得预测框 230 | #------------------------------# 231 | gt_boxes = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) 232 | #------------------------------# 233 | # 获得预测txt 234 | #------------------------------# 235 | self.get_map_txt(image_id, image, self.class_names, self.map_out_path) 236 | 237 | #------------------------------# 238 | # 获得真实框txt 239 | #------------------------------# 240 | with open(os.path.join(self.map_out_path, "ground-truth/"+image_id+".txt"), "w") as new_f: 241 | for box in gt_boxes: 242 | left, top, right, bottom, obj = box 243 | obj_name = self.class_names[obj] 244 | new_f.write("%s %s %s %s %s\n" % (obj_name, left, top, right, bottom)) 245 | 246 | print("Calculate Map.") 247 | try: 248 | temp_map = get_coco_map(class_names = self.class_names, path = self.map_out_path)[1] 249 | except: 250 | temp_map = get_map(self.MINOVERLAP, False, path = self.map_out_path) 251 | self.maps.append(temp_map) 252 | self.epoches.append(temp_epoch) 253 | 254 | with open(os.path.join(self.log_dir, "epoch_map.txt"), 'a') as f: 255 | f.write(str(temp_map)) 256 | f.write("\n") 257 | 258 | plt.figure() 259 | plt.plot(self.epoches, self.maps, 'red', linewidth = 2, label='train map') 260 | 261 | plt.grid(True) 262 | plt.xlabel('Epoch') 263 | plt.ylabel('Map %s'%str(self.MINOVERLAP)) 264 | plt.title('A Map Curve') 265 | plt.legend(loc="upper right") 266 | 267 | plt.savefig(os.path.join(self.log_dir, "epoch_map.png")) 268 | plt.cla() 269 | plt.close("all") 270 | 271 | print("Get map done.") 272 | shutil.rmtree(self.map_out_path) 273 | 274 | class ModelCheckpoint(keras.callbacks.Callback): 275 | def __init__(self, filepath, monitor='val_loss', verbose=0, 276 | save_best_only=False, save_weights_only=False, 277 | mode='auto', period=1): 278 | super(ModelCheckpoint, self).__init__() 279 | self.monitor = monitor 280 | self.verbose = verbose 281 | self.filepath = filepath 282 | self.save_best_only = save_best_only 283 | self.save_weights_only = save_weights_only 284 | self.period = period 285 | self.epochs_since_last_save = 0 286 | 287 | if mode not in ['auto', 'min', 'max']: 288 | warnings.warn('ModelCheckpoint mode %s is unknown, ' 289 | 'fallback to auto mode.' % (mode), 290 | RuntimeWarning) 291 | mode = 'auto' 292 | 293 | if mode == 'min': 294 | self.monitor_op = np.less 295 | self.best = np.Inf 296 | elif mode == 'max': 297 | self.monitor_op = np.greater 298 | self.best = -np.Inf 299 | else: 300 | if 'acc' in self.monitor or self.monitor.startswith('fmeasure'): 301 | self.monitor_op = np.greater 302 | self.best = -np.Inf 303 | else: 304 | self.monitor_op = np.less 305 | self.best = np.Inf 306 | 307 | def on_epoch_end(self, epoch, logs=None): 308 | logs = logs or {} 309 | self.epochs_since_last_save += 1 310 | if self.epochs_since_last_save >= self.period: 311 | self.epochs_since_last_save = 0 312 | filepath = self.filepath.format(epoch=epoch + 1, **logs) 313 | if self.save_best_only: 314 | current = logs.get(self.monitor) 315 | if current is None: 316 | warnings.warn('Can save best model only with %s available, ' 317 | 'skipping.' % (self.monitor), RuntimeWarning) 318 | else: 319 | if self.monitor_op(current, self.best): 320 | if self.verbose > 0: 321 | print('\nEpoch %05d: %s improved from %0.5f to %0.5f,' 322 | ' saving model to %s' 323 | % (epoch + 1, self.monitor, self.best, 324 | current, filepath)) 325 | self.best = current 326 | if self.save_weights_only: 327 | self.model.save_weights(filepath, overwrite=True) 328 | else: 329 | self.model.save(filepath, overwrite=True) 330 | else: 331 | if self.verbose > 0: 332 | print('\nEpoch %05d: %s did not improve' % 333 | (epoch + 1, self.monitor)) 334 | else: 335 | if self.verbose > 0: 336 | print('\nEpoch %05d: saving model to %s' % (epoch + 1, filepath)) 337 | if self.save_weights_only: 338 | self.model.save_weights(filepath, overwrite=True) 339 | else: 340 | self.model.save(filepath, overwrite=True) 341 | 342 | -------------------------------------------------------------------------------- /utils/dataloader.py: -------------------------------------------------------------------------------- 1 | import math 2 | from random import sample, shuffle 3 | 4 | import cv2 5 | import numpy as np 6 | from PIL import Image 7 | from tensorflow import keras 8 | 9 | from utils.utils import cvtColor, preprocess_input 10 | 11 | 12 | class YoloDatasets(keras.utils.Sequence): 13 | def __init__(self, annotation_lines, input_shape, anchors, batch_size, num_classes, anchors_mask, epoch_now, epoch_length, \ 14 | mosaic, mixup, mosaic_prob, mixup_prob, train, special_aug_ratio = 0.7): 15 | self.annotation_lines = annotation_lines 16 | self.length = len(self.annotation_lines) 17 | 18 | self.input_shape = input_shape 19 | self.anchors = anchors 20 | self.batch_size = batch_size 21 | self.num_classes = num_classes 22 | self.anchors_mask = anchors_mask 23 | self.epoch_now = epoch_now - 1 24 | self.epoch_length = epoch_length 25 | self.mosaic = mosaic 26 | self.mosaic_prob = mosaic_prob 27 | self.mixup = mixup 28 | self.mixup_prob = mixup_prob 29 | self.train = train 30 | self.special_aug_ratio = special_aug_ratio 31 | 32 | def __len__(self): 33 | return math.ceil(len(self.annotation_lines) / float(self.batch_size)) 34 | 35 | def __getitem__(self, index): 36 | image_data = [] 37 | box_data = [] 38 | for i in range(index * self.batch_size, (index + 1) * self.batch_size): 39 | i = i % self.length 40 | #---------------------------------------------------# 41 | # 训练时进行数据的随机增强 42 | # 验证时不进行数据的随机增强 43 | #---------------------------------------------------# 44 | if self.mosaic and self.rand() < self.mosaic_prob and self.epoch_now < self.epoch_length * self.special_aug_ratio: 45 | lines = sample(self.annotation_lines, 3) 46 | lines.append(self.annotation_lines[i]) 47 | shuffle(lines) 48 | image, box = self.get_random_data_with_Mosaic(lines, self.input_shape) 49 | 50 | if self.mixup and self.rand() < self.mixup_prob: 51 | lines = sample(self.annotation_lines, 1) 52 | image_2, box_2 = self.get_random_data(lines[0], self.input_shape, random = self.train) 53 | image, box = self.get_random_data_with_MixUp(image, box, image_2, box_2) 54 | else: 55 | image, box = self.get_random_data(self.annotation_lines[i], self.input_shape, random = self.train) 56 | image_data.append(preprocess_input(np.array(image, np.float32))) 57 | box_data.append(box) 58 | 59 | image_data = np.array(image_data) 60 | box_data = np.array(box_data) 61 | y_true = self.preprocess_true_boxes(box_data, self.input_shape, self.anchors, self.num_classes) 62 | return [image_data, *y_true], np.zeros(self.batch_size) 63 | 64 | def generate(self): 65 | i = 0 66 | while True: 67 | image_data = [] 68 | box_data = [] 69 | for b in range(self.batch_size): 70 | if i==0: 71 | np.random.shuffle(self.annotation_lines) 72 | #---------------------------------------------------# 73 | # 训练时进行数据的随机增强 74 | # 验证时不进行数据的随机增强 75 | #---------------------------------------------------# 76 | if self.mosaic and self.rand() < self.mosaic_prob and self.epoch_now < self.epoch_length * self.special_aug_ratio: 77 | lines = sample(self.annotation_lines, 3) 78 | lines.append(self.annotation_lines[i]) 79 | shuffle(lines) 80 | image, box = self.get_random_data_with_Mosaic(lines, self.input_shape) 81 | 82 | if self.mixup and self.rand() < self.mixup_prob: 83 | lines = sample(self.annotation_lines, 1) 84 | image_2, box_2 = self.get_random_data(lines[0], self.input_shape, random = self.train) 85 | image, box = self.get_random_data_with_MixUp(image, box, image_2, box_2) 86 | else: 87 | image, box = self.get_random_data(self.annotation_lines[i], self.input_shape, random = self.train) 88 | 89 | i = (i+1) % self.length 90 | image_data.append(preprocess_input(np.array(image, np.float32))) 91 | box_data.append(box) 92 | image_data = np.array(image_data) 93 | box_data = np.array(box_data) 94 | y_true = self.preprocess_true_boxes(box_data, self.input_shape, self.anchors, self.num_classes) 95 | yield image_data, y_true[0], y_true[1] 96 | 97 | def on_epoch_end(self): 98 | self.epoch_now += 1 99 | shuffle(self.annotation_lines) 100 | 101 | def rand(self, a=0, b=1): 102 | return np.random.rand()*(b-a) + a 103 | 104 | def get_random_data(self, annotation_line, input_shape, max_boxes=500, jitter=.3, hue=.1, sat=0.7, val=0.4, random=True): 105 | line = annotation_line.split() 106 | #------------------------------# 107 | # 读取图像并转换成RGB图像 108 | #------------------------------# 109 | image = Image.open(line[0]) 110 | image = cvtColor(image) 111 | #------------------------------# 112 | # 获得图像的高宽与目标高宽 113 | #------------------------------# 114 | iw, ih = image.size 115 | h, w = input_shape 116 | #------------------------------# 117 | # 获得预测框 118 | #------------------------------# 119 | box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) 120 | 121 | if not random: 122 | scale = min(w/iw, h/ih) 123 | nw = int(iw*scale) 124 | nh = int(ih*scale) 125 | dx = (w-nw)//2 126 | dy = (h-nh)//2 127 | 128 | #---------------------------------# 129 | # 将图像多余的部分加上灰条 130 | #---------------------------------# 131 | image = image.resize((nw,nh), Image.BICUBIC) 132 | new_image = Image.new('RGB', (w,h), (128,128,128)) 133 | new_image.paste(image, (dx, dy)) 134 | image_data = np.array(new_image, np.float32) 135 | 136 | #---------------------------------# 137 | # 对真实框进行调整 138 | #---------------------------------# 139 | box_data = np.zeros((max_boxes,5)) 140 | if len(box)>0: 141 | np.random.shuffle(box) 142 | box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx 143 | box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy 144 | box[:, 0:2][box[:, 0:2]<0] = 0 145 | box[:, 2][box[:, 2]>w] = w 146 | box[:, 3][box[:, 3]>h] = h 147 | box_w = box[:, 2] - box[:, 0] 148 | box_h = box[:, 3] - box[:, 1] 149 | box = box[np.logical_and(box_w>1, box_h>1)] 150 | if len(box)>max_boxes: box = box[:max_boxes] 151 | box_data[:len(box)] = box 152 | 153 | return image_data, box_data 154 | 155 | #------------------------------------------# 156 | # 对图像进行缩放并且进行长和宽的扭曲 157 | #------------------------------------------# 158 | new_ar = iw/ih * self.rand(1-jitter,1+jitter) / self.rand(1-jitter,1+jitter) 159 | scale = self.rand(.25, 2) 160 | if new_ar < 1: 161 | nh = int(scale*h) 162 | nw = int(nh*new_ar) 163 | else: 164 | nw = int(scale*w) 165 | nh = int(nw/new_ar) 166 | image = image.resize((nw,nh), Image.BICUBIC) 167 | 168 | #------------------------------------------# 169 | # 将图像多余的部分加上灰条 170 | #------------------------------------------# 171 | dx = int(self.rand(0, w-nw)) 172 | dy = int(self.rand(0, h-nh)) 173 | new_image = Image.new('RGB', (w,h), (128,128,128)) 174 | new_image.paste(image, (dx, dy)) 175 | image = new_image 176 | 177 | #------------------------------------------# 178 | # 翻转图像 179 | #------------------------------------------# 180 | flip = self.rand()<.5 181 | if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT) 182 | 183 | image_data = np.array(image, np.uint8) 184 | #---------------------------------# 185 | # 对图像进行色域变换 186 | # 计算色域变换的参数 187 | #---------------------------------# 188 | r = np.random.uniform(-1, 1, 3) * [hue, sat, val] + 1 189 | #---------------------------------# 190 | # 将图像转到HSV上 191 | #---------------------------------# 192 | hue, sat, val = cv2.split(cv2.cvtColor(image_data, cv2.COLOR_RGB2HSV)) 193 | dtype = image_data.dtype 194 | #---------------------------------# 195 | # 应用变换 196 | #---------------------------------# 197 | x = np.arange(0, 256, dtype=r.dtype) 198 | lut_hue = ((x * r[0]) % 180).astype(dtype) 199 | lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) 200 | lut_val = np.clip(x * r[2], 0, 255).astype(dtype) 201 | 202 | image_data = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) 203 | image_data = cv2.cvtColor(image_data, cv2.COLOR_HSV2RGB) 204 | 205 | #---------------------------------# 206 | # 对真实框进行调整 207 | #---------------------------------# 208 | box_data = np.zeros((max_boxes,5)) 209 | if len(box)>0: 210 | np.random.shuffle(box) 211 | box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx 212 | box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy 213 | if flip: box[:, [0,2]] = w - box[:, [2,0]] 214 | box[:, 0:2][box[:, 0:2]<0] = 0 215 | box[:, 2][box[:, 2]>w] = w 216 | box[:, 3][box[:, 3]>h] = h 217 | box_w = box[:, 2] - box[:, 0] 218 | box_h = box[:, 3] - box[:, 1] 219 | box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box 220 | if len(box)>max_boxes: box = box[:max_boxes] 221 | box_data[:len(box)] = box 222 | 223 | return image_data, box_data 224 | 225 | def merge_bboxes(self, bboxes, cutx, cuty): 226 | merge_bbox = [] 227 | for i in range(len(bboxes)): 228 | for box in bboxes[i]: 229 | tmp_box = [] 230 | x1, y1, x2, y2 = box[0], box[1], box[2], box[3] 231 | 232 | if i == 0: 233 | if y1 > cuty or x1 > cutx: 234 | continue 235 | if y2 >= cuty and y1 <= cuty: 236 | y2 = cuty 237 | if x2 >= cutx and x1 <= cutx: 238 | x2 = cutx 239 | 240 | if i == 1: 241 | if y2 < cuty or x1 > cutx: 242 | continue 243 | if y2 >= cuty and y1 <= cuty: 244 | y1 = cuty 245 | if x2 >= cutx and x1 <= cutx: 246 | x2 = cutx 247 | 248 | if i == 2: 249 | if y2 < cuty or x2 < cutx: 250 | continue 251 | if y2 >= cuty and y1 <= cuty: 252 | y1 = cuty 253 | if x2 >= cutx and x1 <= cutx: 254 | x1 = cutx 255 | 256 | if i == 3: 257 | if y1 > cuty or x2 < cutx: 258 | continue 259 | if y2 >= cuty and y1 <= cuty: 260 | y2 = cuty 261 | if x2 >= cutx and x1 <= cutx: 262 | x1 = cutx 263 | tmp_box.append(x1) 264 | tmp_box.append(y1) 265 | tmp_box.append(x2) 266 | tmp_box.append(y2) 267 | tmp_box.append(box[-1]) 268 | merge_bbox.append(tmp_box) 269 | return merge_bbox 270 | 271 | def get_random_data_with_Mosaic(self, annotation_line, input_shape, max_boxes=500, jitter=0.3, hue=.1, sat=0.7, val=0.4): 272 | h, w = input_shape 273 | min_offset_x = self.rand(0.3, 0.7) 274 | min_offset_y = self.rand(0.3, 0.7) 275 | 276 | image_datas = [] 277 | box_datas = [] 278 | index = 0 279 | for line in annotation_line: 280 | #---------------------------------# 281 | # 每一行进行分割 282 | #---------------------------------# 283 | line_content = line.split() 284 | #---------------------------------# 285 | # 打开图片 286 | #---------------------------------# 287 | image = Image.open(line_content[0]) 288 | image = cvtColor(image) 289 | 290 | #---------------------------------# 291 | # 图片的大小 292 | #---------------------------------# 293 | iw, ih = image.size 294 | #---------------------------------# 295 | # 保存框的位置 296 | #---------------------------------# 297 | box = np.array([np.array(list(map(int,box.split(',')))) for box in line_content[1:]]) 298 | 299 | #---------------------------------# 300 | # 是否翻转图片 301 | #---------------------------------# 302 | flip = self.rand()<.5 303 | if flip and len(box)>0: 304 | image = image.transpose(Image.FLIP_LEFT_RIGHT) 305 | box[:, [0,2]] = iw - box[:, [2,0]] 306 | 307 | #------------------------------------------# 308 | # 对图像进行缩放并且进行长和宽的扭曲 309 | #------------------------------------------# 310 | new_ar = iw/ih * self.rand(1-jitter,1+jitter) / self.rand(1-jitter,1+jitter) 311 | scale = self.rand(.4, 1) 312 | if new_ar < 1: 313 | nh = int(scale*h) 314 | nw = int(nh*new_ar) 315 | else: 316 | nw = int(scale*w) 317 | nh = int(nw/new_ar) 318 | image = image.resize((nw, nh), Image.BICUBIC) 319 | 320 | #-----------------------------------------------# 321 | # 将图片进行放置,分别对应四张分割图片的位置 322 | #-----------------------------------------------# 323 | if index == 0: 324 | dx = int(w*min_offset_x) - nw 325 | dy = int(h*min_offset_y) - nh 326 | elif index == 1: 327 | dx = int(w*min_offset_x) - nw 328 | dy = int(h*min_offset_y) 329 | elif index == 2: 330 | dx = int(w*min_offset_x) 331 | dy = int(h*min_offset_y) 332 | elif index == 3: 333 | dx = int(w*min_offset_x) 334 | dy = int(h*min_offset_y) - nh 335 | 336 | new_image = Image.new('RGB', (w,h), (128,128,128)) 337 | new_image.paste(image, (dx, dy)) 338 | image_data = np.array(new_image) 339 | 340 | index = index + 1 341 | box_data = [] 342 | #---------------------------------# 343 | # 对box进行重新处理 344 | #---------------------------------# 345 | if len(box)>0: 346 | np.random.shuffle(box) 347 | box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx 348 | box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy 349 | box[:, 0:2][box[:, 0:2]<0] = 0 350 | box[:, 2][box[:, 2]>w] = w 351 | box[:, 3][box[:, 3]>h] = h 352 | box_w = box[:, 2] - box[:, 0] 353 | box_h = box[:, 3] - box[:, 1] 354 | box = box[np.logical_and(box_w>1, box_h>1)] 355 | box_data = np.zeros((len(box),5)) 356 | box_data[:len(box)] = box 357 | 358 | image_datas.append(image_data) 359 | box_datas.append(box_data) 360 | 361 | #---------------------------------# 362 | # 将图片分割,放在一起 363 | #---------------------------------# 364 | cutx = int(w * min_offset_x) 365 | cuty = int(h * min_offset_y) 366 | 367 | new_image = np.zeros([h, w, 3]) 368 | new_image[:cuty, :cutx, :] = image_datas[0][:cuty, :cutx, :] 369 | new_image[cuty:, :cutx, :] = image_datas[1][cuty:, :cutx, :] 370 | new_image[cuty:, cutx:, :] = image_datas[2][cuty:, cutx:, :] 371 | new_image[:cuty, cutx:, :] = image_datas[3][:cuty, cutx:, :] 372 | 373 | new_image = np.array(new_image, np.uint8) 374 | #---------------------------------# 375 | # 对图像进行色域变换 376 | # 计算色域变换的参数 377 | #---------------------------------# 378 | r = np.random.uniform(-1, 1, 3) * [hue, sat, val] + 1 379 | #---------------------------------# 380 | # 将图像转到HSV上 381 | #---------------------------------# 382 | hue, sat, val = cv2.split(cv2.cvtColor(new_image, cv2.COLOR_RGB2HSV)) 383 | dtype = new_image.dtype 384 | #---------------------------------# 385 | # 应用变换 386 | #---------------------------------# 387 | x = np.arange(0, 256, dtype=r.dtype) 388 | lut_hue = ((x * r[0]) % 180).astype(dtype) 389 | lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) 390 | lut_val = np.clip(x * r[2], 0, 255).astype(dtype) 391 | 392 | new_image = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) 393 | new_image = cv2.cvtColor(new_image, cv2.COLOR_HSV2RGB) 394 | 395 | #---------------------------------# 396 | # 对框进行进一步的处理 397 | #---------------------------------# 398 | new_boxes = self.merge_bboxes(box_datas, cutx, cuty) 399 | 400 | #---------------------------------# 401 | # 将box进行调整 402 | #---------------------------------# 403 | box_data = np.zeros((max_boxes, 5)) 404 | if len(new_boxes)>0: 405 | if len(new_boxes)>max_boxes: new_boxes = new_boxes[:max_boxes] 406 | box_data[:len(new_boxes)] = new_boxes 407 | return new_image, box_data 408 | 409 | def get_random_data_with_MixUp(self, image_1, box_1, image_2, box_2, max_boxes=500): 410 | new_image = np.array(image_1, np.float32) * 0.5 + np.array(image_2, np.float32) * 0.5 411 | 412 | box_1_wh = box_1[:, 2:4] - box_1[:, 0:2] 413 | box_1_valid = box_1_wh[:, 0] > 0 414 | 415 | box_2_wh = box_2[:, 2:4] - box_2[:, 0:2] 416 | box_2_valid = box_2_wh[:, 0] > 0 417 | 418 | new_boxes = np.concatenate([box_1[box_1_valid, :], box_2[box_2_valid, :]], axis=0) 419 | #---------------------------------# 420 | # 将box进行调整 421 | #---------------------------------# 422 | box_data = np.zeros((max_boxes, 5)) 423 | if len(new_boxes)>0: 424 | if len(new_boxes)>max_boxes: new_boxes = new_boxes[:max_boxes] 425 | box_data[:len(new_boxes)] = new_boxes 426 | return new_image, box_data 427 | 428 | def preprocess_true_boxes(self, true_boxes, input_shape, anchors, num_classes): 429 | assert (true_boxes[..., 4] [1,9,2] 465 | #-----------------------------------------------------------# 466 | anchors = np.expand_dims(anchors, 0) 467 | anchor_maxes = anchors / 2. 468 | anchor_mins = -anchor_maxes 469 | 470 | #-----------------------------------------------------------# 471 | # 长宽要大于0才有效 472 | #-----------------------------------------------------------# 473 | valid_mask = boxes_wh[..., 0]>0 474 | 475 | for b in range(m): 476 | #-----------------------------------------------------------# 477 | # 对每一张图进行处理 478 | #-----------------------------------------------------------# 479 | wh = boxes_wh[b, valid_mask[b]] 480 | if len(wh) == 0: continue 481 | #-----------------------------------------------------------# 482 | # [n,2] -> [n,1,2] 483 | #-----------------------------------------------------------# 484 | wh = np.expand_dims(wh, -2) 485 | box_maxes = wh / 2. 486 | box_mins = - box_maxes 487 | 488 | #-----------------------------------------------------------# 489 | # 计算所有真实框和先验框的交并比 490 | # intersect_area [n,9] 491 | # box_area [n,1] 492 | # anchor_area [1,9] 493 | # iou [n,9] 494 | #-----------------------------------------------------------# 495 | intersect_mins = np.maximum(box_mins, anchor_mins) 496 | intersect_maxes = np.minimum(box_maxes, anchor_maxes) 497 | intersect_wh = np.maximum(intersect_maxes - intersect_mins, 0.) 498 | intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] 499 | 500 | box_area = wh[..., 0] * wh[..., 1] 501 | anchor_area = anchors[..., 0] * anchors[..., 1] 502 | 503 | iou = intersect_area / (box_area + anchor_area - intersect_area) 504 | #-----------------------------------------------------------# 505 | # 维度是[n,] 感谢 消尽不死鸟 的提醒 506 | #-----------------------------------------------------------# 507 | best_anchor = np.argmax(iou, axis=-1) 508 | sort_anchor = np.argsort(iou, axis=-1) 509 | 510 | def check_in_anchors_mask(index, anchors_mask): 511 | for sub_anchors_mask in anchors_mask: 512 | if index in sub_anchors_mask: 513 | return True 514 | return False 515 | 516 | for t, n in enumerate(best_anchor): 517 | #----------------------------------------# 518 | # 防止匹配到的先验框不在anchors_mask中 519 | #----------------------------------------# 520 | if not check_in_anchors_mask(n, self.anchors_mask): 521 | for index in sort_anchor[t][::-1]: 522 | if check_in_anchors_mask(index, self.anchors_mask): 523 | n = index 524 | break 525 | #-----------------------------------------------------------# 526 | # 找到每个真实框所属的特征层 527 | #-----------------------------------------------------------# 528 | for l in range(num_layers): 529 | if n in self.anchors_mask[l]: 530 | #-----------------------------------------------------------# 531 | # floor用于向下取整,找到真实框所属的特征层对应的x、y轴坐标 532 | #-----------------------------------------------------------# 533 | i = np.floor(true_boxes[b,t,0] * grid_shapes[l][1]).astype('int32') 534 | j = np.floor(true_boxes[b,t,1] * grid_shapes[l][0]).astype('int32') 535 | #-----------------------------------------------------------# 536 | # k指的的当前这个特征点的第k个先验框 537 | #-----------------------------------------------------------# 538 | k = self.anchors_mask[l].index(n) 539 | #-----------------------------------------------------------# 540 | # c指的是当前这个真实框的种类 541 | #-----------------------------------------------------------# 542 | c = true_boxes[b, t, 4].astype('int32') 543 | #-----------------------------------------------------------# 544 | # y_true的shape为(m,13,13,3,85)(m,26,26,3,85) 545 | # 最后的85可以拆分成4+1+80,4代表的是框的中心与宽高、 546 | # 1代表的是置信度、80代表的是种类 547 | #-----------------------------------------------------------# 548 | y_true[l][b, j, i, k, 0:4] = true_boxes[b, t, 0:4] 549 | y_true[l][b, j, i, k, 4] = 1 550 | y_true[l][b, j, i, k, 5+c] = 1 551 | 552 | return y_true 553 | -------------------------------------------------------------------------------- /utils/utils.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | 3 | import numpy as np 4 | from PIL import Image 5 | 6 | 7 | def compose(*funcs): 8 | if funcs: 9 | return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs) 10 | else: 11 | raise ValueError('Composition of empty sequence not supported.') 12 | 13 | #---------------------------------------------------------# 14 | # 将图像转换成RGB图像,防止灰度图在预测时报错。 15 | # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB 16 | #---------------------------------------------------------# 17 | def cvtColor(image): 18 | if len(np.shape(image)) == 3 and np.shape(image)[2] == 3: 19 | return image 20 | else: 21 | image = image.convert('RGB') 22 | return image 23 | 24 | #---------------------------------------------------# 25 | # 对输入图像进行resize 26 | #---------------------------------------------------# 27 | def resize_image(image, size, letterbox_image): 28 | iw, ih = image.size 29 | w, h = size 30 | if letterbox_image: 31 | scale = min(w/iw, h/ih) 32 | nw = int(iw*scale) 33 | nh = int(ih*scale) 34 | 35 | image = image.resize((nw,nh), Image.BICUBIC) 36 | new_image = Image.new('RGB', size, (128,128,128)) 37 | new_image.paste(image, ((w-nw)//2, (h-nh)//2)) 38 | else: 39 | new_image = image.resize((w, h), Image.BICUBIC) 40 | return new_image 41 | 42 | #---------------------------------------------------# 43 | # 获得类 44 | #---------------------------------------------------# 45 | def get_classes(classes_path): 46 | with open(classes_path, encoding='utf-8') as f: 47 | class_names = f.readlines() 48 | class_names = [c.strip() for c in class_names] 49 | return class_names, len(class_names) 50 | 51 | #---------------------------------------------------# 52 | # 获得先验框 53 | #---------------------------------------------------# 54 | def get_anchors(anchors_path): 55 | '''loads the anchors from a file''' 56 | with open(anchors_path, encoding='utf-8') as f: 57 | anchors = f.readline() 58 | anchors = [float(x) for x in anchors.split(',')] 59 | anchors = np.array(anchors).reshape(-1, 2) 60 | return anchors, len(anchors) 61 | 62 | def preprocess_input(image): 63 | image /= 255.0 64 | return image 65 | 66 | def show_config(**kwargs): 67 | print('Configurations:') 68 | print('-' * 70) 69 | print('|%25s | %40s|' % ('keys', 'values')) 70 | print('-' * 70) 71 | for key, value in kwargs.items(): 72 | print('|%25s | %40s|' % (str(key), str(value))) 73 | print('-' * 70) 74 | 75 | #-------------------------------------------------------------------------------------------------------------------------------# 76 | # From https://github.com/ckyrkou/Keras_FLOP_Estimator 77 | # Fix lots of bugs 78 | #-------------------------------------------------------------------------------------------------------------------------------# 79 | def net_flops(model, table=False, print_result=True): 80 | if (table == True): 81 | print("\n") 82 | print('%25s | %16s | %16s | %16s | %16s | %6s | %6s' % ( 83 | 'Layer Name', 'Input Shape', 'Output Shape', 'Kernel Size', 'Filters', 'Strides', 'FLOPS')) 84 | print('=' * 120) 85 | 86 | #---------------------------------------------------# 87 | # 总的FLOPs 88 | #---------------------------------------------------# 89 | t_flops = 0 90 | factor = 1e9 91 | 92 | for l in model.layers: 93 | try: 94 | #--------------------------------------# 95 | # 所需参数的初始化定义 96 | #--------------------------------------# 97 | o_shape, i_shape, strides, ks, filters = ('', '', ''), ('', '', ''), (1, 1), (0, 0), 0 98 | flops = 0 99 | #--------------------------------------# 100 | # 获得层的名字 101 | #--------------------------------------# 102 | name = l.name 103 | 104 | if ('InputLayer' in str(l)): 105 | i_shape = l.get_input_shape_at(0)[1:4] 106 | o_shape = l.get_output_shape_at(0)[1:4] 107 | 108 | #--------------------------------------# 109 | # Reshape层 110 | #--------------------------------------# 111 | elif ('Reshape' in str(l)): 112 | i_shape = l.get_input_shape_at(0)[1:4] 113 | o_shape = l.get_output_shape_at(0)[1:4] 114 | 115 | #--------------------------------------# 116 | # 填充层 117 | #--------------------------------------# 118 | elif ('Padding' in str(l)): 119 | i_shape = l.get_input_shape_at(0)[1:4] 120 | o_shape = l.get_output_shape_at(0)[1:4] 121 | 122 | #--------------------------------------# 123 | # 平铺层 124 | #--------------------------------------# 125 | elif ('Flatten' in str(l)): 126 | i_shape = l.get_input_shape_at(0)[1:4] 127 | o_shape = l.get_output_shape_at(0)[1:4] 128 | 129 | #--------------------------------------# 130 | # 激活函数层 131 | #--------------------------------------# 132 | elif 'Activation' in str(l): 133 | i_shape = l.get_input_shape_at(0)[1:4] 134 | o_shape = l.get_output_shape_at(0)[1:4] 135 | 136 | #--------------------------------------# 137 | # LeakyReLU 138 | #--------------------------------------# 139 | elif 'LeakyReLU' in str(l): 140 | for i in range(len(l._inbound_nodes)): 141 | i_shape = l.get_input_shape_at(i)[1:4] 142 | o_shape = l.get_output_shape_at(i)[1:4] 143 | 144 | flops += i_shape[0] * i_shape[1] * i_shape[2] 145 | 146 | #--------------------------------------# 147 | # 池化层 148 | #--------------------------------------# 149 | elif 'MaxPooling' in str(l): 150 | i_shape = l.get_input_shape_at(0)[1:4] 151 | o_shape = l.get_output_shape_at(0)[1:4] 152 | 153 | #--------------------------------------# 154 | # 池化层 155 | #--------------------------------------# 156 | elif ('AveragePooling' in str(l) and 'Global' not in str(l)): 157 | strides = l.strides 158 | ks = l.pool_size 159 | 160 | for i in range(len(l._inbound_nodes)): 161 | i_shape = l.get_input_shape_at(i)[1:4] 162 | o_shape = l.get_output_shape_at(i)[1:4] 163 | 164 | flops += o_shape[0] * o_shape[1] * o_shape[2] 165 | 166 | #--------------------------------------# 167 | # 全局池化层 168 | #--------------------------------------# 169 | elif ('AveragePooling' in str(l) and 'Global' in str(l)): 170 | for i in range(len(l._inbound_nodes)): 171 | i_shape = l.get_input_shape_at(i)[1:4] 172 | o_shape = l.get_output_shape_at(i)[1:4] 173 | 174 | flops += (i_shape[0] * i_shape[1] + 1) * i_shape[2] 175 | 176 | #--------------------------------------# 177 | # 标准化层 178 | #--------------------------------------# 179 | elif ('BatchNormalization' in str(l)): 180 | for i in range(len(l._inbound_nodes)): 181 | i_shape = l.get_input_shape_at(i)[1:4] 182 | o_shape = l.get_output_shape_at(i)[1:4] 183 | 184 | temp_flops = 1 185 | for i in range(len(i_shape)): 186 | temp_flops *= i_shape[i] 187 | temp_flops *= 2 188 | 189 | flops += temp_flops 190 | 191 | #--------------------------------------# 192 | # 全连接层 193 | #--------------------------------------# 194 | elif ('Dense' in str(l)): 195 | for i in range(len(l._inbound_nodes)): 196 | i_shape = l.get_input_shape_at(i)[1:4] 197 | o_shape = l.get_output_shape_at(i)[1:4] 198 | 199 | temp_flops = 1 200 | for i in range(len(o_shape)): 201 | temp_flops *= o_shape[i] 202 | 203 | if (i_shape[-1] == None): 204 | temp_flops = temp_flops * o_shape[-1] 205 | else: 206 | temp_flops = temp_flops * i_shape[-1] 207 | flops += temp_flops 208 | 209 | #--------------------------------------# 210 | # 普通卷积层 211 | #--------------------------------------# 212 | elif ('Conv2D' in str(l) and 'DepthwiseConv2D' not in str(l) and 'SeparableConv2D' not in str(l)): 213 | strides = l.strides 214 | ks = l.kernel_size 215 | filters = l.filters 216 | bias = 1 if l.use_bias else 0 217 | 218 | for i in range(len(l._inbound_nodes)): 219 | i_shape = l.get_input_shape_at(i)[1:4] 220 | o_shape = l.get_output_shape_at(i)[1:4] 221 | 222 | if (filters == None): 223 | filters = i_shape[2] 224 | flops += filters * o_shape[0] * o_shape[1] * (ks[0] * ks[1] * i_shape[2] + bias) 225 | 226 | #--------------------------------------# 227 | # 逐层卷积层 228 | #--------------------------------------# 229 | elif ('Conv2D' in str(l) and 'DepthwiseConv2D' in str(l) and 'SeparableConv2D' not in str(l)): 230 | strides = l.strides 231 | ks = l.kernel_size 232 | filters = l.filters 233 | bias = 1 if l.use_bias else 0 234 | 235 | for i in range(len(l._inbound_nodes)): 236 | i_shape = l.get_input_shape_at(i)[1:4] 237 | o_shape = l.get_output_shape_at(i)[1:4] 238 | 239 | if (filters == None): 240 | filters = i_shape[2] 241 | flops += filters * o_shape[0] * o_shape[1] * (ks[0] * ks[1] + bias) 242 | 243 | #--------------------------------------# 244 | # 深度可分离卷积层 245 | #--------------------------------------# 246 | elif ('Conv2D' in str(l) and 'DepthwiseConv2D' not in str(l) and 'SeparableConv2D' in str(l)): 247 | strides = l.strides 248 | ks = l.kernel_size 249 | filters = l.filters 250 | 251 | for i in range(len(l._inbound_nodes)): 252 | i_shape = l.get_input_shape_at(i)[1:4] 253 | o_shape = l.get_output_shape_at(i)[1:4] 254 | 255 | if (filters == None): 256 | filters = i_shape[2] 257 | flops += i_shape[2] * o_shape[0] * o_shape[1] * (ks[0] * ks[1] + bias) + \ 258 | filters * o_shape[0] * o_shape[1] * (1 * 1 * i_shape[2] + bias) 259 | #--------------------------------------# 260 | # 模型中有模型时 261 | #--------------------------------------# 262 | elif 'Model' in str(l): 263 | flops = net_flops(l, print_result=False) 264 | 265 | t_flops += flops 266 | 267 | if (table == True): 268 | print('%25s | %16s | %16s | %16s | %16s | %6s | %5.4f' % ( 269 | name[:25], str(i_shape), str(o_shape), str(ks), str(filters), str(strides), flops)) 270 | 271 | except: 272 | pass 273 | 274 | t_flops = t_flops * 2 275 | if print_result: 276 | show_flops = t_flops / factor 277 | print('Total GFLOPs: %.3fG' % (show_flops)) 278 | return t_flops -------------------------------------------------------------------------------- /utils/utils_bbox.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | from tensorflow.keras import backend as K 4 | 5 | 6 | #---------------------------------------------------# 7 | # 对box进行调整,使其符合真实图片的样子 8 | #---------------------------------------------------# 9 | def yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image): 10 | #-----------------------------------------------------------------# 11 | # 把y轴放前面是因为方便预测框和图像的宽高进行相乘 12 | #-----------------------------------------------------------------# 13 | box_yx = box_xy[..., ::-1] 14 | box_hw = box_wh[..., ::-1] 15 | input_shape = K.cast(input_shape, K.dtype(box_yx)) 16 | image_shape = K.cast(image_shape, K.dtype(box_yx)) 17 | 18 | if letterbox_image: 19 | #-----------------------------------------------------------------# 20 | # 这里求出来的offset是图像有效区域相对于图像左上角的偏移情况 21 | # new_shape指的是宽高缩放情况 22 | #-----------------------------------------------------------------# 23 | new_shape = K.round(image_shape * K.min(input_shape/image_shape)) 24 | offset = (input_shape - new_shape)/2./input_shape 25 | scale = input_shape/new_shape 26 | 27 | box_yx = (box_yx - offset) * scale 28 | box_hw *= scale 29 | 30 | box_mins = box_yx - (box_hw / 2.) 31 | box_maxes = box_yx + (box_hw / 2.) 32 | boxes = K.concatenate([box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2]]) 33 | boxes *= K.concatenate([image_shape, image_shape]) 34 | return boxes 35 | 36 | #---------------------------------------------------# 37 | # 将预测值的每个特征层调成真实值 38 | #---------------------------------------------------# 39 | def get_anchors_and_decode(feats, anchors, num_classes, input_shape, calc_loss=False): 40 | num_anchors = len(anchors) 41 | #------------------------------------------# 42 | # grid_shape指的是特征层的高和宽 43 | #------------------------------------------# 44 | grid_shape = K.shape(feats)[1:3] 45 | #--------------------------------------------------------------------# 46 | # 获得各个特征点的坐标信息。生成的shape为(13, 13, num_anchors, 2) 47 | #--------------------------------------------------------------------# 48 | grid_x = K.tile(K.reshape(K.arange(0, stop=grid_shape[1]), [1, -1, 1, 1]), [grid_shape[0], 1, num_anchors, 1]) 49 | grid_y = K.tile(K.reshape(K.arange(0, stop=grid_shape[0]), [-1, 1, 1, 1]), [1, grid_shape[1], num_anchors, 1]) 50 | grid = K.cast(K.concatenate([grid_x, grid_y]), K.dtype(feats)) 51 | #---------------------------------------------------------------# 52 | # 将先验框进行拓展,生成的shape为(13, 13, num_anchors, 2) 53 | #---------------------------------------------------------------# 54 | anchors_tensor = K.reshape(K.constant(anchors), [1, 1, num_anchors, 2]) 55 | anchors_tensor = K.tile(anchors_tensor, [grid_shape[0], grid_shape[1], 1, 1]) 56 | 57 | #---------------------------------------------------# 58 | # 将预测结果调整成(batch_size,13,13,3,85) 59 | # 85可拆分成4 + 1 + 80 60 | # 4代表的是中心宽高的调整参数 61 | # 1代表的是框的置信度 62 | # 80代表的是种类的置信度 63 | #---------------------------------------------------# 64 | feats = K.reshape(feats, [-1, grid_shape[0], grid_shape[1], num_anchors, num_classes + 5]) 65 | #------------------------------------------# 66 | # 对先验框进行解码,并进行归一化 67 | #------------------------------------------# 68 | box_xy = (K.sigmoid(feats[..., :2]) + grid) / K.cast(grid_shape[::-1], K.dtype(feats)) 69 | box_wh = K.exp(feats[..., 2:4]) * anchors_tensor / K.cast(input_shape[::-1], K.dtype(feats)) 70 | #------------------------------------------# 71 | # 获得预测框的置信度 72 | #------------------------------------------# 73 | box_confidence = K.sigmoid(feats[..., 4:5]) 74 | box_class_probs = K.sigmoid(feats[..., 5:]) 75 | 76 | #---------------------------------------------------------------------# 77 | # 在计算loss的时候返回grid, feats, box_xy, box_wh 78 | # 在预测的时候返回box_xy, box_wh, box_confidence, box_class_probs 79 | #---------------------------------------------------------------------# 80 | if calc_loss == True: 81 | return grid, feats, box_xy, box_wh 82 | return box_xy, box_wh, box_confidence, box_class_probs 83 | 84 | #---------------------------------------------------# 85 | # 图片预测 86 | #---------------------------------------------------# 87 | def DecodeBox(outputs, 88 | anchors, 89 | num_classes, 90 | input_shape, 91 | #-----------------------------------------------------------# 92 | # 13x13的特征层对应的anchor是[81,82],[135,169],[344,319] 93 | # 26x26的特征层对应的anchor是[10,14],[23,27],[37,58] 94 | #-----------------------------------------------------------# 95 | anchor_mask = [[3, 4, 5], [1, 2, 3]], 96 | max_boxes = 100, 97 | confidence = 0.5, 98 | nms_iou = 0.3, 99 | letterbox_image = True): 100 | 101 | image_shape = K.reshape(outputs[-1],[-1]) 102 | 103 | box_xy = [] 104 | box_wh = [] 105 | box_confidence = [] 106 | box_class_probs = [] 107 | for i in range(len(anchor_mask)): 108 | sub_box_xy, sub_box_wh, sub_box_confidence, sub_box_class_probs = \ 109 | get_anchors_and_decode(outputs[i], anchors[anchor_mask[i]], num_classes, input_shape) 110 | box_xy.append(K.reshape(sub_box_xy, [-1, 2])) 111 | box_wh.append(K.reshape(sub_box_wh, [-1, 2])) 112 | box_confidence.append(K.reshape(sub_box_confidence, [-1, 1])) 113 | box_class_probs.append(K.reshape(sub_box_class_probs, [-1, num_classes])) 114 | box_xy = K.concatenate(box_xy, axis = 0) 115 | box_wh = K.concatenate(box_wh, axis = 0) 116 | box_confidence = K.concatenate(box_confidence, axis = 0) 117 | box_class_probs = K.concatenate(box_class_probs, axis = 0) 118 | 119 | #------------------------------------------------------------------------------------------------------------# 120 | # 在图像传入网络预测前会进行letterbox_image给图像周围添加灰条,因此生成的box_xy, box_wh是相对于有灰条的图像的 121 | # 我们需要对其进行修改,去除灰条的部分。 将box_xy、和box_wh调节成y_min,y_max,xmin,xmax 122 | # 如果没有使用letterbox_image也需要将归一化后的box_xy, box_wh调整成相对于原图大小的 123 | #------------------------------------------------------------------------------------------------------------# 124 | boxes = yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image) 125 | 126 | box_scores = box_confidence * box_class_probs 127 | 128 | #-----------------------------------------------------------# 129 | # 判断得分是否大于score_threshold 130 | #-----------------------------------------------------------# 131 | mask = box_scores >= confidence 132 | max_boxes_tensor = K.constant(max_boxes, dtype='int32') 133 | boxes_out = [] 134 | scores_out = [] 135 | classes_out = [] 136 | for c in range(num_classes): 137 | #-----------------------------------------------------------# 138 | # 取出所有box_scores >= score_threshold的框,和成绩 139 | #-----------------------------------------------------------# 140 | class_boxes = tf.boolean_mask(boxes, mask[:, c]) 141 | class_box_scores = tf.boolean_mask(box_scores[:, c], mask[:, c]) 142 | 143 | #-----------------------------------------------------------# 144 | # 非极大抑制 145 | # 保留一定区域内得分最大的框 146 | #-----------------------------------------------------------# 147 | nms_index = tf.image.non_max_suppression(class_boxes, class_box_scores, max_boxes_tensor, iou_threshold=nms_iou) 148 | 149 | #-----------------------------------------------------------# 150 | # 获取非极大抑制后的结果 151 | # 下列三个分别是:框的位置,得分与种类 152 | #-----------------------------------------------------------# 153 | class_boxes = K.gather(class_boxes, nms_index) 154 | class_box_scores = K.gather(class_box_scores, nms_index) 155 | classes = K.ones_like(class_box_scores, 'int32') * c 156 | 157 | boxes_out.append(class_boxes) 158 | scores_out.append(class_box_scores) 159 | classes_out.append(classes) 160 | boxes_out = K.concatenate(boxes_out, axis=0) 161 | scores_out = K.concatenate(scores_out, axis=0) 162 | classes_out = K.concatenate(classes_out, axis=0) 163 | 164 | return boxes_out, scores_out, classes_out 165 | 166 | 167 | class DecodeBoxNP(): 168 | def __init__(self, anchors, num_classes, input_shape, anchors_mask = [[6,7,8], [3,4,5], [0,1,2]]): 169 | super(DecodeBoxNP, self).__init__() 170 | self.anchors = anchors 171 | self.num_classes = num_classes 172 | self.bbox_attrs = 5 + num_classes 173 | self.input_shape = input_shape 174 | self.anchors_mask = anchors_mask 175 | 176 | def sigmoid(self, x): 177 | return 1 / (1 + np.exp(-x)) 178 | 179 | def decode_box(self, inputs): 180 | outputs = [] 181 | for i, input in enumerate(inputs): 182 | batch_size = np.shape(input)[0] 183 | input_height = np.shape(input)[2] 184 | input_width = np.shape(input)[3] 185 | 186 | #-----------------------------------------------# 187 | # 输入为640x640时 188 | # stride_h = stride_w = 32、16、8 189 | #-----------------------------------------------# 190 | stride_h = self.input_shape[0] / input_height 191 | stride_w = self.input_shape[1] / input_width 192 | #-------------------------------------------------# 193 | # 此时获得的scaled_anchors大小是相对于特征层的 194 | #-------------------------------------------------# 195 | scaled_anchors = [(anchor_width / stride_w, anchor_height / stride_h) for anchor_width, anchor_height in self.anchors[self.anchors_mask[i]]] 196 | 197 | #-----------------------------------------------# 198 | # 输入的input一共有三个,他们的shape分别是 199 | # batch_size, 3, 20, 20, 85 200 | # batch_size, 3, 40, 40, 85 201 | # batch_size, 3, 80, 80, 85 202 | #-----------------------------------------------# 203 | prediction = np.transpose(np.reshape(input, (batch_size, len(self.anchors_mask[i]), self.bbox_attrs, input_height, input_width)), (0, 1, 3, 4, 2)) 204 | 205 | #-----------------------------------------------# 206 | # 先验框的中心位置的调整参数 207 | #-----------------------------------------------# 208 | x = self.sigmoid(prediction[..., 0]) 209 | y = self.sigmoid(prediction[..., 1]) 210 | #-----------------------------------------------# 211 | # 先验框的宽高调整参数 212 | #-----------------------------------------------# 213 | w = prediction[..., 2] 214 | h = prediction[..., 3] 215 | #-----------------------------------------------# 216 | # 获得置信度,是否有物体 217 | #-----------------------------------------------# 218 | conf = self.sigmoid(prediction[..., 4]) 219 | #-----------------------------------------------# 220 | # 种类置信度 221 | #-----------------------------------------------# 222 | pred_cls = self.sigmoid(prediction[..., 5:]) 223 | 224 | #----------------------------------------------------------# 225 | # 生成网格,先验框中心,网格左上角 226 | # batch_size,3,20,20 227 | #----------------------------------------------------------# 228 | grid_x = np.repeat(np.expand_dims(np.repeat(np.expand_dims(np.linspace(0, input_width - 1, input_width), 0), input_height, axis=0), 0), batch_size * len(self.anchors_mask[i]), axis=0) 229 | grid_x = np.reshape(grid_x, np.shape(x)) 230 | grid_y = np.repeat(np.expand_dims(np.repeat(np.expand_dims(np.linspace(0, input_height - 1, input_height), 0), input_width, axis=0).T, 0), batch_size * len(self.anchors_mask[i]), axis=0) 231 | grid_y = np.reshape(grid_y, np.shape(y)) 232 | 233 | #----------------------------------------------------------# 234 | # 按照网格格式生成先验框的宽高 235 | # batch_size,3,20,20 236 | #----------------------------------------------------------# 237 | anchor_w = np.repeat(np.expand_dims(np.repeat(np.expand_dims(np.array(scaled_anchors)[:, 0], 0), batch_size, axis=0), -1), input_height * input_width, axis=-1) 238 | anchor_h = np.repeat(np.expand_dims(np.repeat(np.expand_dims(np.array(scaled_anchors)[:, 1], 0), batch_size, axis=0), -1), input_height * input_width, axis=-1) 239 | anchor_w = np.reshape(anchor_w, np.shape(w)) 240 | anchor_h = np.reshape(anchor_h, np.shape(h)) 241 | #----------------------------------------------------------# 242 | # 利用预测结果对先验框进行调整 243 | # 首先调整先验框的中心,从先验框中心向右下角偏移 244 | # 再调整先验框的宽高。 245 | # x 0 ~ 1 => 0 ~ 2 => -0.5, 1.5 => 负责一定范围的目标的预测 246 | # y 0 ~ 1 => 0 ~ 2 => -0.5, 1.5 => 负责一定范围的目标的预测 247 | # w 0 ~ 1 => 0 ~ 2 => 0 ~ 4 => 先验框的宽高调节范围为0~4倍 248 | # h 0 ~ 1 => 0 ~ 2 => 0 ~ 4 => 先验框的宽高调节范围为0~4倍 249 | #----------------------------------------------------------# 250 | pred_boxes = np.zeros(np.shape(prediction[..., :4])) 251 | pred_boxes[..., 0] = x + grid_x 252 | pred_boxes[..., 1] = y + grid_y 253 | pred_boxes[..., 2] = np.exp(w) * anchor_w 254 | pred_boxes[..., 3] = np.exp(h) * anchor_h 255 | 256 | #----------------------------------------------------------# 257 | # 将输出结果归一化成小数的形式 258 | #----------------------------------------------------------# 259 | _scale = np.array([input_width, input_height, input_width, input_height]) 260 | output = np.concatenate([np.reshape(pred_boxes, (batch_size, -1, 4)) / _scale, 261 | np.reshape(conf, (batch_size, -1, 1)), np.reshape(pred_cls, (batch_size, -1, self.num_classes))], -1) 262 | outputs.append(output) 263 | return outputs 264 | 265 | def bbox_iou(self, box1, box2, x1y1x2y2=True): 266 | """ 267 | 计算IOU 268 | """ 269 | if not x1y1x2y2: 270 | b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2 271 | b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2 272 | b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2 273 | b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2 274 | else: 275 | b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3] 276 | b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3] 277 | 278 | inter_rect_x1 = np.maximum(b1_x1, b2_x1) 279 | inter_rect_y1 = np.maximum(b1_y1, b2_y1) 280 | inter_rect_x2 = np.minimum(b1_x2, b2_x2) 281 | inter_rect_y2 = np.minimum(b1_y2, b2_y2) 282 | 283 | inter_area = np.maximum(inter_rect_x2 - inter_rect_x1, 0) * \ 284 | np.maximum(inter_rect_y2 - inter_rect_y1, 0) 285 | 286 | b1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1) 287 | b2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) 288 | 289 | iou = inter_area / np.maximum(b1_area + b2_area - inter_area, 1e-6) 290 | 291 | return iou 292 | 293 | def yolo_correct_boxes(self, box_xy, box_wh, input_shape, image_shape, letterbox_image): 294 | #-----------------------------------------------------------------# 295 | # 把y轴放前面是因为方便预测框和图像的宽高进行相乘 296 | #-----------------------------------------------------------------# 297 | box_yx = box_xy[..., ::-1] 298 | box_hw = box_wh[..., ::-1] 299 | input_shape = np.array(input_shape) 300 | image_shape = np.array(image_shape) 301 | 302 | if letterbox_image: 303 | #-----------------------------------------------------------------# 304 | # 这里求出来的offset是图像有效区域相对于图像左上角的偏移情况 305 | # new_shape指的是宽高缩放情况 306 | #-----------------------------------------------------------------# 307 | new_shape = np.round(image_shape * np.min(input_shape/image_shape)) 308 | offset = (input_shape - new_shape)/2./input_shape 309 | scale = input_shape/new_shape 310 | 311 | box_yx = (box_yx - offset) * scale 312 | box_hw *= scale 313 | 314 | box_mins = box_yx - (box_hw / 2.) 315 | box_maxes = box_yx + (box_hw / 2.) 316 | boxes = np.concatenate([box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2]], axis=-1) 317 | boxes *= np.concatenate([image_shape, image_shape], axis=-1) 318 | return boxes 319 | 320 | def non_max_suppression(self, prediction, num_classes, input_shape, image_shape, letterbox_image, conf_thres=0.5, nms_thres=0.4): 321 | #----------------------------------------------------------# 322 | # 将预测结果的格式转换成左上角右下角的格式。 323 | # prediction [batch_size, num_anchors, 85] 324 | #----------------------------------------------------------# 325 | box_corner = np.zeros_like(prediction) 326 | box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2 327 | box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2 328 | box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2 329 | box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2 330 | prediction[:, :, :4] = box_corner[:, :, :4] 331 | 332 | output = [None for _ in range(len(prediction))] 333 | for i, image_pred in enumerate(prediction): 334 | #----------------------------------------------------------# 335 | # 对种类预测部分取max。 336 | # class_conf [num_anchors, 1] 种类置信度 337 | # class_pred [num_anchors, 1] 种类 338 | #----------------------------------------------------------# 339 | class_conf = np.max(image_pred[:, 5:5 + num_classes], 1, keepdims=True) 340 | class_pred = np.expand_dims(np.argmax(image_pred[:, 5:5 + num_classes], 1), -1) 341 | 342 | #----------------------------------------------------------# 343 | # 利用置信度进行第一轮筛选 344 | #----------------------------------------------------------# 345 | conf_mask = np.squeeze((image_pred[:, 4] * class_conf[:, 0] >= conf_thres)) 346 | 347 | #----------------------------------------------------------# 348 | # 根据置信度进行预测结果的筛选 349 | #----------------------------------------------------------# 350 | image_pred = image_pred[conf_mask] 351 | class_conf = class_conf[conf_mask] 352 | class_pred = class_pred[conf_mask] 353 | if not np.shape(image_pred)[0]: 354 | continue 355 | #-------------------------------------------------------------------------# 356 | # detections [num_anchors, 7] 357 | # 7的内容为:x1, y1, x2, y2, obj_conf, class_conf, class_pred 358 | #-------------------------------------------------------------------------# 359 | detections = np.concatenate((image_pred[:, :5], class_conf, class_pred), 1) 360 | 361 | #------------------------------------------# 362 | # 获得预测结果中包含的所有种类 363 | #------------------------------------------# 364 | unique_labels = np.unique(detections[:, -1]) 365 | 366 | for c in unique_labels: 367 | #------------------------------------------# 368 | # 获得某一类得分筛选后全部的预测结果 369 | #------------------------------------------# 370 | detections_class = detections[detections[:, -1] == c] 371 | 372 | # 按照存在物体的置信度排序 373 | conf_sort_index = np.argsort(detections_class[:, 4] * detections_class[:, 5])[::-1] 374 | detections_class = detections_class[conf_sort_index] 375 | # 进行非极大抑制 376 | max_detections = [] 377 | while np.shape(detections_class)[0]: 378 | # 取出这一类置信度最高的,一步一步往下判断,判断重合程度是否大于nms_thres,如果是则去除掉 379 | max_detections.append(detections_class[0:1]) 380 | if len(detections_class) == 1: 381 | break 382 | ious = self.bbox_iou(max_detections[-1], detections_class[1:]) 383 | detections_class = detections_class[1:][ious < nms_thres] 384 | # 堆叠 385 | max_detections = np.concatenate(max_detections, 0) 386 | 387 | # Add max detections to outputs 388 | output[i] = max_detections if output[i] is None else np.concatenate((output[i], max_detections)) 389 | 390 | if output[i] is not None: 391 | output[i] = output[i] 392 | box_xy, box_wh = (output[i][:, 0:2] + output[i][:, 2:4])/2, output[i][:, 2:4] - output[i][:, 0:2] 393 | output[i][:, :4] = self.yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image) 394 | return output 395 | -------------------------------------------------------------------------------- /utils/utils_fit.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import tensorflow as tf 4 | from nets.yolo import yolo_loss 5 | from tqdm import tqdm 6 | 7 | 8 | #------------------------------# 9 | # 防止bug 10 | #------------------------------# 11 | def get_train_step_fn(input_shape, anchors, anchors_mask, num_classes, label_smoothing, strategy): 12 | @tf.function 13 | def train_step(imgs, targets, net, optimizer): 14 | with tf.GradientTape() as tape: 15 | #------------------------------# 16 | # 计算loss 17 | #------------------------------# 18 | P5_output, P4_output = net(imgs, training=True) 19 | args = [P5_output, P4_output] + targets 20 | loss_value = yolo_loss( 21 | args, input_shape, anchors, anchors_mask, num_classes, 22 | label_smoothing = label_smoothing, 23 | balance = [0.4, 1.0, 4], 24 | box_ratio = 0.05, 25 | obj_ratio = 5 * (input_shape[0] * input_shape[1]) / (416 ** 2), 26 | cls_ratio = 1 * (num_classes / 80) 27 | ) 28 | #------------------------------# 29 | # 添加上l2正则化参数 30 | #------------------------------# 31 | loss_value = tf.reduce_sum(net.losses) + loss_value 32 | grads = tape.gradient(loss_value, net.trainable_variables) 33 | optimizer.apply_gradients(zip(grads, net.trainable_variables)) 34 | return loss_value 35 | 36 | if strategy == None: 37 | return train_step 38 | else: 39 | #----------------------# 40 | # 多gpu训练 41 | #----------------------# 42 | @tf.function 43 | def distributed_train_step(images, targets, net, optimizer): 44 | per_replica_losses = strategy.run(train_step, args=(images, targets, net, optimizer,)) 45 | return strategy.reduce(tf.distribute.ReduceOp.MEAN, per_replica_losses, 46 | axis=None) 47 | return distributed_train_step 48 | 49 | #----------------------# 50 | # 防止bug 51 | #----------------------# 52 | def get_val_step_fn(input_shape, anchors, anchors_mask, num_classes, label_smoothing, strategy): 53 | @tf.function 54 | def val_step(imgs, targets, net, optimizer): 55 | #------------------------------# 56 | # 计算loss 57 | #------------------------------# 58 | P5_output, P4_output = net(imgs, training=True) 59 | args = [P5_output, P4_output] + targets 60 | loss_value = yolo_loss( 61 | args, input_shape, anchors, anchors_mask, num_classes, 62 | label_smoothing = label_smoothing, 63 | balance = [0.4, 1.0, 4], 64 | box_ratio = 0.05, 65 | obj_ratio = 5 * (input_shape[0] * input_shape[1]) / (416 ** 2), 66 | cls_ratio = 1 * (num_classes / 80) 67 | ) 68 | #------------------------------# 69 | # 添加上l2正则化参数 70 | #------------------------------# 71 | loss_value = tf.reduce_sum(net.losses) + loss_value 72 | return loss_value 73 | if strategy == None: 74 | return val_step 75 | else: 76 | #----------------------# 77 | # 多gpu验证 78 | #----------------------# 79 | @tf.function 80 | def distributed_val_step(images, targets, net, optimizer): 81 | per_replica_losses = strategy.run(val_step, args=(images, targets, net, optimizer,)) 82 | return strategy.reduce(tf.distribute.ReduceOp.MEAN, per_replica_losses, 83 | axis=None) 84 | return distributed_val_step 85 | 86 | def fit_one_epoch(net, loss_history, eval_callback, optimizer, epoch, epoch_step, epoch_step_val, gen, gen_val, Epoch, 87 | input_shape, anchors, anchors_mask, num_classes, label_smoothing, save_period, save_dir, strategy): 88 | train_step = get_train_step_fn(input_shape, anchors, anchors_mask, num_classes, label_smoothing, strategy) 89 | val_step = get_val_step_fn(input_shape, anchors, anchors_mask, num_classes, label_smoothing, strategy) 90 | 91 | loss = 0 92 | val_loss = 0 93 | print('Start Train') 94 | with tqdm(total=epoch_step,desc=f'Epoch {epoch + 1}/{Epoch}',postfix=dict,mininterval=0.3) as pbar: 95 | for iteration, batch in enumerate(gen): 96 | if iteration >= epoch_step: 97 | break 98 | images, target0, target1 = batch[0], batch[1], batch[2] 99 | targets = [target0, target1] 100 | loss_value = train_step(images, targets, net, optimizer) 101 | loss = loss + loss_value 102 | 103 | pbar.set_postfix(**{'total_loss': float(loss) / (iteration + 1), 104 | 'lr' : optimizer.lr.numpy()}) 105 | pbar.update(1) 106 | print('Finish Train') 107 | 108 | print('Start Validation') 109 | with tqdm(total=epoch_step_val, desc=f'Epoch {epoch + 1}/{Epoch}',postfix=dict,mininterval=0.3) as pbar: 110 | for iteration, batch in enumerate(gen_val): 111 | if iteration >= epoch_step_val: 112 | break 113 | images, target0, target1 = batch[0], batch[1], batch[2] 114 | targets = [target0, target1] 115 | loss_value = val_step(images, targets, net, optimizer) 116 | val_loss = val_loss + loss_value 117 | 118 | pbar.set_postfix(**{'total_loss': float(val_loss) / (iteration + 1)}) 119 | pbar.update(1) 120 | print('Finish Validation') 121 | 122 | logs = {'loss': loss.numpy() / epoch_step, 'val_loss': val_loss.numpy() / epoch_step_val} 123 | loss_history.on_epoch_end([], logs) 124 | eval_callback.on_epoch_end(epoch, logs) 125 | print('Epoch:'+ str(epoch+1) + '/' + str(Epoch)) 126 | print('Total Loss: %.3f || Val Loss: %.3f ' % (loss / epoch_step, val_loss / epoch_step_val)) 127 | 128 | #-----------------------------------------------# 129 | # 保存权值 130 | #-----------------------------------------------# 131 | if (epoch + 1) % save_period == 0 or epoch + 1 == Epoch: 132 | net.save_weights(os.path.join(save_dir, "ep%03d-loss%.3f-val_loss%.3f.h5" % (epoch + 1, loss / epoch_step, val_loss / epoch_step_val))) 133 | 134 | if len(loss_history.val_loss) <= 1 or (val_loss / epoch_step_val) <= min(loss_history.val_loss): 135 | print('Save best model to best_epoch_weights.pth') 136 | net.save_weights(os.path.join(save_dir, "best_epoch_weights.h5")) 137 | 138 | net.save_weights(os.path.join(save_dir, "last_epoch_weights.h5")) -------------------------------------------------------------------------------- /utils_coco/coco_annotation.py: -------------------------------------------------------------------------------- 1 | #-------------------------------------------------------# 2 | # 用于处理COCO数据集,根据json文件生成txt文件用于训练 3 | #-------------------------------------------------------# 4 | import json 5 | import os 6 | from collections import defaultdict 7 | 8 | #-------------------------------------------------------# 9 | # 指向了COCO训练集与验证集图片的路径 10 | #-------------------------------------------------------# 11 | train_datasets_path = "coco_dataset/train2017" 12 | val_datasets_path = "coco_dataset/val2017" 13 | 14 | #-------------------------------------------------------# 15 | # 指向了COCO训练集与验证集标签的路径 16 | #-------------------------------------------------------# 17 | train_annotation_path = "coco_dataset/annotations/instances_train2017.json" 18 | val_annotation_path = "coco_dataset/annotations/instances_val2017.json" 19 | 20 | #-------------------------------------------------------# 21 | # 生成的txt文件路径 22 | #-------------------------------------------------------# 23 | train_output_path = "coco_train.txt" 24 | val_output_path = "coco_val.txt" 25 | 26 | if __name__ == "__main__": 27 | name_box_id = defaultdict(list) 28 | id_name = dict() 29 | f = open(train_annotation_path, encoding='utf-8') 30 | data = json.load(f) 31 | 32 | annotations = data['annotations'] 33 | for ant in annotations: 34 | id = ant['image_id'] 35 | name = os.path.join(train_datasets_path, '%012d.jpg' % id) 36 | cat = ant['category_id'] 37 | if cat >= 1 and cat <= 11: 38 | cat = cat - 1 39 | elif cat >= 13 and cat <= 25: 40 | cat = cat - 2 41 | elif cat >= 27 and cat <= 28: 42 | cat = cat - 3 43 | elif cat >= 31 and cat <= 44: 44 | cat = cat - 5 45 | elif cat >= 46 and cat <= 65: 46 | cat = cat - 6 47 | elif cat == 67: 48 | cat = cat - 7 49 | elif cat == 70: 50 | cat = cat - 9 51 | elif cat >= 72 and cat <= 82: 52 | cat = cat - 10 53 | elif cat >= 84 and cat <= 90: 54 | cat = cat - 11 55 | name_box_id[name].append([ant['bbox'], cat]) 56 | 57 | f = open(train_output_path, 'w') 58 | for key in name_box_id.keys(): 59 | f.write(key) 60 | box_infos = name_box_id[key] 61 | for info in box_infos: 62 | x_min = int(info[0][0]) 63 | y_min = int(info[0][1]) 64 | x_max = x_min + int(info[0][2]) 65 | y_max = y_min + int(info[0][3]) 66 | 67 | box_info = " %d,%d,%d,%d,%d" % ( 68 | x_min, y_min, x_max, y_max, int(info[1])) 69 | f.write(box_info) 70 | f.write('\n') 71 | f.close() 72 | 73 | name_box_id = defaultdict(list) 74 | id_name = dict() 75 | f = open(val_annotation_path, encoding='utf-8') 76 | data = json.load(f) 77 | 78 | annotations = data['annotations'] 79 | for ant in annotations: 80 | id = ant['image_id'] 81 | name = os.path.join(val_datasets_path, '%012d.jpg' % id) 82 | cat = ant['category_id'] 83 | if cat >= 1 and cat <= 11: 84 | cat = cat - 1 85 | elif cat >= 13 and cat <= 25: 86 | cat = cat - 2 87 | elif cat >= 27 and cat <= 28: 88 | cat = cat - 3 89 | elif cat >= 31 and cat <= 44: 90 | cat = cat - 5 91 | elif cat >= 46 and cat <= 65: 92 | cat = cat - 6 93 | elif cat == 67: 94 | cat = cat - 7 95 | elif cat == 70: 96 | cat = cat - 9 97 | elif cat >= 72 and cat <= 82: 98 | cat = cat - 10 99 | elif cat >= 84 and cat <= 90: 100 | cat = cat - 11 101 | name_box_id[name].append([ant['bbox'], cat]) 102 | 103 | f = open(val_output_path, 'w') 104 | for key in name_box_id.keys(): 105 | f.write(key) 106 | box_infos = name_box_id[key] 107 | for info in box_infos: 108 | x_min = int(info[0][0]) 109 | y_min = int(info[0][1]) 110 | x_max = x_min + int(info[0][2]) 111 | y_max = y_min + int(info[0][3]) 112 | 113 | box_info = " %d,%d,%d,%d,%d" % ( 114 | x_min, y_min, x_max, y_max, int(info[1])) 115 | f.write(box_info) 116 | f.write('\n') 117 | f.close() 118 | -------------------------------------------------------------------------------- /utils_coco/get_map_coco.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | 4 | import numpy as np 5 | import tensorflow as tf 6 | from PIL import Image 7 | from pycocotools.coco import COCO 8 | from pycocotools.cocoeval import COCOeval 9 | from tqdm import tqdm 10 | from utils.utils import cvtColor, preprocess_input, resize_image 11 | from yolo import YOLO 12 | 13 | gpus = tf.config.experimental.list_physical_devices(device_type='GPU') 14 | for gpu in gpus: 15 | tf.config.experimental.set_memory_growth(gpu, True) 16 | #----------------------------------------------------------------------------# 17 | # map_mode用于指定该文件运行时计算的内容 18 | # map_mode为0代表整个map计算流程,包括获得预测结果、计算map。 19 | # map_mode为1代表仅仅获得预测结果。 20 | # map_mode为2代表仅仅获得计算map。 21 | #--------------------------------------------------------------------------# 22 | map_mode = 0 23 | #-------------------------------------------------------# 24 | # 指向了验证集标签与图片路径 25 | #-------------------------------------------------------# 26 | cocoGt_path = 'coco_dataset/annotations/instances_val2017.json' 27 | dataset_img_path = 'coco_dataset/val2017' 28 | #-------------------------------------------------------# 29 | # 结果输出的文件夹,默认为map_out 30 | #-------------------------------------------------------# 31 | temp_save_path = 'map_out/coco_eval' 32 | 33 | class mAP_YOLO(YOLO): 34 | #---------------------------------------------------# 35 | # 检测图片 36 | #---------------------------------------------------# 37 | def detect_image(self, image_id, image, results, clsid2catid): 38 | #---------------------------------------------------------# 39 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 40 | # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB 41 | #---------------------------------------------------------# 42 | image = cvtColor(image) 43 | #---------------------------------------------------------# 44 | # 给图像增加灰条,实现不失真的resize 45 | # 也可以直接resize进行识别 46 | #---------------------------------------------------------# 47 | image_data = resize_image(image, (self.input_shape[1], self.input_shape[0]), self.letterbox_image) 48 | #---------------------------------------------------------# 49 | # 添加上batch_size维度,并进行归一化 50 | #---------------------------------------------------------# 51 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 52 | 53 | #---------------------------------------------------------# 54 | # 将图像输入网络当中进行预测! 55 | #---------------------------------------------------------# 56 | input_image_shape = np.expand_dims(np.array([image.size[1], image.size[0]], dtype='float32'), 0) 57 | out_boxes, out_scores, out_classes = self.yolo_model.predict([image_data, input_image_shape]) 58 | 59 | for i, c in enumerate(out_classes): 60 | result = {} 61 | top, left, bottom, right = out_boxes[i] 62 | 63 | result["image_id"] = int(image_id) 64 | result["category_id"] = clsid2catid[c] 65 | result["bbox"] = [float(left),float(top),float(right-left),float(bottom-top)] 66 | result["score"] = float(out_scores[i]) 67 | results.append(result) 68 | 69 | return results 70 | 71 | if __name__ == "__main__": 72 | if not os.path.exists(temp_save_path): 73 | os.makedirs(temp_save_path) 74 | 75 | cocoGt = COCO(cocoGt_path) 76 | ids = list(cocoGt.imgToAnns.keys()) 77 | clsid2catid = cocoGt.getCatIds() 78 | 79 | if map_mode == 0 or map_mode == 1: 80 | yolo = mAP_YOLO(confidence = 0.001, nms_iou = 0.65) 81 | 82 | with open(os.path.join(temp_save_path, 'eval_results.json'),"w") as f: 83 | results = [] 84 | for image_id in tqdm(ids): 85 | image_path = os.path.join(dataset_img_path, cocoGt.loadImgs(image_id)[0]['file_name']) 86 | image = Image.open(image_path) 87 | results = yolo.detect_image(image_id, image, results, clsid2catid) 88 | json.dump(results, f) 89 | 90 | if map_mode == 0 or map_mode == 2: 91 | cocoDt = cocoGt.loadRes(os.path.join(temp_save_path, 'eval_results.json')) 92 | cocoEval = COCOeval(cocoGt, cocoDt, 'bbox') 93 | cocoEval.evaluate() 94 | cocoEval.accumulate() 95 | cocoEval.summarize() 96 | print("Get map done.") -------------------------------------------------------------------------------- /voc_annotation.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | import xml.etree.ElementTree as ET 4 | 5 | import numpy as np 6 | 7 | from utils.utils import get_classes 8 | 9 | #--------------------------------------------------------------------------------------------------------------------------------# 10 | # annotation_mode用于指定该文件运行时计算的内容 11 | # annotation_mode为0代表整个标签处理过程,包括获得VOCdevkit/VOC2007/ImageSets里面的txt以及训练用的2007_train.txt、2007_val.txt 12 | # annotation_mode为1代表获得VOCdevkit/VOC2007/ImageSets里面的txt 13 | # annotation_mode为2代表获得训练用的2007_train.txt、2007_val.txt 14 | #--------------------------------------------------------------------------------------------------------------------------------# 15 | annotation_mode = 0 16 | #-------------------------------------------------------------------# 17 | # 必须要修改,用于生成2007_train.txt、2007_val.txt的目标信息 18 | # 与训练和预测所用的classes_path一致即可 19 | # 如果生成的2007_train.txt里面没有目标信息 20 | # 那么就是因为classes没有设定正确 21 | # 仅在annotation_mode为0和2的时候有效 22 | #-------------------------------------------------------------------# 23 | classes_path = 'model_data/voc_classes.txt' 24 | #--------------------------------------------------------------------------------------------------------------------------------# 25 | # trainval_percent用于指定(训练集+验证集)与测试集的比例,默认情况下 (训练集+验证集):测试集 = 9:1 26 | # train_percent用于指定(训练集+验证集)中训练集与验证集的比例,默认情况下 训练集:验证集 = 9:1 27 | # 仅在annotation_mode为0和1的时候有效 28 | #--------------------------------------------------------------------------------------------------------------------------------# 29 | trainval_percent = 0.9 30 | train_percent = 0.9 31 | #-------------------------------------------------------# 32 | # 指向VOC数据集所在的文件夹 33 | # 默认指向根目录下的VOC数据集 34 | #-------------------------------------------------------# 35 | VOCdevkit_path = 'VOCdevkit' 36 | 37 | VOCdevkit_sets = [('2007', 'train'), ('2007', 'val')] 38 | classes, _ = get_classes(classes_path) 39 | 40 | #-------------------------------------------------------# 41 | # 统计目标数量 42 | #-------------------------------------------------------# 43 | photo_nums = np.zeros(len(VOCdevkit_sets)) 44 | nums = np.zeros(len(classes)) 45 | def convert_annotation(year, image_id, list_file): 46 | in_file = open(os.path.join(VOCdevkit_path, 'VOC%s/Annotations/%s.xml'%(year, image_id)), encoding='utf-8') 47 | tree=ET.parse(in_file) 48 | root = tree.getroot() 49 | 50 | for obj in root.iter('object'): 51 | difficult = 0 52 | if obj.find('difficult')!=None: 53 | difficult = obj.find('difficult').text 54 | cls = obj.find('name').text 55 | if cls not in classes or int(difficult)==1: 56 | continue 57 | cls_id = classes.index(cls) 58 | xmlbox = obj.find('bndbox') 59 | b = (int(float(xmlbox.find('xmin').text)), int(float(xmlbox.find('ymin').text)), int(float(xmlbox.find('xmax').text)), int(float(xmlbox.find('ymax').text))) 60 | list_file.write(" " + ",".join([str(a) for a in b]) + ',' + str(cls_id)) 61 | 62 | nums[classes.index(cls)] = nums[classes.index(cls)] + 1 63 | 64 | if __name__ == "__main__": 65 | random.seed(0) 66 | if " " in os.path.abspath(VOCdevkit_path): 67 | raise ValueError("数据集存放的文件夹路径与图片名称中不可以存在空格,否则会影响正常的模型训练,请注意修改。") 68 | 69 | if annotation_mode == 0 or annotation_mode == 1: 70 | print("Generate txt in ImageSets.") 71 | xmlfilepath = os.path.join(VOCdevkit_path, 'VOC2007/Annotations') 72 | saveBasePath = os.path.join(VOCdevkit_path, 'VOC2007/ImageSets/Main') 73 | temp_xml = os.listdir(xmlfilepath) 74 | total_xml = [] 75 | for xml in temp_xml: 76 | if xml.endswith(".xml"): 77 | total_xml.append(xml) 78 | 79 | num = len(total_xml) 80 | list = range(num) 81 | tv = int(num*trainval_percent) 82 | tr = int(tv*train_percent) 83 | trainval= random.sample(list,tv) 84 | train = random.sample(trainval,tr) 85 | 86 | print("train and val size",tv) 87 | print("train size",tr) 88 | ftrainval = open(os.path.join(saveBasePath,'trainval.txt'), 'w') 89 | ftest = open(os.path.join(saveBasePath,'test.txt'), 'w') 90 | ftrain = open(os.path.join(saveBasePath,'train.txt'), 'w') 91 | fval = open(os.path.join(saveBasePath,'val.txt'), 'w') 92 | 93 | for i in list: 94 | name=total_xml[i][:-4]+'\n' 95 | if i in trainval: 96 | ftrainval.write(name) 97 | if i in train: 98 | ftrain.write(name) 99 | else: 100 | fval.write(name) 101 | else: 102 | ftest.write(name) 103 | 104 | ftrainval.close() 105 | ftrain.close() 106 | fval.close() 107 | ftest.close() 108 | print("Generate txt in ImageSets done.") 109 | 110 | if annotation_mode == 0 or annotation_mode == 2: 111 | print("Generate 2007_train.txt and 2007_val.txt for train.") 112 | type_index = 0 113 | for year, image_set in VOCdevkit_sets: 114 | image_ids = open(os.path.join(VOCdevkit_path, 'VOC%s/ImageSets/Main/%s.txt'%(year, image_set)), encoding='utf-8').read().strip().split() 115 | list_file = open('%s_%s.txt'%(year, image_set), 'w', encoding='utf-8') 116 | for image_id in image_ids: 117 | list_file.write('%s/VOC%s/JPEGImages/%s.jpg'%(os.path.abspath(VOCdevkit_path), year, image_id)) 118 | 119 | convert_annotation(year, image_id, list_file) 120 | list_file.write('\n') 121 | photo_nums[type_index] = len(image_ids) 122 | type_index += 1 123 | list_file.close() 124 | print("Generate 2007_train.txt and 2007_val.txt for train done.") 125 | 126 | def printTable(List1, List2): 127 | for i in range(len(List1[0])): 128 | print("|", end=' ') 129 | for j in range(len(List1)): 130 | print(List1[j][i].rjust(int(List2[j])), end=' ') 131 | print("|", end=' ') 132 | print() 133 | 134 | str_nums = [str(int(x)) for x in nums] 135 | tableData = [ 136 | classes, str_nums 137 | ] 138 | colWidths = [0]*len(tableData) 139 | len1 = 0 140 | for i in range(len(tableData)): 141 | for j in range(len(tableData[i])): 142 | if len(tableData[i][j]) > colWidths[i]: 143 | colWidths[i] = len(tableData[i][j]) 144 | printTable(tableData, colWidths) 145 | 146 | if photo_nums[0] <= 500: 147 | print("训练集数量小于500,属于较小的数据量,请注意设置较大的训练世代(Epoch)以满足足够的梯度下降次数(Step)。") 148 | 149 | if np.sum(nums) == 0: 150 | print("在数据集中并未获得任何目标,请注意修改classes_path对应自己的数据集,并且保证标签名字正确,否则训练将会没有任何效果!") 151 | print("在数据集中并未获得任何目标,请注意修改classes_path对应自己的数据集,并且保证标签名字正确,否则训练将会没有任何效果!") 152 | print("在数据集中并未获得任何目标,请注意修改classes_path对应自己的数据集,并且保证标签名字正确,否则训练将会没有任何效果!") 153 | print("(重要的事情说三遍)。") 154 | -------------------------------------------------------------------------------- /yolo.py: -------------------------------------------------------------------------------- 1 | import colorsys 2 | import os 3 | import time 4 | import cv2 5 | import gc 6 | 7 | import numpy as np 8 | import tensorflow as tf 9 | from PIL import ImageDraw, ImageFont, Image 10 | from tensorflow.keras.layers import Input, Lambda 11 | from tensorflow.keras.models import Model 12 | 13 | from nets.yolo import yolo_body 14 | from utils.utils import (cvtColor, get_anchors, get_classes, preprocess_input, 15 | resize_image, show_config) 16 | from utils.utils_bbox import DecodeBox, DecodeBoxNP 17 | 18 | 19 | class YOLO(object): 20 | _defaults = { 21 | #--------------------------------------------------------------------------# 22 | # 使用自己训练好的模型进行预测一定要修改model_path和classes_path! 23 | # model_path指向logs文件夹下的权值文件,classes_path指向model_data下的txt 24 | # 25 | # 训练好后logs文件夹下存在多个权值文件,选择验证集损失较低的即可。 26 | # 验证集损失较低不代表mAP较高,仅代表该权值在验证集上泛化性能较好。 27 | # 如果出现shape不匹配,同时要注意训练时的model_path和classes_path参数的修改 28 | #--------------------------------------------------------------------------# 29 | "model_path" : 'model_data/yolov4_tiny_weights_coco.h5', 30 | "classes_path" : 'model_data/coco_classes.txt', 31 | #---------------------------------------------------------------------# 32 | # anchors_path代表先验框对应的txt文件,一般不修改。 33 | # anchors_mask用于帮助代码找到对应的先验框,一般不修改。 34 | #---------------------------------------------------------------------# 35 | "anchors_path" : 'model_data/yolo_anchors.txt', 36 | "anchors_mask" : [[3, 4, 5], [1, 2, 3]], 37 | #-------------------------------# 38 | # 所使用的注意力机制的类型 39 | # phi = 0为不使用注意力机制 40 | # phi = 1为SE 41 | # phi = 2为CBAM 42 | # phi = 3为ECA 43 | #-------------------------------# 44 | "phi" : 0, 45 | #---------------------------------------------------------------------# 46 | # 输入图片的大小,必须为32的倍数。 47 | #---------------------------------------------------------------------# 48 | "input_shape" : [416, 416], 49 | #---------------------------------------------------------------------# 50 | # 只有得分大于置信度的预测框会被保留下来 51 | #---------------------------------------------------------------------# 52 | "confidence" : 0.5, 53 | #---------------------------------------------------------------------# 54 | # 非极大抑制所用到的nms_iou大小 55 | #---------------------------------------------------------------------# 56 | "nms_iou" : 0.3, 57 | "max_boxes" : 100, 58 | #---------------------------------------------------------------------# 59 | # 该变量用于控制是否使用letterbox_image对输入图像进行不失真的resize, 60 | # 在多次测试后,发现关闭letterbox_image直接resize的效果更好 61 | #---------------------------------------------------------------------# 62 | "letterbox_image" : True, 63 | } 64 | 65 | @classmethod 66 | def get_defaults(cls, n): 67 | if n in cls._defaults: 68 | return cls._defaults[n] 69 | else: 70 | return "Unrecognized attribute name '" + n + "'" 71 | 72 | #---------------------------------------------------# 73 | # 初始化yolo 74 | #---------------------------------------------------# 75 | def __init__(self, **kwargs): 76 | self.__dict__.update(self._defaults) 77 | for name, value in kwargs.items(): 78 | setattr(self, name, value) 79 | self._defaults[name] = value 80 | 81 | #---------------------------------------------------# 82 | # 获得种类和先验框的数量 83 | #---------------------------------------------------# 84 | self.class_names, self.num_classes = get_classes(self.classes_path) 85 | self.anchors, self.num_anchors = get_anchors(self.anchors_path) 86 | 87 | #---------------------------------------------------# 88 | # 画框设置不同的颜色 89 | #---------------------------------------------------# 90 | hsv_tuples = [(x / self.num_classes, 1., 1.) for x in range(self.num_classes)] 91 | self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) 92 | self.colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), self.colors)) 93 | 94 | self.generate() 95 | 96 | show_config(**self._defaults) 97 | 98 | #---------------------------------------------------# 99 | # 载入模型 100 | #---------------------------------------------------# 101 | def generate(self): 102 | model_path = os.path.expanduser(self.model_path) 103 | assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.' 104 | 105 | self.model = yolo_body([self.input_shape[0], self.input_shape[1], 3], self.anchors_mask, self.num_classes, self.phi) 106 | self.model.load_weights(self.model_path) 107 | 108 | print('{} model, anchors, and classes loaded.'.format(model_path)) 109 | #---------------------------------------------------------# 110 | # 在DecodeBox函数中,我们会对预测结果进行后处理 111 | # 后处理的内容包括,解码、非极大抑制、门限筛选等 112 | #---------------------------------------------------------# 113 | self.input_image_shape = Input([2,],batch_size=1) 114 | inputs = [*self.model.output, self.input_image_shape] 115 | outputs = Lambda( 116 | DecodeBox, 117 | output_shape = (1,), 118 | name = 'yolo_eval', 119 | arguments = { 120 | 'anchors' : self.anchors, 121 | 'num_classes' : self.num_classes, 122 | 'input_shape' : self.input_shape, 123 | 'anchor_mask' : self.anchors_mask, 124 | 'confidence' : self.confidence, 125 | 'nms_iou' : self.nms_iou, 126 | 'max_boxes' : self.max_boxes, 127 | 'letterbox_image' : self.letterbox_image 128 | } 129 | )(inputs) 130 | self.yolo_model = Model([self.model.input, self.input_image_shape], outputs) 131 | 132 | @tf.function 133 | def get_pred(self, image_data, input_image_shape): 134 | out_boxes, out_scores, out_classes = self.yolo_model([image_data, input_image_shape], training=False) 135 | return out_boxes, out_scores, out_classes 136 | #---------------------------------------------------# 137 | # 检测图片 138 | #---------------------------------------------------# 139 | def detect_image(self, image, crop = False, count = False): 140 | #---------------------------------------------------------# 141 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 142 | # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB 143 | #---------------------------------------------------------# 144 | image = cvtColor(image) 145 | #---------------------------------------------------------# 146 | # 给图像增加灰条,实现不失真的resize 147 | # 也可以直接resize进行识别 148 | #---------------------------------------------------------# 149 | image_data = resize_image(image, (self.input_shape[1], self.input_shape[0]), self.letterbox_image) 150 | #---------------------------------------------------------# 151 | # 添加上batch_size维度,并进行归一化 152 | #---------------------------------------------------------# 153 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 154 | 155 | #---------------------------------------------------------# 156 | # 将图像输入网络当中进行预测! 157 | #---------------------------------------------------------# 158 | input_image_shape = np.expand_dims(np.array([image.size[1], image.size[0]], dtype='float32'), 0) 159 | out_boxes, out_scores, out_classes = self.get_pred(image_data, input_image_shape) 160 | 161 | print('Found {} boxes for {}'.format(len(out_boxes), 'img')) 162 | #---------------------------------------------------------# 163 | # 设置字体与边框厚度 164 | #---------------------------------------------------------# 165 | font = ImageFont.truetype(font='model_data/simhei.ttf', size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32')) 166 | thickness = int(max((image.size[0] + image.size[1]) // np.mean(self.input_shape), 1)) 167 | #---------------------------------------------------------# 168 | # 计数 169 | #---------------------------------------------------------# 170 | if count: 171 | print("top_label:", out_classes) 172 | classes_nums = np.zeros([self.num_classes]) 173 | for i in range(self.num_classes): 174 | num = np.sum(out_classes == i) 175 | if num > 0: 176 | print(self.class_names[i], " : ", num) 177 | classes_nums[i] = num 178 | print("classes_nums:", classes_nums) 179 | #---------------------------------------------------------# 180 | # 是否进行目标的裁剪 181 | #---------------------------------------------------------# 182 | if crop: 183 | for i, c in list(enumerate(out_boxes)): 184 | top, left, bottom, right = out_boxes[i] 185 | top = max(0, np.floor(top).astype('int32')) 186 | left = max(0, np.floor(left).astype('int32')) 187 | bottom = min(image.size[1], np.floor(bottom).astype('int32')) 188 | right = min(image.size[0], np.floor(right).astype('int32')) 189 | 190 | dir_save_path = "img_crop" 191 | if not os.path.exists(dir_save_path): 192 | os.makedirs(dir_save_path) 193 | crop_image = image.crop([left, top, right, bottom]) 194 | crop_image.save(os.path.join(dir_save_path, "crop_" + str(i) + ".png"), quality=95, subsampling=0) 195 | print("save crop_" + str(i) + ".png to " + dir_save_path) 196 | #---------------------------------------------------------# 197 | # 图像绘制 198 | #---------------------------------------------------------# 199 | for i, c in list(enumerate(out_classes)): 200 | predicted_class = self.class_names[int(c)] 201 | box = out_boxes[i] 202 | score = out_scores[i] 203 | 204 | top, left, bottom, right = box 205 | 206 | top = max(0, np.floor(top).astype('int32')) 207 | left = max(0, np.floor(left).astype('int32')) 208 | bottom = min(image.size[1], np.floor(bottom).astype('int32')) 209 | right = min(image.size[0], np.floor(right).astype('int32')) 210 | 211 | label = '{} {:.2f}'.format(predicted_class, score) 212 | draw = ImageDraw.Draw(image) 213 | label_size = draw.textsize(label, font) 214 | label = label.encode('utf-8') 215 | print(label, top, left, bottom, right) 216 | 217 | if top - label_size[1] >= 0: 218 | text_origin = np.array([left, top - label_size[1]]) 219 | else: 220 | text_origin = np.array([left, top + 1]) 221 | 222 | for i in range(thickness): 223 | draw.rectangle([left + i, top + i, right - i, bottom - i], outline=self.colors[c]) 224 | draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)], fill=self.colors[c]) 225 | draw.text(text_origin, str(label,'UTF-8'), fill=(0, 0, 0), font=font) 226 | del draw 227 | 228 | return image 229 | 230 | def get_FPS(self, image, test_interval): 231 | #---------------------------------------------------------# 232 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 233 | # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB 234 | #---------------------------------------------------------# 235 | image = cvtColor(image) 236 | #---------------------------------------------------------# 237 | # 给图像增加灰条,实现不失真的resize 238 | # 也可以直接resize进行识别 239 | #---------------------------------------------------------# 240 | image_data = resize_image(image, (self.input_shape[1], self.input_shape[0]), self.letterbox_image) 241 | #---------------------------------------------------------# 242 | # 添加上batch_size维度,并进行归一化 243 | #---------------------------------------------------------# 244 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 245 | 246 | #---------------------------------------------------------# 247 | # 将图像输入网络当中进行预测! 248 | #---------------------------------------------------------# 249 | input_image_shape = np.expand_dims(np.array([image.size[1], image.size[0]], dtype='float32'), 0) 250 | out_boxes, out_scores, out_classes = self.get_pred(image_data, input_image_shape) 251 | 252 | t1 = time.time() 253 | for _ in range(test_interval): 254 | out_boxes, out_scores, out_classes = self.get_pred(image_data, input_image_shape) 255 | t2 = time.time() 256 | tact_time = (t2 - t1) / test_interval 257 | return tact_time 258 | 259 | def detect_heatmap(self, image, heatmap_save_path): 260 | import cv2 261 | import matplotlib.pyplot as plt 262 | def sigmoid(x): 263 | y = 1.0 / (1.0 + np.exp(-x)) 264 | return y 265 | #---------------------------------------------------------# 266 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 267 | # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB 268 | #---------------------------------------------------------# 269 | image = cvtColor(image) 270 | #---------------------------------------------------------# 271 | # 给图像增加灰条,实现不失真的resize 272 | # 也可以直接resize进行识别 273 | #---------------------------------------------------------# 274 | image_data = resize_image(image, (self.input_shape[1], self.input_shape[0]), self.letterbox_image) 275 | #---------------------------------------------------------# 276 | # 添加上batch_size维度,并进行归一化 277 | #---------------------------------------------------------# 278 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 279 | 280 | output = self.model.predict(image_data) 281 | 282 | plt.imshow(image, alpha=1) 283 | plt.axis('off') 284 | mask = np.zeros((image.size[1], image.size[0])) 285 | for sub_output in output: 286 | b, h, w, c = np.shape(sub_output) 287 | sub_output = np.reshape(sub_output, [b, h, w, 3, -1])[0] 288 | score = np.max(sigmoid(sub_output[..., 4]), -1) 289 | score = cv2.resize(score, (image.size[0], image.size[1])) 290 | normed_score = (score * 255).astype('uint8') 291 | mask = np.maximum(mask, normed_score) 292 | 293 | plt.imshow(mask, alpha=0.5, interpolation='nearest', cmap="jet") 294 | 295 | plt.axis('off') 296 | plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) 297 | plt.margins(0, 0) 298 | plt.savefig(heatmap_save_path, dpi=200, bbox_inches='tight', pad_inches = -0.1) 299 | print("Save to the " + heatmap_save_path) 300 | plt.show() 301 | 302 | def convert_to_onnx(self, simplify, model_path): 303 | import onnx 304 | import tf2onnx 305 | spec = (tf.TensorSpec((None, *self.input_shape, 3), tf.float32, name="input"),) 306 | tf2onnx.convert.from_keras(self.model, input_signature=spec, opset=13, output_path=model_path) 307 | 308 | # Checks 309 | model_onnx = onnx.load(model_path) # load onnx model 310 | onnx.checker.check_model(model_onnx) # check onnx model 311 | 312 | # Simplify onnx 313 | if simplify: 314 | import onnxsim 315 | print(f'Simplifying with onnx-simplifier {onnxsim.__version__}.') 316 | model_onnx, check = onnxsim.simplify( 317 | model_onnx, 318 | dynamic_input_shape=False, 319 | input_shapes=None) 320 | assert check, 'assert check failed' 321 | onnx.save(model_onnx, model_path) 322 | 323 | print('Onnx model save as {}'.format(model_path)) 324 | 325 | #---------------------------------------------------# 326 | # 检测图片 327 | #---------------------------------------------------# 328 | def get_map_txt(self, image_id, image, class_names, map_out_path): 329 | f = open(os.path.join(map_out_path, "detection-results/"+image_id+".txt"),"w") 330 | #---------------------------------------------------------# 331 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 332 | #---------------------------------------------------------# 333 | image = cvtColor(image) 334 | #---------------------------------------------------------# 335 | # 给图像增加灰条,实现不失真的resize 336 | # 也可以直接resize进行识别 337 | #---------------------------------------------------------# 338 | image_data = resize_image(image, (self.input_shape[1], self.input_shape[0]), self.letterbox_image) 339 | #---------------------------------------------------------# 340 | # 添加上batch_size维度,并进行归一化 341 | #---------------------------------------------------------# 342 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 343 | 344 | #---------------------------------------------------------# 345 | # 将图像输入网络当中进行预测! 346 | #---------------------------------------------------------# 347 | input_image_shape = np.expand_dims(np.array([image.size[1], image.size[0]], dtype='float32'), 0) 348 | out_boxes, out_scores, out_classes = self.get_pred(image_data, input_image_shape) 349 | 350 | for i, c in enumerate(out_classes): 351 | predicted_class = self.class_names[int(c)] 352 | try: 353 | score = str(out_scores[i].numpy()) 354 | except: 355 | score = str(out_scores[i]) 356 | top, left, bottom, right = out_boxes[i] 357 | if predicted_class not in class_names: 358 | continue 359 | 360 | f.write("%s %s %s %s %s %s\n" % (predicted_class, score[:6], str(int(left)), str(int(top)), str(int(right)),str(int(bottom)))) 361 | 362 | f.close() 363 | return 364 | 365 | class YOLO_ONNX(object): 366 | _defaults = { 367 | #--------------------------------------------------------------------------# 368 | # 使用自己训练好的模型进行预测一定要修改onnx_path和classes_path! 369 | # onnx_path指向logs文件夹下的权值文件,classes_path指向model_data下的txt 370 | # 371 | # 训练好后logs文件夹下存在多个权值文件,选择验证集损失较低的即可。 372 | # 验证集损失较低不代表mAP较高,仅代表该权值在验证集上泛化性能较好。 373 | # 如果出现shape不匹配,同时要注意训练时的onnx_path和classes_path参数的修改 374 | #--------------------------------------------------------------------------# 375 | "onnx_path" : 'model_data/models.onnx', 376 | "classes_path" : 'model_data/coco_classes.txt', 377 | #---------------------------------------------------------------------# 378 | # anchors_path代表先验框对应的txt文件,一般不修改。 379 | # anchors_mask用于帮助代码找到对应的先验框,一般不修改。 380 | #---------------------------------------------------------------------# 381 | "anchors_path" : 'model_data/yolo_anchors.txt', 382 | "anchors_mask" : [[3, 4, 5], [1, 2, 3]], 383 | #---------------------------------------------------------------------# 384 | # 输入图片的大小,必须为32的倍数。 385 | #---------------------------------------------------------------------# 386 | "input_shape" : [416, 416], 387 | #---------------------------------------------------------------------# 388 | # 只有得分大于置信度的预测框会被保留下来 389 | #---------------------------------------------------------------------# 390 | "confidence" : 0.5, 391 | #---------------------------------------------------------------------# 392 | # 非极大抑制所用到的nms_iou大小 393 | #---------------------------------------------------------------------# 394 | "nms_iou" : 0.3, 395 | #---------------------------------------------------------------------# 396 | # 该变量用于控制是否使用letterbox_image对输入图像进行不失真的resize, 397 | # 在多次测试后,发现关闭letterbox_image直接resize的效果更好 398 | #---------------------------------------------------------------------# 399 | "letterbox_image" : True 400 | } 401 | 402 | @classmethod 403 | def get_defaults(cls, n): 404 | if n in cls._defaults: 405 | return cls._defaults[n] 406 | else: 407 | return "Unrecognized attribute name '" + n + "'" 408 | 409 | #---------------------------------------------------# 410 | # 初始化YOLO 411 | #---------------------------------------------------# 412 | def __init__(self, **kwargs): 413 | self.__dict__.update(self._defaults) 414 | for name, value in kwargs.items(): 415 | setattr(self, name, value) 416 | self._defaults[name] = value 417 | 418 | import onnxruntime 419 | self.onnx_session = onnxruntime.InferenceSession(self.onnx_path) 420 | # 获得所有的输入node 421 | self.input_name = self.get_input_name() 422 | # 获得所有的输出node 423 | self.output_name = self.get_output_name() 424 | 425 | #---------------------------------------------------# 426 | # 获得种类和先验框的数量 427 | #---------------------------------------------------# 428 | self.class_names, self.num_classes = self.get_classes(self.classes_path) 429 | self.anchors, self.num_anchors = self.get_anchors(self.anchors_path) 430 | self.bbox_util = DecodeBoxNP(self.anchors, self.num_classes, (self.input_shape[0], self.input_shape[1]), self.anchors_mask) 431 | 432 | #---------------------------------------------------# 433 | # 画框设置不同的颜色 434 | #---------------------------------------------------# 435 | hsv_tuples = [(x / self.num_classes, 1., 1.) for x in range(self.num_classes)] 436 | self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) 437 | self.colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), self.colors)) 438 | 439 | show_config(**self._defaults) 440 | 441 | def get_classes(self, classes_path): 442 | with open(classes_path, encoding='utf-8') as f: 443 | class_names = f.readlines() 444 | class_names = [c.strip() for c in class_names] 445 | return class_names, len(class_names) 446 | 447 | def get_anchors(self, anchors_path): 448 | '''loads the anchors from a file''' 449 | with open(anchors_path, encoding='utf-8') as f: 450 | anchors = f.readline() 451 | anchors = [float(x) for x in anchors.split(',')] 452 | anchors = np.array(anchors).reshape(-1, 2) 453 | return anchors, len(anchors) 454 | 455 | def get_input_name(self): 456 | # 获得所有的输入node 457 | input_name=[] 458 | for node in self.onnx_session.get_inputs(): 459 | input_name.append(node.name) 460 | return input_name 461 | 462 | def get_output_name(self): 463 | # 获得所有的输出node 464 | output_name=[] 465 | for node in self.onnx_session.get_outputs(): 466 | output_name.append(node.name) 467 | return output_name 468 | 469 | def get_input_feed(self,image_tensor): 470 | # 利用input_name获得输入的tensor 471 | input_feed={} 472 | for name in self.input_name: 473 | input_feed[name]=image_tensor 474 | return input_feed 475 | 476 | #---------------------------------------------------# 477 | # 对输入图像进行resize 478 | #---------------------------------------------------# 479 | def resize_image(self, image, size, letterbox_image, mode='PIL'): 480 | if mode == 'PIL': 481 | iw, ih = image.size 482 | w, h = size 483 | 484 | if letterbox_image: 485 | scale = min(w/iw, h/ih) 486 | nw = int(iw*scale) 487 | nh = int(ih*scale) 488 | 489 | image = image.resize((nw,nh), Image.BICUBIC) 490 | new_image = Image.new('RGB', size, (128,128,128)) 491 | new_image.paste(image, ((w-nw)//2, (h-nh)//2)) 492 | else: 493 | new_image = image.resize((w, h), Image.BICUBIC) 494 | else: 495 | image = np.array(image) 496 | if letterbox_image: 497 | # 获得现在的shape 498 | shape = np.shape(image)[:2] 499 | # 获得输出的shape 500 | if isinstance(size, int): 501 | size = (size, size) 502 | 503 | # 计算缩放的比例 504 | r = min(size[0] / shape[0], size[1] / shape[1]) 505 | 506 | # 计算缩放后图片的高宽 507 | new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) 508 | dw, dh = size[1] - new_unpad[0], size[0] - new_unpad[1] 509 | 510 | # 除以2以padding到两边 511 | dw /= 2 512 | dh /= 2 513 | 514 | # 对图像进行resize 515 | if shape[::-1] != new_unpad: # resize 516 | image = cv2.resize(image, new_unpad, interpolation=cv2.INTER_LINEAR) 517 | top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1)) 518 | left, right = int(round(dw - 0.1)), int(round(dw + 0.1)) 519 | 520 | new_image = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(128, 128, 128)) # add border 521 | else: 522 | new_image = cv2.resize(image, (w, h)) 523 | 524 | return new_image 525 | 526 | def detect_image(self, image): 527 | image_shape = np.array(np.shape(image)[0:2]) 528 | #---------------------------------------------------------# 529 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 530 | # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB 531 | #---------------------------------------------------------# 532 | image = cvtColor(image) 533 | 534 | image_data = self.resize_image(image, self.input_shape, True) 535 | #---------------------------------------------------------# 536 | # 添加上batch_size维度 537 | # h, w, 3 => 3, h, w => 1, 3, h, w 538 | #---------------------------------------------------------# 539 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 540 | 541 | input_feed = self.get_input_feed(image_data) 542 | outputs = self.onnx_session.run(output_names=self.output_name, input_feed=input_feed) 543 | 544 | feature_map_shape = [[int(j / (2 ** (i + 4))) for j in self.input_shape] for i in range(len(self.anchors_mask))][::-1] 545 | for i in range(len(self.anchors_mask)): 546 | outputs[i] = np.transpose(np.reshape(outputs[i], (1, feature_map_shape[i][0], feature_map_shape[i][1], len(self.anchors_mask[i]) * (5 + self.num_classes))), (0, 3, 1, 2)) 547 | 548 | outputs = self.bbox_util.decode_box(outputs) 549 | #---------------------------------------------------------# 550 | # 将预测框进行堆叠,然后进行非极大抑制 551 | #---------------------------------------------------------# 552 | results = self.bbox_util.non_max_suppression(np.concatenate(outputs, 1), self.num_classes, self.input_shape, 553 | image_shape, self.letterbox_image, conf_thres = self.confidence, nms_thres = self.nms_iou) 554 | 555 | if results[0] is None: 556 | return image 557 | 558 | top_label = np.array(results[0][:, 6], dtype = 'int32') 559 | top_conf = results[0][:, 4] * results[0][:, 5] 560 | top_boxes = results[0][:, :4] 561 | 562 | #---------------------------------------------------------# 563 | # 设置字体与边框厚度 564 | #---------------------------------------------------------# 565 | font = ImageFont.truetype(font='model_data/simhei.ttf', size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32')) 566 | thickness = int(max((image.size[0] + image.size[1]) // np.mean(self.input_shape), 1)) 567 | 568 | #---------------------------------------------------------# 569 | # 图像绘制 570 | #---------------------------------------------------------# 571 | for i, c in list(enumerate(top_label)): 572 | predicted_class = self.class_names[int(c)] 573 | box = top_boxes[i] 574 | score = top_conf[i] 575 | 576 | top, left, bottom, right = box 577 | 578 | top = max(0, np.floor(top).astype('int32')) 579 | left = max(0, np.floor(left).astype('int32')) 580 | bottom = min(image.size[1], np.floor(bottom).astype('int32')) 581 | right = min(image.size[0], np.floor(right).astype('int32')) 582 | 583 | label = '{} {:.2f}'.format(predicted_class, score) 584 | draw = ImageDraw.Draw(image) 585 | label_size = draw.textsize(label, font) 586 | label = label.encode('utf-8') 587 | print(label, top, left, bottom, right) 588 | 589 | if top - label_size[1] >= 0: 590 | text_origin = np.array([left, top - label_size[1]]) 591 | else: 592 | text_origin = np.array([left, top + 1]) 593 | 594 | for i in range(thickness): 595 | draw.rectangle([left + i, top + i, right - i, bottom - i], outline=self.colors[c]) 596 | draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)], fill=self.colors[c]) 597 | draw.text(text_origin, str(label,'UTF-8'), fill=(0, 0, 0), font=font) 598 | del draw 599 | 600 | return image -------------------------------------------------------------------------------- /常见问题汇总.md: -------------------------------------------------------------------------------- 1 | 问题汇总的博客地址为[https://blog.csdn.net/weixin_44791964/article/details/107517428](https://blog.csdn.net/weixin_44791964/article/details/107517428)。 2 | 3 | # 问题汇总 4 | ## 1、下载问题 5 | ### a、代码下载 6 | **问:up主,可以给我发一份代码吗,代码在哪里下载啊? 7 | 答:Github上的地址就在视频简介里。复制一下就能进去下载了。** 8 | 9 | **问:up主,为什么我下载的代码提示压缩包损坏? 10 | 答:重新去Github下载。** 11 | 12 | **问:up主,为什么我下载的代码和你在视频以及博客上的代码不一样? 13 | 答:我常常会对代码进行更新,最终以实际的代码为准。** 14 | 15 | ### b、 权值下载 16 | **问:up主,为什么我下载的代码里面,model_data下面没有.pth或者.h5文件? 17 | 答:我一般会把权值上传到Github和百度网盘,在GITHUB的README里面就能找到。** 18 | 19 | ### c、 数据集下载 20 | **问:up主,XXXX数据集在哪里下载啊? 21 | 答:一般数据集的下载地址我会放在README里面,基本上都有,没有的话请及时联系我添加,直接发github的issue即可**。 22 | 23 | ## 2、环境配置问题 24 | ### a、20系列及以下显卡环境配置 25 | **pytorch代码对应的pytorch版本为1.2,博客地址对应**[https://blog.csdn.net/weixin_44791964/article/details/106037141](https://blog.csdn.net/weixin_44791964/article/details/106037141)。 26 | 27 | **keras代码对应的tensorflow版本为1.13.2,keras版本是2.1.5,博客地址对应**[https://blog.csdn.net/weixin_44791964/article/details/104702142](https://blog.csdn.net/weixin_44791964/article/details/104702142)。 28 | 29 | **tf2代码对应的tensorflow版本为2.2.0,无需安装keras,博客地址对应**[https://blog.csdn.net/weixin_44791964/article/details/109161493](https://blog.csdn.net/weixin_44791964/article/details/109161493)。 30 | 31 | **问:你的代码某某某版本的tensorflow和pytorch能用嘛? 32 | 答:最好按照我推荐的配置,配置教程也有!其它版本的我没有试过!可能出现问题但是一般问题不大。仅需要改少量代码即可。** 33 | 34 | ### b、30系列显卡环境配置 35 | 30系显卡由于框架更新不可使用上述环境配置教程。 36 | 当前我已经测试的可以用的30显卡配置如下: 37 | **pytorch代码对应的pytorch版本为1.7.0,cuda为11.0,cudnn为8.0.5,博客地址对应**[https://blog.csdn.net/weixin_44791964/article/details/120668551](https://blog.csdn.net/weixin_44791964/article/details/120668551)。 38 | 39 | **keras代码无法在win10下配置cuda11,在ubuntu下可以百度查询一下,配置tensorflow版本为1.15.4,keras版本是2.1.5或者2.3.1(少量函数接口不同,代码可能还需要少量调整。)** 40 | 41 | **tf2代码对应的tensorflow版本为2.4.0,cuda为11.0,cudnn为8.0.5,博客地址对应为**[https://blog.csdn.net/weixin_44791964/article/details/120657664](https://blog.csdn.net/weixin_44791964/article/details/120657664)。 42 | 43 | ### c、CPU环境配置 44 | **pytorch代码对应的pytorch-cpu版本为1.2,博客地址对应**[https://blog.csdn.net/weixin_44791964/article/details/120655098](https://blog.csdn.net/weixin_44791964/article/details/120655098) 45 | 46 | **keras代码对应的tensorflow-cpu版本为1.13.2,keras版本是2.1.5,博客地址对应**[https://blog.csdn.net/weixin_44791964/article/details/120653717](https://blog.csdn.net/weixin_44791964/article/details/120653717)。 47 | 48 | **tf2代码对应的tensorflow-cpu版本为2.2.0,无需安装keras,博客地址对应**[https://blog.csdn.net/weixin_44791964/article/details/120656291](https://blog.csdn.net/weixin_44791964/article/details/120656291)。 49 | 50 | 51 | ### d、GPU利用问题与环境使用问题 52 | **问:为什么我安装了tensorflow-gpu但是却没用利用GPU进行训练呢? 53 | 答:确认tensorflow-gpu已经装好,利用pip list查看tensorflow版本,然后查看任务管理器或者利用nvidia命令看看是否使用了gpu进行训练,任务管理器的话要看显存使用情况。** 54 | 55 | **问:up主,我好像没有在用gpu进行训练啊,怎么看是不是用了GPU进行训练? 56 | 答:查看是否使用GPU进行训练一般使用NVIDIA在命令行的查看命令。在windows电脑中打开cmd然后利用nvidia-smi指令查看GPU利用情况** 57 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/f88ef794c9a341918f000eb2b1c67af6.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQnViYmxpaWlpbmc=,size_20,color_FFFFFF,t_70,g_se,x_16) 58 | **如果要一定看任务管理器的话,请看性能部分GPU的显存是否利用,或者查看任务管理器的Cuda,而非Copy。** 59 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20201013234241524.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDc5MTk2NA==,size_16,color_FFFFFF,t_70#pic_center) 60 | 61 | ### e、DLL load failed: 找不到指定的模块 62 | **问:出现如下错误** 63 | ```python 64 | Traceback (most recent call last): 65 | File "C:\Users\focus\Anaconda3\ana\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in 66 | from tensorflow.python.pywrap_tensorflow_internal import * 67 | File "C:\Users\focus\Anaconda3\ana\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in 68 | pywrap_tensorflow_internal = swig_import_helper() 69 | File "C:\Users\focus\Anaconda3\ana\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper 70 | _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) 71 | File "C:\Users\focus\Anaconda3\ana\envs\tensorflow-gpu\lib\imp.py", line 243, in load_modulereturn load_dynamic(name, filename, file) 72 | File "C:\Users\focus\Anaconda3\ana\envs\tensorflow-gpu\lib\imp.py", line 343, in load_dynamic 73 | return _load(spec) 74 | ImportError: DLL load failed: 找不到指定的模块。 75 | ``` 76 | **答:如果没重启过就重启一下,否则重新按照步骤安装,还无法解决则把你的GPU、CUDA、CUDNN、TF版本以及PYTORCH版本私聊告诉我。** 77 | 78 | ### f、no module问题(no module name utils.utils、no module named 'matplotlib' ) 79 | **问:为什么提示说no module name utils.utils(no module name nets.yolo、no module name nets.ssd等一系列问题)啊? 80 | 答:utils并不需要用pip装,它就在我上传的仓库的根目录,出现这个问题的原因是根目录不对,查查相对目录和根目录的概念。查了基本上就明白了。** 81 | 82 | **问:为什么提示说no module name matplotlib(no module name PIL,no module name cv2等等)? 83 | 答:这个库没安装打开命令行安装就好。pip install matplotlib** 84 | 85 | **问:为什么我已经用pip装了opencv(pillow、matplotlib等),还是提示no module name cv2? 86 | 答:没有激活环境装,要激活对应的conda环境进行安装才可以正常使用** 87 | 88 | **问:为什么提示说No module named 'torch' ? 89 | 答:其实我也真的很想知道为什么会有这个问题……这个pytorch没装是什么情况?一般就俩情况,一个是真的没装,还有一个是装到其它环境了,当前激活的环境不是自己装的环境。** 90 | 91 | **问:为什么提示说No module named 'tensorflow' ? 92 | 答:同上。** 93 | 94 | ### g、cuda安装失败问题 95 | 一般cuda安装前需要安装Visual Studio,装个2017版本即可。 96 | 97 | ### h、Ubuntu系统问题 98 | **所有代码在Ubuntu下可以使用,我两个系统都试过。** 99 | 100 | ### i、VSCODE提示错误的问题 101 | **问:为什么在VSCODE里面提示一大堆的错误啊? 102 | 答:我也提示一大堆的错误,但是不影响,是VSCODE的问题,如果不想看错误的话就装Pycharm。 103 | 最好将设置里面的Python:Language Server,调整为Pylance。** 104 | 105 | ### j、使用cpu进行训练与预测的问题 106 | **对于keras和tf2的代码而言,如果想用cpu进行训练和预测,直接装cpu版本的tensorflow就可以了。** 107 | 108 | **对于pytorch的代码而言,如果想用cpu进行训练和预测,需要将cuda=True修改成cuda=False。** 109 | 110 | ### k、tqdm没有pos参数问题 111 | **问:运行代码提示'tqdm' object has no attribute 'pos'。 112 | 答:重装tqdm,换个版本就可以了。** 113 | 114 | ### l、提示decode(“utf-8”)的问题 115 | **由于h5py库的更新,安装过程中会自动安装h5py=3.0.0以上的版本,会导致decode("utf-8")的错误! 116 | 各位一定要在安装完tensorflow后利用命令装h5py=2.10.0!** 117 | ``` 118 | pip install h5py==2.10.0 119 | ``` 120 | 121 | ### m、提示TypeError: __array__() takes 1 positional argument but 2 were given错误 122 | 可以修改pillow版本解决。 123 | ``` 124 | pip install pillow==8.2.0 125 | ``` 126 | ### n、如何查看当前cuda和cudnn 127 | **window下cuda版本查看方式如下: 128 | 1、打开cmd窗口。 129 | 2、输入nvcc -V。 130 | 3、Cuda compilation tools, release XXXXXXXX中的XXXXXXXX即cuda版本。** 131 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/0389ea35107a408a80ab5cb6590d5a74.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQnViYmxpaWlpbmc=,size_20,color_FFFFFF,t_70,g_se,x_16) 132 | window下cudnn版本查看方式如下: 133 | 1、进入cuda安装目录,进入incude文件夹。 134 | 2、找到cudnn.h文件。 135 | 3、右键文本打开,下拉,看到#define处可获得cudnn版本。 136 | ```python 137 | #define CUDNN_MAJOR 7 138 | #define CUDNN_MINOR 4 139 | #define CUDNN_PATCHLEVEL 1 140 | ``` 141 | 代表cudnn为7.4.1。 142 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/7a86b68b17c84feaa6fa95780d4ae4b4.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQnViYmxpaWlpbmc=,size_20,color_FFFFFF,t_70,g_se,x_16) 143 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/81bb7c3e13cc492292530e4b69df86a9.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQnViYmxpaWlpbmc=,size_20,color_FFFFFF,t_70,g_se,x_16) 144 | 145 | ### o、为什么按照你的环境配置后还是不能使用 146 | **问:up主,为什么我按照你的环境配置后还是不能使用? 147 | 答:请把你的GPU、CUDA、CUDNN、TF版本以及PYTORCH版本B站私聊告诉我。** 148 | 149 | ### p、其它问题 150 | **问:为什么提示TypeError: cat() got an unexpected keyword argument 'axis',Traceback (most recent call last),AttributeError: 'Tensor' object has no attribute 'bool'? 151 | 答:这是版本问题,建议使用torch1.2以上版本** 152 | 153 | **其它有很多稀奇古怪的问题,很多是版本问题,建议按照我的视频教程安装Keras和tensorflow。比如装的是tensorflow2,就不用问我说为什么我没法运行Keras-yolo啥的。那是必然不行的。** 154 | 155 | ## 3、目标检测库问题汇总(人脸检测和分类库也可参考) 156 | ### a、shape不匹配问题。 157 | #### 1)、训练时shape不匹配问题。 158 | **问:up主,为什么运行train.py会提示shape不匹配啊? 159 | 答:在keras环境中,因为你训练的种类和原始的种类不同,网络结构会变化,所以最尾部的shape会有少量不匹配。** 160 | 161 | #### 2)、预测时shape不匹配问题。 162 | **问:为什么我运行predict.py会提示我说shape不匹配呀。** 163 | ##### i、copying a param with shape torch.Size([75, 704, 1, 1]) from checkpoint 164 | 在Pytorch里面是这样的: 165 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200722171631901.png) 166 | ##### ii、Shapes are [1,1,1024,75] and [255,1024,1,1]. for 'Assign_360' (op: 'Assign') with input shapes: [1,1,1024,75], [255,1024,1,1]. 167 | 在Keras里面是这样的: 168 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200722171523380.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDc5MTk2NA==,size_16,color_FFFFFF,t_70) 169 | **答:原因主要有仨: 170 | 1、训练的classes_path没改,就开始训练了。 171 | 2、训练的model_path没改。 172 | 3、训练的classes_path没改。 173 | 请检查清楚了!确定自己所用的model_path和classes_path是对应的!训练的时候用到的num_classes或者classes_path也需要检查!** 174 | 175 | ### b、显存不足问题(OOM、RuntimeError: CUDA out of memory)。 176 | **问:为什么我运行train.py下面的命令行闪的贼快,还提示OOM啥的? 177 | 答:这是在keras中出现的,爆显存了,可以改小batch_size,SSD的显存占用率是最小的,建议用SSD; 178 | 2G显存:SSD、YOLOV4-TINY 179 | 4G显存:YOLOV3 180 | 6G显存:YOLOV4、Retinanet、M2det、Efficientdet、Faster RCNN等 181 | 8G+显存:随便选吧。** 182 | **需要注意的是,受到BatchNorm2d影响,batch_size不可为1,至少为2。** 183 | 184 | **问:为什么提示 RuntimeError: CUDA out of memory. Tried to allocate 52.00 MiB (GPU 0; 15.90 GiB total capacity; 14.85 GiB already allocated; 51.88 MiB free; 15.07 GiB reserved in total by PyTorch)? 185 | 答:这是pytorch中出现的,爆显存了,同上。** 186 | 187 | **问:为什么我显存都没利用,就直接爆显存了? 188 | 答:都爆显存了,自然就不利用了,模型没有开始训练。** 189 | ### c、为什么要进行冻结训练与解冻训练,不进行行吗? 190 | **问:为什么要冻结训练和解冻训练呀? 191 | 答:可以不进行,本质上是为了保证性能不足的同学的训练,如果电脑性能完全不够,可以将Freeze_Epoch和UnFreeze_Epoch设置成一样,只进行冻结训练。** 192 | 193 | **同时这也是迁移学习的思想,因为神经网络主干特征提取部分所提取到的特征是通用的,我们冻结起来训练可以加快训练效率,也可以防止权值被破坏。** 194 | 在冻结阶段,模型的主干被冻结了,特征提取网络不发生改变。占用的显存较小,仅对网络进行微调。 195 | 在解冻阶段,模型的主干不被冻结了,特征提取网络会发生改变。占用的显存较大,网络所有的参数都会发生改变。 196 | 197 | ### d、我的LOSS好大啊,有问题吗?(我的LOSS好小啊,有问题吗?) 198 | **问:为什么我的网络不收敛啊,LOSS是XXXX。 199 | 答:不同网络的LOSS不同,LOSS只是一个参考指标,用于查看网络是否收敛,而非评价网络好坏,我的yolo代码都没有归一化,所以LOSS值看起来比较高,LOSS的值不重要,重要的是是否在变小,预测是否有效果。** 200 | 201 | ### e、为什么我训练出来的模型没有预测结果? 202 | **问:为什么我的训练效果不好?预测了没有框(框不准)。 203 | 答:** 204 | 考虑几个问题: 205 | 1、目标信息问题,查看2007_train.txt文件是否有目标信息,没有的话请修改voc_annotation.py。 206 | 2、数据集问题,小于500的自行考虑增加数据集,同时测试不同的模型,确认数据集是好的。 207 | 3、是否解冻训练,如果数据集分布与常规画面差距过大需要进一步解冻训练,调整主干,加强特征提取能力。 208 | 4、网络问题,比如SSD不适合小目标,因为先验框固定了。 209 | 5、训练时长问题,有些同学只训练了几代表示没有效果,按默认参数训练完。 210 | 6、确认自己是否按照步骤去做了,如果比如voc_annotation.py里面的classes是否修改了等。 211 | 7、不同网络的LOSS不同,LOSS只是一个参考指标,用于查看网络是否收敛,而非评价网络好坏,LOSS的值不重要,重要的是是否收敛。 212 | 8、是否修改了网络的主干,如果修改了没有预训练权重,网络不容易收敛,自然效果不好。 213 | 214 | ### f、为什么我计算出来的map是0? 215 | **问:为什么我的训练效果不好?没有map? 216 | 答:** 217 | 首先尝试利用predict.py预测一下,如果有效果的话应该是get_map.py里面的classes_path设置错误。如果没有预测结果的话,解决方法同e问题,对下面几点进行检查: 218 | 1、目标信息问题,查看2007_train.txt文件是否有目标信息,没有的话请修改voc_annotation.py。 219 | 2、数据集问题,小于500的自行考虑增加数据集,同时测试不同的模型,确认数据集是好的。 220 | 3、是否解冻训练,如果数据集分布与常规画面差距过大需要进一步解冻训练,调整主干,加强特征提取能力。 221 | 4、网络问题,比如SSD不适合小目标,因为先验框固定了。 222 | 5、训练时长问题,有些同学只训练了几代表示没有效果,按默认参数训练完。 223 | 6、确认自己是否按照步骤去做了,如果比如voc_annotation.py里面的classes是否修改了等。 224 | 7、不同网络的LOSS不同,LOSS只是一个参考指标,用于查看网络是否收敛,而非评价网络好坏,LOSS的值不重要,重要的是是否收敛。 225 | 8、是否修改了网络的主干,如果修改了没有预训练权重,网络不容易收敛,自然效果不好。 226 | 227 | ### g、gbk编码错误('gbk' codec can't decode byte)。 228 | **问:我怎么出现了gbk什么的编码错误啊:** 229 | ```python 230 | UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 446: illegal multibyte sequence 231 | ``` 232 | **答:标签和路径不要使用中文,如果一定要使用中文,请注意处理的时候编码的问题,改成打开文件的encoding方式改为utf-8。** 233 | 234 | ### h、我的图片是xxx*xxx的分辨率的,可以用吗? 235 | **问:我的图片是xxx*xxx的分辨率的,可以用吗!** 236 | **答:可以用,代码里面会自动进行resize与数据增强。** 237 | 238 | ### i、我想进行数据增强!怎么增强? 239 | **问:我想要进行数据增强!怎么做呢?** 240 | **答:可以用,代码里面会自动进行resize与数据增强。** 241 | 242 | ### j、多GPU训练。 243 | **问:怎么进行多GPU训练? 244 | 答:pytorch的大多数代码可以直接使用gpu训练,keras的话直接百度就好了,实现并不复杂,我没有多卡没法详细测试,还需要各位同学自己努力了。** 245 | 246 | ### k、能不能训练灰度图? 247 | **问:能不能训练灰度图(预测灰度图)啊? 248 | 答:我的大多数库会将灰度图转化成RGB进行训练和预测,如果遇到代码不能训练或者预测灰度图的情况,可以尝试一下在get_random_data里面将Image.open后的结果转换成RGB,预测的时候也这样试试。(仅供参考)** 249 | 250 | ### l、断点续练问题。 251 | **问:我已经训练过几个世代了,能不能从这个基础上继续开始训练 252 | 答:可以,你在训练前,和载入预训练权重一样载入训练过的权重就行了。一般训练好的权重会保存在logs文件夹里面,将model_path修改成你要开始的权值的路径即可。** 253 | 254 | ### m、我要训练其它的数据集,预训练权重能不能用? 255 | **问:如果我要训练其它的数据集,预训练权重要怎么办啊?** 256 | **答:数据的预训练权重对不同数据集是通用的,因为特征是通用的,预训练权重对于99%的情况都必须要用,不用的话权值太过随机,特征提取效果不明显,网络训练的结果也不会好。** 257 | 258 | ### n、网络如何从0开始训练? 259 | **问:我要怎么不使用预训练权重啊? 260 | 答:看一看注释、大多数代码是model_path = '',Freeze_Train = Fasle**,如果设置model_path无用,**那么把载入预训练权重的代码注释了就行。** 261 | 262 | ### o、为什么从0开始训练效果这么差(修改了网络主干,效果不好怎么办)? 263 | **问:为什么我不使用预训练权重效果这么差啊? 264 | 答:因为随机初始化的权值不好,提取的特征不好,也就导致了模型训练的效果不好,voc07+12、coco+voc07+12效果都不一样,预训练权重还是非常重要的。** 265 | 266 | **问:up,我修改了网络,预训练权重还能用吗? 267 | 答:修改了主干的话,如果不是用的现有的网络,基本上预训练权重是不能用的,要么就自己判断权值里卷积核的shape然后自己匹配,要么只能自己预训练去了;修改了后半部分的话,前半部分的主干部分的预训练权重还是可以用的,如果是pytorch代码的话,需要自己修改一下载入权值的方式,判断shape后载入,如果是keras代码,直接by_name=True,skip_mismatch=True即可。** 268 | 权值匹配的方式可以参考如下: 269 | ```python 270 | # 加快模型训练的效率 271 | print('Loading weights into state dict...') 272 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 273 | model_dict = model.state_dict() 274 | pretrained_dict = torch.load(model_path, map_location=device) 275 | a = {} 276 | for k, v in pretrained_dict.items(): 277 | try: 278 | if np.shape(model_dict[k]) == np.shape(v): 279 | a[k]=v 280 | except: 281 | pass 282 | model_dict.update(a) 283 | model.load_state_dict(model_dict) 284 | print('Finished!') 285 | ``` 286 | 287 | **问:为什么从0开始训练效果这么差(我修改了网络主干,效果不好怎么办)? 288 | 答:一般来讲,网络从0开始的训练效果会很差,因为权值太过随机,特征提取效果不明显,因此非常、非常、非常不建议大家从0开始训练!如果一定要从0开始,可以了解imagenet数据集,首先训练分类模型,获得网络的主干部分权值,分类模型的 主干部分 和该模型通用,基于此进行训练。 289 | 网络修改了主干之后也是同样的问题,随机的权值效果很差。** 290 | 291 | **问:怎么在模型上从0开始训练? 292 | 答:在算力不足与调参能力不足的情况下从0开始训练毫无意义。模型特征提取能力在随机初始化参数的情况下非常差。没有好的参数调节能力和算力,无法使得网络正常收敛。** 293 | 如果一定要从0开始,那么训练的时候请注意几点: 294 | - 不载入预训练权重。 295 | - 不要进行冻结训练,注释冻结模型的代码。 296 | 297 | **问:为什么我不使用预训练权重效果这么差啊? 298 | 答:因为随机初始化的权值不好,提取的特征不好,也就导致了模型训练的效果不好,voc07+12、coco+voc07+12效果都不一样,预训练权重还是非常重要的。** 299 | 300 | ### p、你的权值都是哪里来的? 301 | **问:如果网络不能从0开始训练的话你的权值哪里来的? 302 | 答:有些权值是官方转换过来的,有些权值是自己训练出来的,我用到的主干的imagenet的权值都是官方的。** 303 | 304 | ### q、视频检测与摄像头检测 305 | **问:怎么用摄像头检测呀? 306 | 答:predict.py修改参数可以进行摄像头检测,也有视频详细解释了摄像头检测的思路。** 307 | 308 | **问:怎么用视频检测呀? 309 | 答:同上** 310 | 311 | ### r、如何保存检测出的图片 312 | **问:检测完的图片怎么保存? 313 | 答:一般目标检测用的是Image,所以查询一下PIL库的Image如何进行保存。详细看看predict.py文件的注释。** 314 | 315 | **问:怎么用视频保存呀? 316 | 答:详细看看predict.py文件的注释。** 317 | 318 | ### s、遍历问题 319 | **问:如何对一个文件夹的图片进行遍历? 320 | 答:一般使用os.listdir先找出文件夹里面的所有图片,然后根据predict.py文件里面的执行思路检测图片就行了,详细看看predict.py文件的注释。** 321 | 322 | **问:如何对一个文件夹的图片进行遍历?并且保存。 323 | 答:遍历的话一般使用os.listdir先找出文件夹里面的所有图片,然后根据predict.py文件里面的执行思路检测图片就行了。保存的话一般目标检测用的是Image,所以查询一下PIL库的Image如何进行保存。如果有些库用的是cv2,那就是查一下cv2怎么保存图片。详细看看predict.py文件的注释。** 324 | 325 | ### t、路径问题(No such file or directory、StopIteration: [Errno 13] Permission denied: 'XXXXXX') 326 | **问:我怎么出现了这样的错误呀:** 327 | ```python 328 | FileNotFoundError: 【Errno 2】 No such file or directory 329 | StopIteration: [Errno 13] Permission denied: 'D:\\Study\\Collection\\Dataset\\VOC07+12+test\\VOCdevkit/VOC2007' 330 | …………………………………… 331 | …………………………………… 332 | ``` 333 | **答:去检查一下文件夹路径,查看是否有对应文件;并且检查一下2007_train.txt,其中文件路径是否有错。** 334 | 关于路径有几个重要的点: 335 | **文件夹名称中一定不要有空格。 336 | 注意相对路径和绝对路径。 337 | 多百度路径相关的知识。** 338 | 339 | **所有的路径问题基本上都是根目录问题,好好查一下相对目录的概念!** 340 | ### u、和原版比较问题,你怎么和原版不一样啊? 341 | **问:原版的代码是XXX,为什么你的代码是XXX? 342 | 答:是啊……这要不怎么说我不是原版呢……** 343 | 344 | **问:你这个代码和原版比怎么样,可以达到原版的效果么? 345 | 答:基本上可以达到,我都用voc数据测过,我没有好显卡,没有能力在coco上测试与训练。** 346 | 347 | **问:你有没有实现yolov4所有的tricks,和原版差距多少? 348 | 答:并没有实现全部的改进部分,由于YOLOV4使用的改进实在太多了,很难完全实现与列出来,这里只列出来了一些我比较感兴趣,而且非常有效的改进。论文中提到的SAM(注意力机制模块),作者自己的源码也没有使用。还有其它很多的tricks,不是所有的tricks都有提升,我也没法实现全部的tricks。至于和原版的比较,我没有能力训练coco数据集,根据使用过的同学反应差距不大。** 349 | 350 | ### v、我的检测速度是xxx正常吗?我的检测速度还能增快吗? 351 | **问:你这个FPS可以到达多少,可以到 XX FPS么? 352 | 答:FPS和机子的配置有关,配置高就快,配置低就慢。** 353 | 354 | **问:我的检测速度是xxx正常吗?我的检测速度还能增快吗? 355 | 答:看配置,配置好速度就快,如果想要配置不变的情况下加快速度,就要修改网络了。** 356 | 357 | **问:为什么我用服务器去测试yolov4(or others)的FPS只有十几? 358 | 答:检查是否正确安装了tensorflow-gpu或者pytorch的gpu版本,如果已经正确安装,可以去利用time.time()的方法查看detect_image里面,哪一段代码耗时更长(不仅只有网络耗时长,其它处理部分也会耗时,如绘图等)。** 359 | 360 | **问:为什么论文中说速度可以达到XX,但是这里却没有? 361 | 答:检查是否正确安装了tensorflow-gpu或者pytorch的gpu版本,如果已经正确安装,可以去利用time.time()的方法查看detect_image里面,哪一段代码耗时更长(不仅只有网络耗时长,其它处理部分也会耗时,如绘图等)。有些论文还会使用多batch进行预测,我并没有去实现这个部分。** 362 | 363 | ### w、预测图片不显示问题 364 | **问:为什么你的代码在预测完成后不显示图片?只是在命令行告诉我有什么目标。 365 | 答:给系统安装一个图片查看器就行了。** 366 | 367 | ### x、算法评价问题(目标检测的map、PR曲线、Recall、Precision等) 368 | **问:怎么计算map? 369 | 答:看map视频,都一个流程。** 370 | 371 | **问:计算map的时候,get_map.py里面有一个MINOVERLAP是什么用的,是iou吗? 372 | 答:是iou,它的作用是判断预测框和真实框的重合成度,如果重合程度大于MINOVERLAP,则预测正确。** 373 | 374 | **问:为什么get_map.py里面的self.confidence(self.score)要设置的那么小? 375 | 答:看一下map的视频的原理部分,要知道所有的结果然后再进行pr曲线的绘制。** 376 | 377 | **问:能不能说说怎么绘制PR曲线啥的呀。 378 | 答:可以看mAP视频,结果里面有PR曲线。** 379 | 380 | **问:怎么计算Recall、Precision指标。 381 | 答:这俩指标应该是相对于特定的置信度的,计算map的时候也会获得。** 382 | 383 | ### y、coco数据集训练问题 384 | **问:目标检测怎么训练COCO数据集啊?。 385 | 答:coco数据训练所需要的txt文件可以参考qqwweee的yolo3的库,格式都是一样的。** 386 | 387 | ### z、UP,怎么优化模型啊?我想提升效果 388 | **问:up,怎么修改模型啊,我想发个小论文! 389 | 答:建议看看yolov3和yolov4的区别,然后看看yolov4的论文,作为一个大型调参现场非常有参考意义,使用了很多tricks。我能给的建议就是多看一些经典模型,然后拆解里面的亮点结构并使用。** 390 | 391 | ### aa、UP,有Focal LOSS的代码吗?怎么改啊? 392 | **问:up,YOLO系列使用Focal LOSS的代码你有吗,有提升吗? 393 | 答:很多人试过,提升效果也不大(甚至变的更Low),它自己有自己的正负样本的平衡方式**。改代码的事情,还是自己好好看看代码吧。 394 | 395 | ### ab、部署问题(ONNX、TensorRT等) 396 | 我没有具体部署到手机等设备上过,所以很多部署问题我并不了解…… 397 | 398 | ## 4、语义分割库问题汇总 399 | ### a、shape不匹配问题 400 | #### 1)、训练时shape不匹配问题 401 | **问:up主,为什么运行train.py会提示shape不匹配啊? 402 | 答:在keras环境中,因为你训练的种类和原始的种类不同,网络结构会变化,所以最尾部的shape会有少量不匹配。** 403 | 404 | #### 2)、预测时shape不匹配问题 405 | **问:为什么我运行predict.py会提示我说shape不匹配呀。** 406 | ##### i、copying a param with shape torch.Size([75, 704, 1, 1]) from checkpoint 407 | 在Pytorch里面是这样的: 408 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200722171631901.png) 409 | ##### ii、Shapes are [1,1,1024,75] and [255,1024,1,1]. for 'Assign_360' (op: 'Assign') with input shapes: [1,1,1024,75], [255,1024,1,1]. 410 | 在Keras里面是这样的: 411 | ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200722171523380.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDc5MTk2NA==,size_16,color_FFFFFF,t_70) 412 | **答:原因主要有二: 413 | 1、train.py里面的num_classes没改。 414 | 2、预测时num_classes没改。 415 | 3、预测时model_path没改。 416 | 请检查清楚!训练和预测的时候用到的num_classes都需要检查!** 417 | 418 | ### b、显存不足问题(OOM、RuntimeError: CUDA out of memory)。 419 | **问:为什么我运行train.py下面的命令行闪的贼快,还提示OOM啥的? 420 | 答:这是在keras中出现的,爆显存了,可以改小batch_size。** 421 | 422 | **需要注意的是,受到BatchNorm2d影响,batch_size不可为1,至少为2。** 423 | 424 | **问:为什么提示 RuntimeError: CUDA out of memory. Tried to allocate 52.00 MiB (GPU 0; 15.90 GiB total capacity; 14.85 GiB already allocated; 51.88 MiB free; 15.07 GiB reserved in total by PyTorch)? 425 | 答:这是pytorch中出现的,爆显存了,同上。** 426 | 427 | **问:为什么我显存都没利用,就直接爆显存了? 428 | 答:都爆显存了,自然就不利用了,模型没有开始训练。** 429 | 430 | ### c、为什么要进行冻结训练与解冻训练,不进行行吗? 431 | **问:为什么要冻结训练和解冻训练呀? 432 | 答:可以不进行,本质上是为了保证性能不足的同学的训练,如果电脑性能完全不够,可以将Freeze_Epoch和UnFreeze_Epoch设置成一样,只进行冻结训练。** 433 | 434 | **同时这也是迁移学习的思想,因为神经网络主干特征提取部分所提取到的特征是通用的,我们冻结起来训练可以加快训练效率,也可以防止权值被破坏。** 435 | 在冻结阶段,模型的主干被冻结了,特征提取网络不发生改变。占用的显存较小,仅对网络进行微调。 436 | 在解冻阶段,模型的主干不被冻结了,特征提取网络会发生改变。占用的显存较大,网络所有的参数都会发生改变。 437 | 438 | ### d、我的LOSS好大啊,有问题吗?(我的LOSS好小啊,有问题吗?) 439 | **问:为什么我的网络不收敛啊,LOSS是XXXX。 440 | 答:不同网络的LOSS不同,LOSS只是一个参考指标,用于查看网络是否收敛,而非评价网络好坏,我的yolo代码都没有归一化,所以LOSS值看起来比较高,LOSS的值不重要,重要的是是否在变小,预测是否有效果。** 441 | 442 | ### e、为什么我训练出来的模型没有预测结果? 443 | **问:为什么我的训练效果不好?预测了没有框(框不准)。 444 | 答:** 445 | **考虑几个问题: 446 | 1、数据集问题,这是最重要的问题。小于500的自行考虑增加数据集;一定要检查数据集的标签,视频中详细解析了VOC数据集的格式,但并不是有输入图片有输出标签即可,还需要确认标签的每一个像素值是否为它对应的种类。很多同学的标签格式不对,最常见的错误格式就是标签的背景为黑,目标为白,此时目标的像素点值为255,无法正常训练,目标需要为1才行。 447 | 2、是否解冻训练,如果数据集分布与常规画面差距过大需要进一步解冻训练,调整主干,加强特征提取能力。 448 | 3、网络问题,可以尝试不同的网络。 449 | 4、训练时长问题,有些同学只训练了几代表示没有效果,按默认参数训练完。 450 | 5、确认自己是否按照步骤去做了。 451 | 6、不同网络的LOSS不同,LOSS只是一个参考指标,用于查看网络是否收敛,而非评价网络好坏,LOSS的值不重要,重要的是是否收敛。** 452 | 453 | **问:为什么我的训练效果不好?对小目标预测不准确。 454 | 答:对于deeplab和pspnet而言,可以修改一下downsample_factor,当downsample_factor为16的时候下采样倍数过多,效果不太好,可以修改为8。** 455 | 456 | ### f、为什么我计算出来的miou是0? 457 | **问:为什么我的训练效果不好?计算出来的miou是0?。** 458 | 答: 459 | 与e类似,**考虑几个问题: 460 | 1、数据集问题,这是最重要的问题。小于500的自行考虑增加数据集;一定要检查数据集的标签,视频中详细解析了VOC数据集的格式,但并不是有输入图片有输出标签即可,还需要确认标签的每一个像素值是否为它对应的种类。很多同学的标签格式不对,最常见的错误格式就是标签的背景为黑,目标为白,此时目标的像素点值为255,无法正常训练,目标需要为1才行。 461 | 2、是否解冻训练,如果数据集分布与常规画面差距过大需要进一步解冻训练,调整主干,加强特征提取能力。 462 | 3、网络问题,可以尝试不同的网络。 463 | 4、训练时长问题,有些同学只训练了几代表示没有效果,按默认参数训练完。 464 | 5、确认自己是否按照步骤去做了。 465 | 6、不同网络的LOSS不同,LOSS只是一个参考指标,用于查看网络是否收敛,而非评价网络好坏,LOSS的值不重要,重要的是是否收敛。** 466 | 467 | ### g、gbk编码错误('gbk' codec can't decode byte)。 468 | **问:我怎么出现了gbk什么的编码错误啊:** 469 | ```python 470 | UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 446: illegal multibyte sequence 471 | ``` 472 | **答:标签和路径不要使用中文,如果一定要使用中文,请注意处理的时候编码的问题,改成打开文件的encoding方式改为utf-8。** 473 | 474 | ### h、我的图片是xxx*xxx的分辨率的,可以用吗? 475 | **问:我的图片是xxx*xxx的分辨率的,可以用吗!** 476 | **答:可以用,代码里面会自动进行resize与数据增强。** 477 | 478 | ### i、我想进行数据增强!怎么增强? 479 | **问:我想要进行数据增强!怎么做呢?** 480 | **答:可以用,代码里面会自动进行resize与数据增强。** 481 | 482 | ### j、多GPU训练。 483 | **问:怎么进行多GPU训练? 484 | 答:pytorch的大多数代码可以直接使用gpu训练,keras的话直接百度就好了,实现并不复杂,我没有多卡没法详细测试,还需要各位同学自己努力了。** 485 | 486 | ### k、能不能训练灰度图? 487 | **问:能不能训练灰度图(预测灰度图)啊? 488 | 答:我的大多数库会将灰度图转化成RGB进行训练和预测,如果遇到代码不能训练或者预测灰度图的情况,可以尝试一下在get_random_data里面将Image.open后的结果转换成RGB,预测的时候也这样试试。(仅供参考)** 489 | 490 | ### l、断点续练问题。 491 | **问:我已经训练过几个世代了,能不能从这个基础上继续开始训练 492 | 答:可以,你在训练前,和载入预训练权重一样载入训练过的权重就行了。一般训练好的权重会保存在logs文件夹里面,将model_path修改成你要开始的权值的路径即可。** 493 | 494 | ### m、我要训练其它的数据集,预训练权重能不能用? 495 | **问:如果我要训练其它的数据集,预训练权重要怎么办啊?** 496 | **答:数据的预训练权重对不同数据集是通用的,因为特征是通用的,预训练权重对于99%的情况都必须要用,不用的话权值太过随机,特征提取效果不明显,网络训练的结果也不会好。** 497 | 498 | ### n、网络如何从0开始训练? 499 | **问:我要怎么不使用预训练权重啊? 500 | 答:看一看注释、大多数代码是model_path = '',Freeze_Train = Fasle**,如果设置model_path无用,**那么把载入预训练权重的代码注释了就行。** 501 | 502 | ### o、为什么从0开始训练效果这么差(修改了网络主干,效果不好怎么办)? 503 | **问:为什么我不使用预训练权重效果这么差啊? 504 | 答:因为随机初始化的权值不好,提取的特征不好,也就导致了模型训练的效果不好,预训练权重还是非常重要的。** 505 | 506 | **问:up,我修改了网络,预训练权重还能用吗? 507 | 答:修改了主干的话,如果不是用的现有的网络,基本上预训练权重是不能用的,要么就自己判断权值里卷积核的shape然后自己匹配,要么只能自己预训练去了;修改了后半部分的话,前半部分的主干部分的预训练权重还是可以用的,如果是pytorch代码的话,需要自己修改一下载入权值的方式,判断shape后载入,如果是keras代码,直接by_name=True,skip_mismatch=True即可。** 508 | 权值匹配的方式可以参考如下: 509 | ```python 510 | # 加快模型训练的效率 511 | print('Loading weights into state dict...') 512 | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') 513 | model_dict = model.state_dict() 514 | pretrained_dict = torch.load(model_path, map_location=device) 515 | a = {} 516 | for k, v in pretrained_dict.items(): 517 | try: 518 | if np.shape(model_dict[k]) == np.shape(v): 519 | a[k]=v 520 | except: 521 | pass 522 | model_dict.update(a) 523 | model.load_state_dict(model_dict) 524 | print('Finished!') 525 | ``` 526 | 527 | **问:为什么从0开始训练效果这么差(我修改了网络主干,效果不好怎么办)? 528 | 答:一般来讲,网络从0开始的训练效果会很差,因为权值太过随机,特征提取效果不明显,因此非常、非常、非常不建议大家从0开始训练!如果一定要从0开始,可以了解imagenet数据集,首先训练分类模型,获得网络的主干部分权值,分类模型的 主干部分 和该模型通用,基于此进行训练。 529 | 网络修改了主干之后也是同样的问题,随机的权值效果很差。** 530 | 531 | **问:怎么在模型上从0开始训练? 532 | 答:在算力不足与调参能力不足的情况下从0开始训练毫无意义。模型特征提取能力在随机初始化参数的情况下非常差。没有好的参数调节能力和算力,无法使得网络正常收敛。** 533 | 如果一定要从0开始,那么训练的时候请注意几点: 534 | - 不载入预训练权重。 535 | - 不要进行冻结训练,注释冻结模型的代码。 536 | 537 | **问:为什么我不使用预训练权重效果这么差啊? 538 | 答:因为随机初始化的权值不好,提取的特征不好,也就导致了模型训练的效果不好,voc07+12、coco+voc07+12效果都不一样,预训练权重还是非常重要的。** 539 | 540 | ### p、你的权值都是哪里来的? 541 | **问:如果网络不能从0开始训练的话你的权值哪里来的? 542 | 答:有些权值是官方转换过来的,有些权值是自己训练出来的,我用到的主干的imagenet的权值都是官方的。** 543 | 544 | 545 | ### q、视频检测与摄像头检测 546 | **问:怎么用摄像头检测呀? 547 | 答:predict.py修改参数可以进行摄像头检测,也有视频详细解释了摄像头检测的思路。** 548 | 549 | **问:怎么用视频检测呀? 550 | 答:同上** 551 | 552 | ### r、如何保存检测出的图片 553 | **问:检测完的图片怎么保存? 554 | 答:一般目标检测用的是Image,所以查询一下PIL库的Image如何进行保存。详细看看predict.py文件的注释。** 555 | 556 | **问:怎么用视频保存呀? 557 | 答:详细看看predict.py文件的注释。** 558 | 559 | ### s、遍历问题 560 | **问:如何对一个文件夹的图片进行遍历? 561 | 答:一般使用os.listdir先找出文件夹里面的所有图片,然后根据predict.py文件里面的执行思路检测图片就行了,详细看看predict.py文件的注释。** 562 | 563 | **问:如何对一个文件夹的图片进行遍历?并且保存。 564 | 答:遍历的话一般使用os.listdir先找出文件夹里面的所有图片,然后根据predict.py文件里面的执行思路检测图片就行了。保存的话一般目标检测用的是Image,所以查询一下PIL库的Image如何进行保存。如果有些库用的是cv2,那就是查一下cv2怎么保存图片。详细看看predict.py文件的注释。** 565 | 566 | ### t、路径问题(No such file or directory、StopIteration: [Errno 13] Permission denied: 'XXXXXX') 567 | **问:我怎么出现了这样的错误呀:** 568 | ```python 569 | FileNotFoundError: 【Errno 2】 No such file or directory 570 | StopIteration: [Errno 13] Permission denied: 'D:\\Study\\Collection\\Dataset\\VOC07+12+test\\VOCdevkit/VOC2007' 571 | …………………………………… 572 | …………………………………… 573 | ``` 574 | **答:去检查一下文件夹路径,查看是否有对应文件;并且检查一下2007_train.txt,其中文件路径是否有错。** 575 | 关于路径有几个重要的点: 576 | **文件夹名称中一定不要有空格。 577 | 注意相对路径和绝对路径。 578 | 多百度路径相关的知识。** 579 | 580 | **所有的路径问题基本上都是根目录问题,好好查一下相对目录的概念!** 581 | ### u、和原版比较问题,你怎么和原版不一样啊? 582 | **问:原版的代码是XXX,为什么你的代码是XXX? 583 | 答:是啊……这要不怎么说我不是原版呢……** 584 | 585 | **问:你这个代码和原版比怎么样,可以达到原版的效果么? 586 | 答:基本上可以达到,我都用voc数据测过,我没有好显卡,没有能力在coco上测试与训练。** 587 | 588 | ### v、我的检测速度是xxx正常吗?我的检测速度还能增快吗? 589 | **问:你这个FPS可以到达多少,可以到 XX FPS么? 590 | 答:FPS和机子的配置有关,配置高就快,配置低就慢。** 591 | 592 | **问:我的检测速度是xxx正常吗?我的检测速度还能增快吗? 593 | 答:看配置,配置好速度就快,如果想要配置不变的情况下加快速度,就要修改网络了。** 594 | 595 | **问:为什么论文中说速度可以达到XX,但是这里却没有? 596 | 答:检查是否正确安装了tensorflow-gpu或者pytorch的gpu版本,如果已经正确安装,可以去利用time.time()的方法查看detect_image里面,哪一段代码耗时更长(不仅只有网络耗时长,其它处理部分也会耗时,如绘图等)。有些论文还会使用多batch进行预测,我并没有去实现这个部分。** 597 | 598 | ### w、预测图片不显示问题 599 | **问:为什么你的代码在预测完成后不显示图片?只是在命令行告诉我有什么目标。 600 | 答:给系统安装一个图片查看器就行了。** 601 | 602 | ### x、算法评价问题(miou) 603 | **问:怎么计算miou? 604 | 答:参考视频里的miou测量部分。** 605 | 606 | **问:怎么计算Recall、Precision指标。 607 | 答:现有的代码还无法获得,需要各位同学理解一下混淆矩阵的概念,然后自行计算一下。** 608 | 609 | ### y、UP,怎么优化模型啊?我想提升效果 610 | **问:up,怎么修改模型啊,我想发个小论文! 611 | 答:建议目标检测中的yolov4论文,作为一个大型调参现场非常有参考意义,使用了很多tricks。我能给的建议就是多看一些经典模型,然后拆解里面的亮点结构并使用。** 612 | 613 | ### z、部署问题(ONNX、TensorRT等) 614 | 我没有具体部署到手机等设备上过,所以很多部署问题我并不了解…… 615 | 616 | ## 5、交流群问题 617 | **问:up,有没有QQ群啥的呢? 618 | 答:没有没有,我没有时间管理QQ群……** 619 | 620 | ## 6、怎么学习的问题 621 | **问:up,你的学习路线怎么样的?我是个小白我要怎么学? 622 | 答:这里有几点需要注意哈 623 | 1、我不是高手,很多东西我也不会,我的学习路线也不一定适用所有人。 624 | 2、我实验室不做深度学习,所以我很多东西都是自学,自己摸索,正确与否我也不知道。 625 | 3、我个人觉得学习更靠自学** 626 | 学习路线的话,我是先学习了莫烦的python教程,从tensorflow、keras、pytorch入门,入门完之后学的SSD,YOLO,然后了解了很多经典的卷积网,后面就开始学很多不同的代码了,我的学习方法就是一行一行的看,了解整个代码的执行流程,特征层的shape变化等,花了很多时间也没有什么捷径,就是要花时间吧。 627 | --------------------------------------------------------------------------------