├── nets ├── __init__.py ├── yolo.py ├── CSPdarknet.py └── yolo_training.py ├── utils ├── __init__.py ├── callbacks.py ├── utils.py ├── utils_bbox.py └── dataloader.py ├── logs └── README.md ├── VOCdevkit └── VOC2007 │ ├── Annotations │ └── README.md │ ├── JPEGImages │ └── README.md │ └── ImageSets │ └── Main │ └── README.md ├── img └── street.jpg ├── model_data ├── yolo_anchors.txt ├── simhei.ttf ├── voc_classes.txt └── coco_classes.txt ├── requirements.txt ├── summary.py ├── .gitignore ├── utils_coco ├── get_map_coco.py └── coco_annotation.py ├── voc_annotation.py ├── get_map.py ├── kmeans_for_anchors.py ├── predict.py ├── README.md ├── yolo.py ├── train.py └── 常见问题汇总.md /nets/__init__.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------------------------------- /logs/README.md: -------------------------------------------------------------------------------- 1 | 训练好的权重会保存在这里 2 | -------------------------------------------------------------------------------- /VOCdevkit/VOC2007/Annotations/README.md: -------------------------------------------------------------------------------- 1 | 存放标签文件 -------------------------------------------------------------------------------- /VOCdevkit/VOC2007/JPEGImages/README.md: -------------------------------------------------------------------------------- 1 | 存放图片文件 -------------------------------------------------------------------------------- /VOCdevkit/VOC2007/ImageSets/Main/README.md: -------------------------------------------------------------------------------- 1 | 存放训练索引文件 -------------------------------------------------------------------------------- /img/street.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bubbliiiing/yolov5-keras/HEAD/img/street.jpg -------------------------------------------------------------------------------- /model_data/yolo_anchors.txt: -------------------------------------------------------------------------------- 1 | 10,13, 16,30, 33,23, 30,61, 62,45, 59,119, 116,90, 156,198, 373,326 -------------------------------------------------------------------------------- /model_data/simhei.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bubbliiiing/yolov5-keras/HEAD/model_data/simhei.ttf -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | scipy==1.2.1 2 | numpy==1.17.0 3 | Keras==2.1.5 4 | matplotlib==3.1.2 5 | opencv_python==4.1.2.30 6 | tensorflow_gpu==1.13.2 7 | tqdm==4.60.0 8 | Pillow==8.2.0 9 | h5py==2.10.0 10 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 = [640, 640, 3] 9 | anchors_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]] 10 | num_classes = 80 11 | phi = 'l' 12 | 13 | model = yolo_body(input_shape, anchors_mask, num_classes, 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /utils_coco/get_map_coco.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | 4 | import numpy as np 5 | from keras import backend as K 6 | from PIL import Image 7 | from pycocotools.coco import COCO 8 | from pycocotools.cocoeval import COCOeval 9 | from tqdm import tqdm 10 | 11 | from utils.utils import cvtColor, preprocess_input, resize_image 12 | from yolo import YOLO 13 | 14 | #----------------------------------------------------------------------------# 15 | # map_mode用于指定该文件运行时计算的内容 16 | # map_mode为0代表整个map计算流程,包括获得预测结果、计算map。 17 | # map_mode为1代表仅仅获得预测结果。 18 | # map_mode为2代表仅仅获得计算map。 19 | #--------------------------------------------------------------------------# 20 | map_mode = 0 21 | #-------------------------------------------------------# 22 | # 指向了验证集标签与图片路径 23 | #-------------------------------------------------------# 24 | cocoGt_path = 'coco_dataset/annotations/instances_val2017.json' 25 | dataset_img_path = 'coco_dataset/val2017' 26 | #-------------------------------------------------------# 27 | # 结果输出的文件夹,默认为map_out 28 | #-------------------------------------------------------# 29 | temp_save_path = 'map_out/coco_eval' 30 | 31 | class mAP_YOLO(YOLO): 32 | #---------------------------------------------------# 33 | # 检测图片 34 | #---------------------------------------------------# 35 | def detect_image(self, image_id, image, results, clsid2catid): 36 | #---------------------------------------------------------# 37 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 38 | # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB 39 | #---------------------------------------------------------# 40 | image = cvtColor(image) 41 | #---------------------------------------------------------# 42 | # 给图像增加灰条,实现不失真的resize 43 | # 也可以直接resize进行识别 44 | #---------------------------------------------------------# 45 | image_data = resize_image(image, (self.input_shape[1], self.input_shape[0]), self.letterbox_image) 46 | #---------------------------------------------------------# 47 | # 添加上batch_size维度,并进行归一化 48 | #---------------------------------------------------------# 49 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 50 | 51 | out_boxes, out_scores, out_classes = self.sess.run( 52 | [self.boxes, self.scores, self.classes], 53 | feed_dict={ 54 | self.yolo_model.input: image_data, 55 | self.input_image_shape: [image.size[1], image.size[0]], 56 | K.learning_phase(): 0 57 | }) 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.") 97 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /nets/yolo.py: -------------------------------------------------------------------------------- 1 | from keras.layers import (Concatenate, Input, Lambda, UpSampling2D, 2 | ZeroPadding2D) 3 | from keras.models import Model 4 | 5 | from nets.CSPdarknet import (C3, DarknetConv2D, DarknetConv2D_BN_SiLU, 6 | darknet_body) 7 | from nets.yolo_training import yolo_loss 8 | 9 | 10 | #---------------------------------------------------# 11 | # Panet网络的构建,并且获得预测结果 12 | #---------------------------------------------------# 13 | def yolo_body(input_shape, anchors_mask, num_classes, phi): 14 | depth_dict = {'s' : 0.33, 'm' : 0.67, 'l' : 1.00, 'x' : 1.33,} 15 | width_dict = {'s' : 0.50, 'm' : 0.75, 'l' : 1.00, 'x' : 1.25,} 16 | dep_mul, wid_mul = depth_dict[phi], width_dict[phi] 17 | 18 | base_channels = int(wid_mul * 64) # 64 19 | base_depth = max(round(dep_mul * 3), 1) # 3 20 | 21 | inputs = Input(input_shape) 22 | #---------------------------------------------------# 23 | # 生成主干模型,获得三个有效特征层,他们的shape分别是: 24 | # 80, 80, 256 25 | # 40, 40, 512 26 | # 20, 20, 1024 27 | #---------------------------------------------------# 28 | feat1, feat2, feat3 = darknet_body(inputs, base_channels, base_depth) 29 | 30 | # 20, 20, 1024 -> 20, 20, 512 31 | P5 = DarknetConv2D_BN_SiLU(int(base_channels * 8), (1, 1), name = 'conv_for_feat3')(feat3) 32 | # 20, 20, 512 -> 40, 40, 512 33 | P5_upsample = UpSampling2D()(P5) 34 | # 40, 40, 512 cat 40, 40, 512 -> 40, 40, 1024 35 | P5_upsample = Concatenate(axis = -1)([P5_upsample, feat2]) 36 | # 40, 40, 1024 -> 40, 40, 512 37 | P5_upsample = C3(P5_upsample, int(base_channels * 8), base_depth, shortcut = False, name = 'conv3_for_upsample1') 38 | 39 | # 40, 40, 512 -> 40, 40, 256 40 | P4 = DarknetConv2D_BN_SiLU(int(base_channels * 4), (1, 1), name = 'conv_for_feat2')(P5_upsample) 41 | # 40, 40, 256 -> 80, 80, 256 42 | P4_upsample = UpSampling2D()(P4) 43 | # 80, 80, 256 cat 80, 80, 256 -> 80, 80, 512 44 | P4_upsample = Concatenate(axis = -1)([P4_upsample, feat1]) 45 | # 80, 80, 512 -> 80, 80, 256 46 | P3_out = C3(P4_upsample, int(base_channels * 4), base_depth, shortcut = False, name = 'conv3_for_upsample2') 47 | 48 | # 80, 80, 256 -> 40, 40, 256 49 | P3_downsample = ZeroPadding2D(((1, 0),(1, 0)))(P3_out) 50 | P3_downsample = DarknetConv2D_BN_SiLU(int(base_channels * 4), (3, 3), strides = (2, 2), name = 'down_sample1')(P3_downsample) 51 | # 40, 40, 256 cat 40, 40, 256 -> 40, 40, 512 52 | P3_downsample = Concatenate(axis = -1)([P3_downsample, P4]) 53 | # 40, 40, 512 -> 40, 40, 512 54 | P4_out = C3(P3_downsample, int(base_channels * 8), base_depth, shortcut = False, name = 'conv3_for_downsample1') 55 | 56 | # 40, 40, 512 -> 20, 20, 512 57 | P4_downsample = ZeroPadding2D(((1, 0),(1, 0)))(P4_out) 58 | P4_downsample = DarknetConv2D_BN_SiLU(int(base_channels * 8), (3, 3), strides = (2, 2), name = 'down_sample2')(P4_downsample) 59 | # 20, 20, 512 cat 20, 20, 512 -> 20, 20, 1024 60 | P4_downsample = Concatenate(axis = -1)([P4_downsample, P5]) 61 | # 20, 20, 1024 -> 20, 20, 1024 62 | P5_out = C3(P4_downsample, int(base_channels * 16), base_depth, shortcut = False, name = 'conv3_for_downsample2') 63 | 64 | # len(anchors_mask[2]) = 3 65 | # 5 + num_classes -> 4 + 1 + num_classes 66 | # 4是先验框的回归系数,1是sigmoid将值固定到0-1,num_classes用于判断先验框是什么类别的物体 67 | # bs, 20, 20, 3 * (4 + 1 + num_classes) 68 | out2 = DarknetConv2D(len(anchors_mask[2]) * (5 + num_classes), (1, 1), strides = (1, 1), name = 'yolo_head_P3')(P3_out) 69 | out1 = DarknetConv2D(len(anchors_mask[1]) * (5 + num_classes), (1, 1), strides = (1, 1), name = 'yolo_head_P4')(P4_out) 70 | out0 = DarknetConv2D(len(anchors_mask[0]) * (5 + num_classes), (1, 1), strides = (1, 1), name = 'yolo_head_P5')(P5_out) 71 | return Model(inputs, [out0, out1, out2]) 72 | 73 | def get_train_model(model_body, input_shape, num_classes, anchors, anchors_mask, label_smoothing): 74 | y_true = [Input(shape = (input_shape[0] // {0:32, 1:16, 2:8}[l], input_shape[1] // {0:32, 1:16, 2:8}[l], \ 75 | len(anchors_mask[l]), num_classes + 5)) for l in range(len(anchors_mask))] 76 | model_loss = Lambda( 77 | yolo_loss, 78 | output_shape = (1, ), 79 | name = 'yolo_loss', 80 | arguments = { 81 | 'input_shape' : input_shape, 82 | 'anchors' : anchors, 83 | 'anchors_mask' : anchors_mask, 84 | 'num_classes' : num_classes, 85 | 'label_smoothing' : label_smoothing, 86 | 'balance' : [0.4, 1.0, 4], 87 | 'box_ratio' : 0.05, 88 | 'obj_ratio' : 1 * (input_shape[0] * input_shape[1]) / (640 ** 2), 89 | 'cls_ratio' : 0.5 * (num_classes / 80) 90 | } 91 | )([*model_body.output, *y_true]) 92 | model = Model([model_body.input, *y_true], model_loss) 93 | return model 94 | -------------------------------------------------------------------------------- /nets/CSPdarknet.py: -------------------------------------------------------------------------------- 1 | from functools import wraps 2 | 3 | import tensorflow as tf 4 | from keras import backend as K 5 | from keras.initializers import random_normal 6 | from keras.layers import (Add, BatchNormalization, Concatenate, Conv2D, Layer, 7 | MaxPooling2D, ZeroPadding2D) 8 | from keras.layers.normalization import BatchNormalization 9 | from keras.regularizers import l2 10 | from utils.utils import compose 11 | 12 | 13 | class SiLU(Layer): 14 | def __init__(self, **kwargs): 15 | super(SiLU, self).__init__(**kwargs) 16 | self.supports_masking = True 17 | 18 | def call(self, inputs): 19 | return inputs * K.sigmoid(inputs) 20 | 21 | def get_config(self): 22 | config = super(SiLU, self).get_config() 23 | return config 24 | 25 | def compute_output_shape(self, input_shape): 26 | return input_shape 27 | 28 | class Focus(Layer): 29 | def __init__(self): 30 | super(Focus, self).__init__() 31 | 32 | def compute_output_shape(self, input_shape): 33 | return (input_shape[0], input_shape[1] // 2 if input_shape[1] != None else input_shape[1], input_shape[2] // 2 if input_shape[2] != None else input_shape[2], input_shape[3] * 4) 34 | 35 | def call(self, x): 36 | return tf.concat( 37 | [x[..., ::2, ::2, :], 38 | x[..., 1::2, ::2, :], 39 | x[..., ::2, 1::2, :], 40 | x[..., 1::2, 1::2, :]], 41 | axis=-1 42 | ) 43 | 44 | #------------------------------------------------------# 45 | # 单次卷积DarknetConv2D 46 | # 如果步长为2则自己设定padding方式。 47 | #------------------------------------------------------# 48 | @wraps(Conv2D) 49 | def DarknetConv2D(*args, **kwargs): 50 | darknet_conv_kwargs = {'kernel_initializer' : random_normal(stddev=0.02)} 51 | darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides')==(2, 2) else 'same' 52 | darknet_conv_kwargs.update(kwargs) 53 | return Conv2D(*args, **darknet_conv_kwargs) 54 | 55 | #---------------------------------------------------# 56 | # 卷积块 -> 卷积 + 标准化 + 激活函数 57 | # DarknetConv2D + BatchNormalization + SiLU 58 | #---------------------------------------------------# 59 | def DarknetConv2D_BN_SiLU(*args, **kwargs): 60 | no_bias_kwargs = {'use_bias': False} 61 | no_bias_kwargs.update(kwargs) 62 | if "name" in kwargs.keys(): 63 | no_bias_kwargs['name'] = kwargs['name'] + '.conv' 64 | return compose( 65 | DarknetConv2D(*args, **no_bias_kwargs), 66 | BatchNormalization(momentum = 0.97, epsilon = 0.001, name = kwargs['name'] + '.bn'), 67 | SiLU()) 68 | 69 | def Bottleneck(x, out_channels, shortcut=True, name = ""): 70 | y = compose( 71 | DarknetConv2D_BN_SiLU(out_channels, (1, 1), name = name + '.cv1'), 72 | DarknetConv2D_BN_SiLU(out_channels, (3, 3), name = name + '.cv2'))(x) 73 | if shortcut: 74 | y = Add()([x, y]) 75 | return y 76 | 77 | def C3(x, num_filters, num_blocks, shortcut=True, expansion=0.5, name=""): 78 | hidden_channels = int(num_filters * expansion) 79 | #----------------------------------------------------------------# 80 | # 主干部分会对num_blocks进行循环,循环内部是残差结构。 81 | #----------------------------------------------------------------# 82 | x_1 = DarknetConv2D_BN_SiLU(hidden_channels, (1, 1), name = name + '.cv1')(x) 83 | #--------------------------------------------------------------------# 84 | # 然后建立一个大的残差边shortconv、这个大残差边绕过了很多的残差结构 85 | #--------------------------------------------------------------------# 86 | x_2 = DarknetConv2D_BN_SiLU(hidden_channels, (1, 1), name = name + '.cv2')(x) 87 | for i in range(num_blocks): 88 | x_1 = Bottleneck(x_1, hidden_channels, shortcut=shortcut, name = name + '.m.' + str(i)) 89 | #----------------------------------------------------------------# 90 | # 将大残差边再堆叠回来 91 | #----------------------------------------------------------------# 92 | route = Concatenate()([x_1, x_2]) 93 | 94 | #----------------------------------------------------------------# 95 | # 最后对通道数进行整合 96 | #----------------------------------------------------------------# 97 | return DarknetConv2D_BN_SiLU(num_filters, (1, 1), name = name + '.cv3')(route) 98 | 99 | def SPPBottleneck(x, out_channels, name = ""): 100 | #---------------------------------------------------# 101 | # 使用了SPP结构,即不同尺度的最大池化后堆叠。 102 | #---------------------------------------------------# 103 | x = DarknetConv2D_BN_SiLU(out_channels // 2, (1, 1), name = name + '.cv1')(x) 104 | maxpool1 = MaxPooling2D(pool_size=(5, 5), strides=(1, 1), padding='same')(x) 105 | maxpool2 = MaxPooling2D(pool_size=(9, 9), strides=(1, 1), padding='same')(x) 106 | maxpool3 = MaxPooling2D(pool_size=(13, 13), strides=(1, 1), padding='same')(x) 107 | x = Concatenate()([x, maxpool1, maxpool2, maxpool3]) 108 | x = DarknetConv2D_BN_SiLU(out_channels, (1, 1), name = name + '.cv2')(x) 109 | return x 110 | 111 | def resblock_body(x, num_filters, num_blocks, expansion=0.5, shortcut=True, last=False, name = ""): 112 | #----------------------------------------------------------------# 113 | # 利用ZeroPadding2D和一个步长为2x2的卷积块进行高和宽的压缩 114 | #----------------------------------------------------------------# 115 | 116 | # 320, 320, 64 => 160, 160, 128 117 | x = ZeroPadding2D(((1, 0),(1, 0)))(x) 118 | x = DarknetConv2D_BN_SiLU(num_filters, (3, 3), strides = (2, 2), name = name + '.0')(x) 119 | if last: 120 | x = SPPBottleneck(x, num_filters, name = name + '.1') 121 | return C3(x, num_filters, num_blocks, shortcut=shortcut, expansion=expansion, name = name + '.1' if not last else name + '.2') 122 | 123 | #---------------------------------------------------# 124 | # CSPdarknet的主体部分 125 | # 输入为一张640x640x3的图片 126 | # 输出为三个有效特征层 127 | #---------------------------------------------------# 128 | def darknet_body(x, base_channels, base_depth): 129 | #---------------------------------------------------# 130 | # base_channels 默认值为64 131 | #---------------------------------------------------# 132 | # 640, 640, 3 => 320, 320, 12 133 | x = Focus()(x) 134 | # 320, 320, 12 => 320, 320, 64 135 | x = DarknetConv2D_BN_SiLU(base_channels, (3, 3), name = 'backbone.stem.conv')(x) 136 | 137 | # 320, 320, 64 => 160, 160, 128 138 | x = resblock_body(x, base_channels * 2, base_depth, name = 'backbone.dark2') 139 | 140 | # 160, 160, 128 => 80, 80, 256 141 | x = resblock_body(x, base_channels * 4, base_depth * 3, name = 'backbone.dark3') 142 | feat1 = x 143 | 144 | # 80, 80, 256 => 40, 40, 512 145 | x = resblock_body(x, base_channels * 8, base_depth * 3, name = 'backbone.dark4') 146 | feat2 = x 147 | 148 | # 40, 40, 512 => 20, 20, 1024 149 | x = resblock_body(x, base_channels * 16, base_depth, shortcut=False, last=True, name = 'backbone.dark5') 150 | feat3 = x 151 | return feat1, feat2, feat3 152 | 153 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /get_map.py: -------------------------------------------------------------------------------- 1 | import os 2 | import xml.etree.ElementTree as ET 3 | 4 | from PIL import Image 5 | from tqdm import tqdm 6 | 7 | from yolo import YOLO 8 | from utils.utils import get_classes 9 | from utils.utils_map import get_coco_map, get_map 10 | 11 | if __name__ == "__main__": 12 | ''' 13 | Recall和Precision不像AP是一个面积的概念,因此在门限值(Confidence)不同时,网络的Recall和Precision值是不同的。 14 | 默认情况下,本代码计算的Recall和Precision代表的是当门限值(Confidence)为0.5时,所对应的Recall和Precision值。 15 | 16 | 受到mAP计算原理的限制,网络在计算mAP时需要获得近乎所有的预测框,这样才可以计算不同门限条件下的Recall和Precision值 17 | 因此,本代码获得的map_out/detection-results/里面的txt的框的数量一般会比直接predict多一些,目的是列出所有可能的预测框, 18 | ''' 19 | #------------------------------------------------------------------------------------------------------------------# 20 | # map_mode用于指定该文件运行时计算的内容 21 | # map_mode为0代表整个map计算流程,包括获得预测结果、获得真实框、计算VOC_map。 22 | # map_mode为1代表仅仅获得预测结果。 23 | # map_mode为2代表仅仅获得真实框。 24 | # map_mode为3代表仅仅计算VOC_map。 25 | # map_mode为4代表利用COCO工具箱计算当前数据集的0.50:0.95map。需要获得预测结果、获得真实框后并安装pycocotools才行 26 | #-------------------------------------------------------------------------------------------------------------------# 27 | map_mode = 0 28 | #--------------------------------------------------------------------------------------# 29 | # 此处的classes_path用于指定需要测量VOC_map的类别 30 | # 一般情况下与训练和预测所用的classes_path一致即可 31 | #--------------------------------------------------------------------------------------# 32 | classes_path = 'model_data/voc_classes.txt' 33 | #--------------------------------------------------------------------------------------# 34 | # MINOVERLAP用于指定想要获得的mAP0.x,mAP0.x的意义是什么请同学们百度一下。 35 | # 比如计算mAP0.75,可以设定MINOVERLAP = 0.75。 36 | # 37 | # 当某一预测框与真实框重合度大于MINOVERLAP时,该预测框被认为是正样本,否则为负样本。 38 | # 因此MINOVERLAP的值越大,预测框要预测的越准确才能被认为是正样本,此时算出来的mAP值越低, 39 | #--------------------------------------------------------------------------------------# 40 | MINOVERLAP = 0.5 41 | #--------------------------------------------------------------------------------------# 42 | # 受到mAP计算原理的限制,网络在计算mAP时需要获得近乎所有的预测框,这样才可以计算mAP 43 | # 因此,confidence的值应当设置的尽量小进而获得全部可能的预测框。 44 | # 45 | # 该值一般不调整。因为计算mAP需要获得近乎所有的预测框,此处的confidence不能随便更改。 46 | # 想要获得不同门限值下的Recall和Precision值,请修改下方的score_threhold。 47 | #--------------------------------------------------------------------------------------# 48 | confidence = 0.001 49 | #--------------------------------------------------------------------------------------# 50 | # 预测时使用到的非极大抑制值的大小,越大表示非极大抑制越不严格。 51 | # 52 | # 该值一般不调整。 53 | #--------------------------------------------------------------------------------------# 54 | nms_iou = 0.5 55 | #---------------------------------------------------------------------------------------------------------------# 56 | # Recall和Precision不像AP是一个面积的概念,因此在门限值不同时,网络的Recall和Precision值是不同的。 57 | # 58 | # 默认情况下,本代码计算的Recall和Precision代表的是当门限值为0.5(此处定义为score_threhold)时所对应的Recall和Precision值。 59 | # 因为计算mAP需要获得近乎所有的预测框,上面定义的confidence不能随便更改。 60 | # 这里专门定义一个score_threhold用于代表门限值,进而在计算mAP时找到门限值对应的Recall和Precision值。 61 | #---------------------------------------------------------------------------------------------------------------# 62 | score_threhold = 0.5 63 | #-------------------------------------------------------# 64 | # map_vis用于指定是否开启VOC_map计算的可视化 65 | #-------------------------------------------------------# 66 | map_vis = False 67 | #-------------------------------------------------------# 68 | # 指向VOC数据集所在的文件夹 69 | # 默认指向根目录下的VOC数据集 70 | #-------------------------------------------------------# 71 | VOCdevkit_path = 'VOCdevkit' 72 | #-------------------------------------------------------# 73 | # 结果输出的文件夹,默认为map_out 74 | #-------------------------------------------------------# 75 | map_out_path = 'map_out' 76 | 77 | image_ids = open(os.path.join(VOCdevkit_path, "VOC2007/ImageSets/Main/test.txt")).read().strip().split() 78 | 79 | if not os.path.exists(map_out_path): 80 | os.makedirs(map_out_path) 81 | if not os.path.exists(os.path.join(map_out_path, 'ground-truth')): 82 | os.makedirs(os.path.join(map_out_path, 'ground-truth')) 83 | if not os.path.exists(os.path.join(map_out_path, 'detection-results')): 84 | os.makedirs(os.path.join(map_out_path, 'detection-results')) 85 | if not os.path.exists(os.path.join(map_out_path, 'images-optional')): 86 | os.makedirs(os.path.join(map_out_path, 'images-optional')) 87 | 88 | class_names, _ = get_classes(classes_path) 89 | 90 | if map_mode == 0 or map_mode == 1: 91 | print("Load model.") 92 | yolo = YOLO(confidence = confidence, nms_iou = nms_iou) 93 | print("Load model done.") 94 | 95 | print("Get predict result.") 96 | for image_id in tqdm(image_ids): 97 | image_path = os.path.join(VOCdevkit_path, "VOC2007/JPEGImages/"+image_id+".jpg") 98 | image = Image.open(image_path) 99 | if map_vis: 100 | image.save(os.path.join(map_out_path, "images-optional/" + image_id + ".jpg")) 101 | yolo.get_map_txt(image_id, image, class_names, map_out_path) 102 | print("Get predict result done.") 103 | 104 | if map_mode == 0 or map_mode == 2: 105 | print("Get ground truth result.") 106 | for image_id in tqdm(image_ids): 107 | with open(os.path.join(map_out_path, "ground-truth/"+image_id+".txt"), "w") as new_f: 108 | root = ET.parse(os.path.join(VOCdevkit_path, "VOC2007/Annotations/"+image_id+".xml")).getroot() 109 | for obj in root.findall('object'): 110 | difficult_flag = False 111 | if obj.find('difficult')!=None: 112 | difficult = obj.find('difficult').text 113 | if int(difficult)==1: 114 | difficult_flag = True 115 | obj_name = obj.find('name').text 116 | if obj_name not in class_names: 117 | continue 118 | bndbox = obj.find('bndbox') 119 | left = bndbox.find('xmin').text 120 | top = bndbox.find('ymin').text 121 | right = bndbox.find('xmax').text 122 | bottom = bndbox.find('ymax').text 123 | 124 | if difficult_flag: 125 | new_f.write("%s %s %s %s %s difficult\n" % (obj_name, left, top, right, bottom)) 126 | else: 127 | new_f.write("%s %s %s %s %s\n" % (obj_name, left, top, right, bottom)) 128 | print("Get ground truth result done.") 129 | 130 | if map_mode == 0 or map_mode == 3: 131 | print("Get map.") 132 | get_map(MINOVERLAP, True, score_threhold = score_threhold, path = map_out_path) 133 | print("Get map done.") 134 | 135 | if map_mode == 4: 136 | print("Get map.") 137 | get_coco_map(class_names = class_names, path = map_out_path) 138 | print("Get map done.") 139 | -------------------------------------------------------------------------------- /kmeans_for_anchors.py: -------------------------------------------------------------------------------- 1 | #-------------------------------------------------------------------------------------------------------# 2 | # kmeans虽然会对数据集中的框进行聚类,但是很多数据集由于框的大小相近,聚类出来的9个框相差不大, 3 | # 这样的框反而不利于模型的训练。因为不同的特征层适合不同大小的先验框,shape越小的特征层适合越大的先验框 4 | # 原始网络的先验框已经按大中小比例分配好了,不进行聚类也会有非常好的效果。 5 | #-------------------------------------------------------------------------------------------------------# 6 | from PIL import Image 7 | 8 | import matplotlib.pyplot as plt 9 | import numpy as np 10 | from tqdm import tqdm 11 | 12 | if __name__ == '__main__': 13 | #-------------------------------------------------------------# 14 | # input_shape 输入的shape大小,一定要是32的倍数 15 | #-------------------------------------------------------------# 16 | input_shape = [640, 640] 17 | #-------------------------------------------------------------# 18 | # anchors_num 先验框的数量 19 | #-------------------------------------------------------------# 20 | anchors_num = 9 21 | #-------------------------------------------------------------# 22 | # train_annotation_path 训练图片路径和标签 23 | #-------------------------------------------------------------# 24 | train_annotation_path = '2007_train.txt' 25 | 26 | np.random.seed(0) 27 | 28 | def cas_ratio(box,cluster): 29 | ratios_of_box_cluster = box / cluster 30 | ratios_of_cluster_box = cluster / box 31 | ratios = np.concatenate([ratios_of_box_cluster, ratios_of_cluster_box], axis = -1) 32 | return np.max(ratios, -1) 33 | 34 | def avg_ratio(box,cluster): 35 | return np.mean([np.min(cas_ratio(box[i],cluster)) for i in range(box.shape[0])]) 36 | 37 | def kmeans(box,k): 38 | #-------------------------------------------------------------# 39 | # 取出一共有多少框 40 | #-------------------------------------------------------------# 41 | row = box.shape[0] 42 | 43 | #-------------------------------------------------------------# 44 | # 每个框各个点的位置 45 | #-------------------------------------------------------------# 46 | distance = np.empty((row,k)) 47 | 48 | #-------------------------------------------------------------# 49 | # 最后的聚类位置 50 | #-------------------------------------------------------------# 51 | last_clu = np.zeros((row,)) 52 | 53 | np.random.seed() 54 | 55 | #-------------------------------------------------------------# 56 | # 随机选5个当聚类中心 57 | #-------------------------------------------------------------# 58 | cluster = box[np.random.choice(row,k,replace = False)] 59 | 60 | iter = 0 61 | while True: 62 | #-------------------------------------------------------------# 63 | # 计算当前框和先验框的宽高比例 64 | #-------------------------------------------------------------# 65 | for i in range(row): 66 | distance[i] = cas_ratio(box[i],cluster) 67 | 68 | #-------------------------------------------------------------# 69 | # 取出最小点 70 | #-------------------------------------------------------------# 71 | near = np.argmin(distance,axis=1) 72 | 73 | if (last_clu == near).all(): 74 | break 75 | 76 | #-------------------------------------------------------------# 77 | # 求每一个类的中位点 78 | #-------------------------------------------------------------# 79 | for j in range(k): 80 | cluster[j] = np.median( 81 | box[near == j],axis=0) 82 | 83 | last_clu = near 84 | if iter % 5 == 0: 85 | print('iter: {:d}. avg_ratio:{:.2f}'.format(iter, avg_ratio(box,cluster))) 86 | iter += 1 87 | 88 | return cluster, near 89 | 90 | def load_data(train_annotation_path): 91 | #---------------------------# 92 | # 读取数据集对应的txt 93 | #---------------------------# 94 | with open(train_annotation_path, encoding='utf-8') as f: 95 | train_lines = f.readlines() 96 | 97 | data = [] 98 | #-------------------------------------------------------------# 99 | # 对于每一个xml都寻找box 100 | #-------------------------------------------------------------# 101 | for line in tqdm(train_lines): 102 | line = line.split() 103 | #------------------------------# 104 | # 读取图像并转换成RGB图像 105 | #------------------------------# 106 | image = Image.open(line[0]) 107 | #------------------------------# 108 | # 获得图像的高宽与目标高宽 109 | #------------------------------# 110 | iw, ih = image.size 111 | #------------------------------# 112 | # 获得预测框 113 | #------------------------------# 114 | boxes = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) 115 | for box in boxes: 116 | xmin = int(float(box[0])) / iw 117 | ymin = int(float(box[1])) / ih 118 | xmax = int(float(box[2])) / iw 119 | ymax = int(float(box[3])) / ih 120 | 121 | xmin = np.float64(xmin) 122 | ymin = np.float64(ymin) 123 | xmax = np.float64(xmax) 124 | ymax = np.float64(ymax) 125 | # 得到宽高 126 | data.append([xmax - xmin, ymax - ymin]) 127 | 128 | return np.array(data) 129 | 130 | #-------------------------------------------------------------# 131 | # 载入所有的xml 132 | # 存储格式为转化为比例后的width,height 133 | #-------------------------------------------------------------# 134 | print('Load xmls.') 135 | data = load_data(train_annotation_path) 136 | print('Load xmls done.') 137 | 138 | #-------------------------------------------------------------# 139 | # 使用k聚类算法 140 | #-------------------------------------------------------------# 141 | print('K-means boxes.') 142 | cluster, near = kmeans(data, anchors_num) 143 | print('K-means boxes done.') 144 | data = data * np.array([input_shape[1], input_shape[0]]) 145 | cluster = cluster * np.array([input_shape[1], input_shape[0]]) 146 | 147 | #-------------------------------------------------------------# 148 | # 绘图 149 | #-------------------------------------------------------------# 150 | for j in range(anchors_num): 151 | plt.scatter(data[near == j][:,0], data[near == j][:,1]) 152 | plt.scatter(cluster[j][0], cluster[j][1], marker='x', c='black') 153 | plt.savefig("kmeans_for_anchors.jpg") 154 | plt.show() 155 | print('Save kmeans_for_anchors.jpg in root dir.') 156 | 157 | cluster = cluster[np.argsort(cluster[:, 0] * cluster[:, 1])] 158 | print('avg_ratio:{:.2f}'.format(avg_ratio(data, cluster))) 159 | print(cluster) 160 | 161 | f = open("yolo_anchors.txt", 'w') 162 | row = np.shape(cluster)[0] 163 | for i in range(row): 164 | if i == 0: 165 | x_y = "%d,%d" % (cluster[i][0], cluster[i][1]) 166 | else: 167 | x_y = ", %d,%d" % (cluster[i][0], cluster[i][1]) 168 | f.write(x_y) 169 | f.close() 170 | -------------------------------------------------------------------------------- /predict.py: -------------------------------------------------------------------------------- 1 | #-----------------------------------------------------------------------# 2 | # predict.py将单张图片预测、摄像头检测、FPS测试和目录遍历检测等功能 3 | # 整合到了一个py文件中,通过指定mode进行模式的修改。 4 | #-----------------------------------------------------------------------# 5 | import time 6 | 7 | import cv2 8 | import numpy as np 9 | from PIL import Image 10 | 11 | from yolo import YOLO 12 | 13 | if __name__ == "__main__": 14 | yolo = YOLO() 15 | #----------------------------------------------------------------------------------------------------------# 16 | # mode用于指定测试的模式: 17 | # 'predict' 表示单张图片预测,如果想对预测过程进行修改,如保存图片,截取对象等,可以先看下方详细的注释 18 | # 'video' 表示视频检测,可调用摄像头或者视频进行检测,详情查看下方注释。 19 | # 'fps' 表示测试fps,使用的图片是img里面的street.jpg,详情查看下方注释。 20 | # 'dir_predict' 表示遍历文件夹进行检测并保存。默认遍历img文件夹,保存img_out文件夹,详情查看下方注释。 21 | # 'heatmap' 表示进行预测结果的热力图可视化,详情查看下方注释。 22 | #----------------------------------------------------------------------------------------------------------# 23 | mode = "predict" 24 | #-------------------------------------------------------------------------# 25 | # crop 指定了是否在单张图片预测后对目标进行截取 26 | # count 指定了是否进行目标的计数 27 | # crop、count仅在mode='predict'时有效 28 | #-------------------------------------------------------------------------# 29 | crop = False 30 | count = False 31 | #----------------------------------------------------------------------------------------------------------# 32 | # video_path 用于指定视频的路径,当video_path=0时表示检测摄像头 33 | # 想要检测视频,则设置如video_path = "xxx.mp4"即可,代表读取出根目录下的xxx.mp4文件。 34 | # video_save_path 表示视频保存的路径,当video_save_path=""时表示不保存 35 | # 想要保存视频,则设置如video_save_path = "yyy.mp4"即可,代表保存为根目录下的yyy.mp4文件。 36 | # video_fps 用于保存的视频的fps 37 | # 38 | # video_path、video_save_path和video_fps仅在mode='video'时有效 39 | # 保存视频时需要ctrl+c退出或者运行到最后一帧才会完成完整的保存步骤。 40 | #----------------------------------------------------------------------------------------------------------# 41 | video_path = 0 42 | video_save_path = "" 43 | video_fps = 25.0 44 | #----------------------------------------------------------------------------------------------------------# 45 | # test_interval 用于指定测量fps的时候,图片检测的次数。理论上test_interval越大,fps越准确。 46 | # fps_image_path 用于指定测试的fps图片 47 | # 48 | # test_interval和fps_image_path仅在mode='fps'有效 49 | #----------------------------------------------------------------------------------------------------------# 50 | test_interval = 100 51 | fps_image_path = "img/street.jpg" 52 | #-------------------------------------------------------------------------# 53 | # dir_origin_path 指定了用于检测的图片的文件夹路径 54 | # dir_save_path 指定了检测完图片的保存路径 55 | # 56 | # dir_origin_path和dir_save_path仅在mode='dir_predict'时有效 57 | #-------------------------------------------------------------------------# 58 | dir_origin_path = "img/" 59 | dir_save_path = "img_out/" 60 | #-------------------------------------------------------------------------# 61 | # heatmap_save_path 热力图的保存路径,默认保存在model_data下 62 | # 63 | # heatmap_save_path仅在mode='heatmap'有效 64 | #-------------------------------------------------------------------------# 65 | heatmap_save_path = "model_data/heatmap_vision.png" 66 | 67 | if mode == "predict": 68 | ''' 69 | 1、如果想要进行检测完的图片的保存,利用r_image.save("img.jpg")即可保存,直接在predict.py里进行修改即可。 70 | 2、如果想要获得预测框的坐标,可以进入yolo.detect_image函数,在绘图部分读取top,left,bottom,right这四个值。 71 | 3、如果想要利用预测框截取下目标,可以进入yolo.detect_image函数,在绘图部分利用获取到的top,left,bottom,right这四个值 72 | 在原图上利用矩阵的方式进行截取。 73 | 4、如果想要在预测图上写额外的字,比如检测到的特定目标的数量,可以进入yolo.detect_image函数,在绘图部分对predicted_class进行判断, 74 | 比如判断if predicted_class == 'car': 即可判断当前目标是否为车,然后记录数量即可。利用draw.text即可写字。 75 | ''' 76 | while True: 77 | img = input('Input image filename:') 78 | try: 79 | image = Image.open(img) 80 | except: 81 | print('Open Error! Try again!') 82 | continue 83 | else: 84 | r_image = yolo.detect_image(image, crop = crop, count=count) 85 | r_image.show() 86 | 87 | elif mode == "video": 88 | capture = cv2.VideoCapture(video_path) 89 | if video_save_path!="": 90 | fourcc = cv2.VideoWriter_fourcc(*'XVID') 91 | size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))) 92 | out = cv2.VideoWriter(video_save_path, fourcc, video_fps, size) 93 | 94 | ref, frame = capture.read() 95 | if not ref: 96 | raise ValueError("未能正确读取摄像头(视频),请注意是否正确安装摄像头(是否正确填写视频路径)。") 97 | 98 | fps = 0.0 99 | while(True): 100 | t1 = time.time() 101 | # 读取某一帧 102 | ref, frame = capture.read() 103 | if not ref: 104 | break 105 | # 格式转变,BGRtoRGB 106 | frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) 107 | # 转变成Image 108 | frame = Image.fromarray(np.uint8(frame)) 109 | # 进行检测 110 | frame = np.array(yolo.detect_image(frame)) 111 | # RGBtoBGR满足opencv显示格式 112 | frame = cv2.cvtColor(frame,cv2.COLOR_RGB2BGR) 113 | 114 | fps = ( fps + (1./(time.time()-t1)) ) / 2 115 | print("fps= %.2f"%(fps)) 116 | frame = cv2.putText(frame, "fps= %.2f"%(fps), (0, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) 117 | 118 | cv2.imshow("video",frame) 119 | c= cv2.waitKey(1) & 0xff 120 | if video_save_path!="": 121 | out.write(frame) 122 | 123 | if c==27: 124 | capture.release() 125 | break 126 | 127 | print("Video Detection Done!") 128 | capture.release() 129 | if video_save_path!="": 130 | print("Save processed video to the path :" + video_save_path) 131 | out.release() 132 | cv2.destroyAllWindows() 133 | 134 | elif mode == "fps": 135 | img = Image.open(fps_image_path) 136 | tact_time = yolo.get_FPS(img, test_interval) 137 | print(str(tact_time) + ' seconds, ' + str(1/tact_time) + 'FPS, @batch_size 1') 138 | 139 | elif mode == "dir_predict": 140 | import os 141 | 142 | from tqdm import tqdm 143 | 144 | img_names = os.listdir(dir_origin_path) 145 | for img_name in tqdm(img_names): 146 | if img_name.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.tif', '.tiff')): 147 | image_path = os.path.join(dir_origin_path, img_name) 148 | image = Image.open(image_path) 149 | r_image = yolo.detect_image(image) 150 | if not os.path.exists(dir_save_path): 151 | os.makedirs(dir_save_path) 152 | r_image.save(os.path.join(dir_save_path, img_name.replace(".jpg", ".png")), quality=95, subsampling=0) 153 | 154 | elif mode == "heatmap": 155 | while True: 156 | img = input('Input image filename:') 157 | try: 158 | image = Image.open(img) 159 | except: 160 | print('Open Error! Try again!') 161 | continue 162 | else: 163 | yolo.detect_heatmap(image, heatmap_save_path) 164 | 165 | else: 166 | raise AssertionError("Please specify the correct mode: 'predict', 'video', 'fps' or 'dir_predict'.") 167 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## YOLOV5:You Only Look Once目标检测模型在keras当中的实现(edition v5.0 in Ultralytics) 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-02`**:**仓库创建,支持不同尺寸模型训练,分别为s、m、l、x版本的yolov5、支持step、cos学习率下降法、支持adam、sgd优化器选择、支持学习率根据batch_size自适应调整、新增图片裁剪。** 19 | 20 | ## 相关仓库 21 | | 模型 | 路径 | 22 | | :----- | :----- | 23 | YoloV3 | https://github.com/bubbliiiing/yolo3-keras 24 | Efficientnet-Yolo3 | https://github.com/bubbliiiing/efficientnet-yolo3-keras 25 | YoloV4 | https://github.com/bubbliiiing/yolov4-keras 26 | YoloV4-tiny | https://github.com/bubbliiiing/yolov4-tiny-keras 27 | Mobilenet-Yolov4 | https://github.com/bubbliiiing/mobilenet-yolov4-keras 28 | YoloV5-V5.0 | https://github.com/bubbliiiing/yolov5-keras 29 | YoloV5-V6.1 | https://github.com/bubbliiiing/yolov5-v6.1-keras 30 | YoloX | https://github.com/bubbliiiing/yolox-keras 31 | YoloV7 | https://github.com/bubbliiiing/yolov7-keras 32 | Yolov7-tiny | https://github.com/bubbliiiing/yolov7-tiny-keras 33 | 34 | ## 性能情况 35 | | 训练数据集 | 权值文件名称 | 测试数据集 | 输入图片大小 | mAP 0.5:0.95 | mAP 0.5 | 36 | | :-----: | :-----: | :------: | :------: | :------: | :-----: | 37 | | COCO-Train2017 | [yolov5_s.h5](https://github.com/bubbliiiing/yolov5-keras/releases/download/v1.0/yolov5_s.h5) | COCO-Val2017 | 640x640 | 35.6 | 53.9 38 | | COCO-Train2017 | [yolov5_m.h5](https://github.com/bubbliiiing/yolov5-keras/releases/download/v1.0/yolov5_m.h5) | COCO-Val2017 | 640x640 | 43.9 | 62.6 39 | | COCO-Train2017 | [yolov5_l.h5](https://github.com/bubbliiiing/yolov5-keras/releases/download/v1.0/yolov5_l.h5) | COCO-Val2017 | 640x640 | 47.4 | 66.2 40 | | COCO-Train2017 | [yolov5_x.h5](https://github.com/bubbliiiing/yolov5-keras/releases/download/v1.0/yolov5_x.h5) | COCO-Val2017 | 640x640 | 49.4 | 67.9 41 | 42 | ## 所需环境 43 | keras==2.1.5 44 | tensorflow-gpu==1.13.2 45 | 46 | ## 文件下载 47 | 训练所需的权值可在百度网盘中下载。 48 | 链接: https://pan.baidu.com/s/18DufVEkngOe-aoA30obLEw 49 | 提取码: disz 50 | 51 | VOC数据集下载地址如下,里面已经包括了训练集、测试集、验证集(与测试集一样),无需再次划分: 52 | 链接: https://pan.baidu.com/s/19Mw2u_df_nBzsC2lg20fQA 53 | 提取码: j5ge 54 | 55 | ## 训练步骤 56 | ### a、训练VOC07+12数据集 57 | 1. 数据集的准备 58 | **本文使用VOC格式进行训练,训练前需要下载好VOC07+12的数据集,解压后放在根目录** 59 | 60 | 2. 数据集的处理 61 | 修改voc_annotation.py里面的annotation_mode=2,运行voc_annotation.py生成根目录下的2007_train.txt和2007_val.txt。 62 | 63 | 3. 开始网络训练 64 | train.py的默认参数用于训练VOC数据集,直接运行train.py即可开始训练。 65 | 66 | 4. 训练结果预测 67 | 训练结果预测需要用到两个文件,分别是yolo.py和predict.py。我们首先需要去yolo.py里面修改model_path以及classes_path,这两个参数必须要修改。 68 | **model_path指向训练好的权值文件,在logs文件夹里。 69 | classes_path指向检测类别所对应的txt。** 70 | 完成修改后就可以运行predict.py进行检测了。运行后输入图片路径即可检测。 71 | 72 | ### b、训练自己的数据集 73 | 1. 数据集的准备 74 | **本文使用VOC格式进行训练,训练前需要自己制作好数据集,** 75 | 训练前将标签文件放在VOCdevkit文件夹下的VOC2007文件夹下的Annotation中。 76 | 训练前将图片文件放在VOCdevkit文件夹下的VOC2007文件夹下的JPEGImages中。 77 | 78 | 2. 数据集的处理 79 | 在完成数据集的摆放之后,我们需要利用voc_annotation.py获得训练用的2007_train.txt和2007_val.txt。 80 | 修改voc_annotation.py里面的参数。第一次训练可以仅修改classes_path,classes_path用于指向检测类别所对应的txt。 81 | 训练自己的数据集时,可以自己建立一个cls_classes.txt,里面写自己所需要区分的类别。 82 | model_data/cls_classes.txt文件内容为: 83 | ```python 84 | cat 85 | dog 86 | ... 87 | ``` 88 | 修改voc_annotation.py中的classes_path,使其对应cls_classes.txt,并运行voc_annotation.py。 89 | 90 | 3. 开始网络训练 91 | **训练的参数较多,均在train.py中,大家可以在下载库后仔细看注释,其中最重要的部分依然是train.py里的classes_path。** 92 | **classes_path用于指向检测类别所对应的txt,这个txt和voc_annotation.py里面的txt一样!训练自己的数据集必须要修改!** 93 | 修改完classes_path后就可以运行train.py开始训练了,在训练多个epoch后,权值会生成在logs文件夹中。 94 | 95 | 4. 训练结果预测 96 | 训练结果预测需要用到两个文件,分别是yolo.py和predict.py。在yolo.py里面修改model_path以及classes_path。 97 | **model_path指向训练好的权值文件,在logs文件夹里。 98 | classes_path指向检测类别所对应的txt。** 99 | 完成修改后就可以运行predict.py进行检测了。运行后输入图片路径即可检测。 100 | 101 | ## 预测步骤 102 | ### a、使用预训练权重 103 | 1. 下载完库后解压,在百度网盘下载权值,放入model_data,运行predict.py,输入 104 | ```python 105 | img/street.jpg 106 | ``` 107 | 2. 在predict.py里面进行设置可以进行fps测试和video视频检测。 108 | ### b、使用自己训练的权重 109 | 1. 按照训练步骤训练。 110 | 2. 在yolo.py文件里面,在如下部分修改model_path和classes_path使其对应训练好的文件;**model_path对应logs文件夹下面的权值文件,classes_path是model_path对应分的类**。 111 | ```python 112 | _defaults = { 113 | #--------------------------------------------------------------------------# 114 | # 使用自己训练好的模型进行预测一定要修改model_path和classes_path! 115 | # model_path指向logs文件夹下的权值文件,classes_path指向model_data下的txt 116 | # 117 | # 训练好后logs文件夹下存在多个权值文件,选择验证集损失较低的即可。 118 | # 验证集损失较低不代表mAP较高,仅代表该权值在验证集上泛化性能较好。 119 | # 如果出现shape不匹配,同时要注意训练时的model_path和classes_path参数的修改 120 | #--------------------------------------------------------------------------# 121 | "model_path" : 'model_data/yolov5_s.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" : [[6, 7, 8], [3, 4, 5], [0, 1, 2]], 129 | #---------------------------------------------------------------------# 130 | # 输入图片的大小,必须为32的倍数。 131 | #---------------------------------------------------------------------# 132 | "input_shape" : [640, 640], 133 | #---------------------------------------------------------------------# 134 | # 所使用的YoloV5的版本。s、m、l、x 135 | #---------------------------------------------------------------------# 136 | "phi" : 's', 137 | #---------------------------------------------------------------------# 138 | # 只有得分大于置信度的预测框会被保留下来 139 | #---------------------------------------------------------------------# 140 | "confidence" : 0.5, 141 | #---------------------------------------------------------------------# 142 | # 非极大抑制所用到的nms_iou大小 143 | #---------------------------------------------------------------------# 144 | "nms_iou" : 0.3, 145 | #---------------------------------------------------------------------# 146 | # 最大框的数量 147 | #---------------------------------------------------------------------# 148 | "max_boxes" : 100, 149 | #---------------------------------------------------------------------# 150 | # 该变量用于控制是否使用letterbox_image对输入图像进行不失真的resize, 151 | # 在多次测试后,发现关闭letterbox_image直接resize的效果更好 152 | #---------------------------------------------------------------------# 153 | "letterbox_image" : True, 154 | } 155 | ``` 156 | 3. 运行predict.py,输入 157 | ```python 158 | img/street.jpg 159 | ``` 160 | 4. 在predict.py里面进行设置可以进行fps测试和video视频检测。 161 | 162 | ## 评估步骤 163 | ### a、评估VOC07+12的测试集 164 | 1. 本文使用VOC格式进行评估。VOC07+12已经划分好了测试集,无需利用voc_annotation.py生成ImageSets文件夹下的txt。 165 | 2. 在yolo.py里面修改model_path以及classes_path。**model_path指向训练好的权值文件,在logs文件夹里。classes_path指向检测类别所对应的txt。** 166 | 3. 运行get_map.py即可获得评估结果,评估结果会保存在map_out文件夹中。 167 | 168 | ### b、评估自己的数据集 169 | 1. 本文使用VOC格式进行评估。 170 | 2. 如果在训练前已经运行过voc_annotation.py文件,代码会自动将数据集划分成训练集、验证集和测试集。如果想要修改测试集的比例,可以修改voc_annotation.py文件下的trainval_percent。trainval_percent用于指定(训练集+验证集)与测试集的比例,默认情况下 (训练集+验证集):测试集 = 9:1。train_percent用于指定(训练集+验证集)中训练集与验证集的比例,默认情况下 训练集:验证集 = 9:1。 171 | 3. 利用voc_annotation.py划分测试集后,前往get_map.py文件修改classes_path,classes_path用于指向检测类别所对应的txt,这个txt和训练时的txt一样。评估自己的数据集必须要修改。 172 | 4. 在yolo.py里面修改model_path以及classes_path。**model_path指向训练好的权值文件,在logs文件夹里。classes_path指向检测类别所对应的txt。** 173 | 5. 运行get_map.py即可获得评估结果,评估结果会保存在map_out文件夹中。 174 | 175 | ## Reference 176 | https://github.com/qqwweee/keras-yolo3/ 177 | https://github.com/Cartucho/mAP 178 | https://github.com/Ma-Dan/keras-yolo4 179 | https://github.com/ultralytics/yolov5 180 | -------------------------------------------------------------------------------- /utils/callbacks.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import keras 4 | import matplotlib 5 | matplotlib.use('Agg') 6 | from matplotlib import pyplot as plt 7 | import scipy.signal 8 | 9 | import shutil 10 | import numpy as np 11 | 12 | from keras import backend as K 13 | from PIL import Image 14 | from tqdm import tqdm 15 | from .utils import cvtColor, preprocess_input, resize_image 16 | from .utils_bbox import DecodeBox 17 | from .utils_map import get_coco_map, get_map 18 | 19 | class LossHistory(keras.callbacks.Callback): 20 | def __init__(self, log_dir): 21 | self.log_dir = log_dir 22 | self.losses = [] 23 | self.val_loss = [] 24 | 25 | os.makedirs(self.log_dir) 26 | 27 | def on_epoch_end(self, epoch, logs={}): 28 | if not os.path.exists(self.log_dir): 29 | os.makedirs(self.log_dir) 30 | 31 | self.losses.append(logs.get('loss')) 32 | self.val_loss.append(logs.get('val_loss')) 33 | 34 | with open(os.path.join(self.log_dir, "epoch_loss.txt"), 'a') as f: 35 | f.write(str(logs.get('loss'))) 36 | f.write("\n") 37 | with open(os.path.join(self.log_dir, "epoch_val_loss.txt"), 'a') as f: 38 | f.write(str(logs.get('val_loss'))) 39 | f.write("\n") 40 | self.loss_plot() 41 | 42 | def loss_plot(self): 43 | iters = range(len(self.losses)) 44 | 45 | plt.figure() 46 | plt.plot(iters, self.losses, 'red', linewidth = 2, label='train loss') 47 | plt.plot(iters, self.val_loss, 'coral', linewidth = 2, label='val loss') 48 | try: 49 | if len(self.losses) < 25: 50 | num = 5 51 | else: 52 | num = 15 53 | 54 | plt.plot(iters, scipy.signal.savgol_filter(self.losses, num, 3), 'green', linestyle = '--', linewidth = 2, label='smooth train loss') 55 | plt.plot(iters, scipy.signal.savgol_filter(self.val_loss, num, 3), '#8B4513', linestyle = '--', linewidth = 2, label='smooth val loss') 56 | except: 57 | pass 58 | 59 | plt.grid(True) 60 | plt.xlabel('Epoch') 61 | plt.ylabel('Loss') 62 | plt.title('A Loss Curve') 63 | plt.legend(loc="upper right") 64 | 65 | plt.savefig(os.path.join(self.log_dir, "epoch_loss.png")) 66 | 67 | plt.cla() 68 | plt.close("all") 69 | 70 | class ParallelModelCheckpoint(keras.callbacks.ModelCheckpoint): 71 | def __init__(self, model, filepath, monitor='val_loss', verbose=0, 72 | save_best_only=False, save_weights_only=False, 73 | mode='auto', period=1): 74 | self.single_model = model 75 | super(ParallelModelCheckpoint,self).__init__(filepath, monitor, verbose,save_best_only, save_weights_only,mode, period) 76 | 77 | def set_model(self, model): 78 | super(ParallelModelCheckpoint,self).set_model(self.single_model) 79 | 80 | class EvalCallback(keras.callbacks.Callback): 81 | def __init__(self, model_body, input_shape, anchors, anchors_mask, class_names, num_classes, val_lines, log_dir,\ 82 | 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): 83 | super(EvalCallback, self).__init__() 84 | 85 | self.input_image_shape = K.placeholder(shape=(2, )) 86 | self.sess = K.get_session() 87 | 88 | self.model_body = model_body 89 | self.input_shape = input_shape 90 | self.anchors = anchors 91 | self.anchors_mask = anchors_mask 92 | self.class_names = class_names 93 | self.num_classes = num_classes 94 | self.val_lines = val_lines 95 | self.log_dir = log_dir 96 | self.map_out_path = map_out_path 97 | self.max_boxes = max_boxes 98 | self.confidence = confidence 99 | self.nms_iou = nms_iou 100 | self.letterbox_image = letterbox_image 101 | self.MINOVERLAP = MINOVERLAP 102 | self.eval_flag = eval_flag 103 | self.period = period 104 | 105 | #---------------------------------------------------------# 106 | # 在yolo_eval函数中,我们会对预测结果进行后处理 107 | # 后处理的内容包括,解码、非极大抑制、门限筛选等 108 | #---------------------------------------------------------# 109 | self.boxes, self.scores, self.classes = DecodeBox( 110 | self.model_body.get_output_at(0), 111 | self.anchors, 112 | self.num_classes, 113 | self.input_image_shape, 114 | self.input_shape, 115 | anchor_mask = self.anchors_mask, 116 | max_boxes = self.max_boxes, 117 | confidence = self.confidence, 118 | nms_iou = self.nms_iou, 119 | letterbox_image = self.letterbox_image 120 | ) 121 | 122 | self.maps = [0] 123 | self.epoches = [0] 124 | if self.eval_flag: 125 | with open(os.path.join(self.log_dir, "epoch_map.txt"), 'a') as f: 126 | f.write(str(0)) 127 | f.write("\n") 128 | 129 | def get_map_txt(self, image_id, image, class_names, map_out_path): 130 | f = open(os.path.join(map_out_path, "detection-results/"+image_id+".txt"),"w") 131 | #---------------------------------------------------------# 132 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 133 | #---------------------------------------------------------# 134 | image = cvtColor(image) 135 | #---------------------------------------------------------# 136 | # 给图像增加灰条,实现不失真的resize 137 | # 也可以直接resize进行识别 138 | #---------------------------------------------------------# 139 | image_data = resize_image(image, (self.input_shape[1],self.input_shape[0]), self.letterbox_image) 140 | #---------------------------------------------------------# 141 | # 添加上batch_size维度,并进行归一化 142 | #---------------------------------------------------------# 143 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 144 | #---------------------------------------------------------# 145 | # 将图像输入网络当中进行预测! 146 | #---------------------------------------------------------# 147 | out_boxes, out_scores, out_classes = self.sess.run( 148 | [self.boxes, self.scores, self.classes], 149 | feed_dict={ 150 | self.model_body.get_input_at(0): image_data, 151 | self.input_image_shape: [image.size[1], image.size[0]], 152 | K.learning_phase(): 0}) 153 | 154 | top_100 = np.argsort(out_scores)[::-1][:self.max_boxes] 155 | out_boxes = out_boxes[top_100] 156 | out_scores = out_scores[top_100] 157 | out_classes = out_classes[top_100] 158 | 159 | for i, c in enumerate(out_classes): 160 | predicted_class = self.class_names[int(c)] 161 | score = str(out_scores[i]) 162 | top, left, bottom, right = out_boxes[i] 163 | if predicted_class not in class_names: 164 | continue 165 | 166 | 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)))) 167 | 168 | f.close() 169 | return 170 | 171 | def on_epoch_end(self, epoch, logs=None): 172 | temp_epoch = epoch + 1 173 | if temp_epoch % self.period == 0 and self.eval_flag: 174 | if not os.path.exists(self.map_out_path): 175 | os.makedirs(self.map_out_path) 176 | if not os.path.exists(os.path.join(self.map_out_path, "ground-truth")): 177 | os.makedirs(os.path.join(self.map_out_path, "ground-truth")) 178 | if not os.path.exists(os.path.join(self.map_out_path, "detection-results")): 179 | os.makedirs(os.path.join(self.map_out_path, "detection-results")) 180 | print("Get map.") 181 | for annotation_line in tqdm(self.val_lines): 182 | line = annotation_line.split() 183 | image_id = os.path.basename(line[0]).split('.')[0] 184 | #------------------------------# 185 | # 读取图像并转换成RGB图像 186 | #------------------------------# 187 | image = Image.open(line[0]) 188 | #------------------------------# 189 | # 获得预测框 190 | #------------------------------# 191 | gt_boxes = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) 192 | #------------------------------# 193 | # 获得预测txt 194 | #------------------------------# 195 | self.get_map_txt(image_id, image, self.class_names, self.map_out_path) 196 | 197 | #------------------------------# 198 | # 获得真实框txt 199 | #------------------------------# 200 | with open(os.path.join(self.map_out_path, "ground-truth/"+image_id+".txt"), "w") as new_f: 201 | for box in gt_boxes: 202 | left, top, right, bottom, obj = box 203 | obj_name = self.class_names[obj] 204 | new_f.write("%s %s %s %s %s\n" % (obj_name, left, top, right, bottom)) 205 | 206 | print("Calculate Map.") 207 | try: 208 | temp_map = get_coco_map(class_names = self.class_names, path = self.map_out_path)[1] 209 | except: 210 | temp_map = get_map(self.MINOVERLAP, False, path = self.map_out_path) 211 | self.maps.append(temp_map) 212 | self.epoches.append(temp_epoch) 213 | 214 | with open(os.path.join(self.log_dir, "epoch_map.txt"), 'a') as f: 215 | f.write(str(temp_map)) 216 | f.write("\n") 217 | 218 | plt.figure() 219 | plt.plot(self.epoches, self.maps, 'red', linewidth = 2, label='train map') 220 | 221 | plt.grid(True) 222 | plt.xlabel('Epoch') 223 | plt.ylabel('Map %s'%str(self.MINOVERLAP)) 224 | plt.title('A Map Curve') 225 | plt.legend(loc="upper right") 226 | 227 | plt.savefig(os.path.join(self.log_dir, "epoch_map.png")) 228 | plt.cla() 229 | plt.close("all") 230 | 231 | print("Get map done.") 232 | shutil.rmtree(self.map_out_path) 233 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /nets/yolo_training.py: -------------------------------------------------------------------------------- 1 | import math 2 | from functools import partial 3 | 4 | import tensorflow as tf 5 | from 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 | balance = [0.4, 1.0, 4], 133 | label_smoothing = 0.01, 134 | box_ratio = 0.05, 135 | obj_ratio = 1, 136 | cls_ratio = 0.5 137 | ): 138 | num_layers = len(anchors_mask) 139 | #---------------------------------------------------------------------------------------------------# 140 | # 将预测结果和实际ground truth分开,args是[*model_body.output, *y_true] 141 | # y_true是一个列表,包含三个特征层,shape分别为: 142 | # (m,20,20,3,85) 143 | # (m,40,40,3,85) 144 | # (m,80,80,3,85) 145 | # yolo_outputs是一个列表,包含三个特征层,shape分别为: 146 | # (m,20,20,3,85) 147 | # (m,40,40,3,85) 148 | # (m,80,80,3,85) 149 | #---------------------------------------------------------------------------------------------------# 150 | y_true = args[num_layers:] 151 | yolo_outputs = args[:num_layers] 152 | 153 | #-----------------------------------------------------------# 154 | # 得到input_shpae为640,640 155 | #-----------------------------------------------------------# 156 | input_shape = K.cast(input_shape, K.dtype(y_true[0])) 157 | 158 | loss = 0 159 | #---------------------------------------------------------------------------------------------------# 160 | # y_true是一个列表,包含三个特征层,shape分别为(m,20,20,3,85),(m,40,40,3,85),(m,80,80,3,85)。 161 | # yolo_outputs是一个列表,包含三个特征层,shape分别为(m,20,20,3,85),(m,40,40,3,85),(m,80,80,3,85)。 162 | #---------------------------------------------------------------------------------------------------# 163 | for l in range(num_layers): 164 | #-----------------------------------------------------------# 165 | # 以第一个特征层(m,20,20,3,85)为例子 166 | # 取出该特征层中存在目标的点的位置。(m,20,20,3,1) 167 | #-----------------------------------------------------------# 168 | object_mask = y_true[l][..., 4:5] 169 | #-----------------------------------------------------------# 170 | # 取出其对应的种类(m,20,20,3,num_classes) 171 | #-----------------------------------------------------------# 172 | true_class_probs = y_true[l][..., 5:] 173 | if label_smoothing: 174 | true_class_probs = _smooth_labels(true_class_probs, label_smoothing) 175 | 176 | #-----------------------------------------------------------# 177 | # 将yolo_outputs的特征层输出进行处理、获得四个返回值 178 | # 其中: 179 | # grid (20,20,1,2) 网格坐标 180 | # raw_pred (m,20,20,3,85) 尚未处理的预测结果 181 | # pred_xy (m,20,20,3,2) 解码后的中心坐标 182 | # pred_wh (m,20,20,3,2) 解码后的宽高坐标 183 | #-----------------------------------------------------------# 184 | grid, raw_pred, pred_xy, pred_wh = get_anchors_and_decode(yolo_outputs[l], 185 | anchors[anchors_mask[l]], num_classes, input_shape, calc_loss=True) 186 | 187 | #-----------------------------------------------------------# 188 | # pred_box是解码后的预测的box的位置 189 | # (m,20,20,3,4) 190 | #-----------------------------------------------------------# 191 | pred_box = K.concatenate([pred_xy, pred_wh]) 192 | 193 | #-----------------------------------------------------------# 194 | # 计算Ciou loss 195 | # raw_true_box 前四个序号的内容是当前这个先验框对应的真实框坐标 196 | # pred_box 每一个特征点每个先验框的预测结果 197 | # box_ciou(pred_box, raw_true_box) 计算每一个特征点上每一个先验框,预测结果和真实情况的ciou 198 | # object_mask 正样本的mask,用于选取正样本,只有正样本才可以计算回归损失。 199 | #-----------------------------------------------------------# 200 | raw_true_box = y_true[l][...,0:4] 201 | ciou = box_ciou(pred_box, raw_true_box) 202 | ciou_loss = object_mask * (1 - ciou) 203 | 204 | #------------------------------------------------------------------------------# 205 | # 先去计算每一个正样本和当前预测框的重合程度 206 | # 使用正样本真实框与预测框的重合程度,作为当前正样本内部是否包含目标的标签 207 | # 208 | # 当前的先验框预测越准确,这个先验框才负责这个真实框的预测。 209 | #------------------------------------------------------------------------------# 210 | tobj = tf.where(tf.equal(object_mask, 1), tf.maximum(ciou, tf.zeros_like(ciou)), tf.zeros_like(ciou)) 211 | confidence_loss = K.binary_crossentropy(tobj, raw_pred[..., 4:5], from_logits=True) 212 | 213 | #-----------------------------------------------------------# 214 | # 计算分类损失 215 | #-----------------------------------------------------------# 216 | class_loss = object_mask * K.binary_crossentropy(true_class_probs, raw_pred[...,5:], from_logits=True) 217 | 218 | #-----------------------------------------------------------# 219 | # 计算正样本数量 220 | #-----------------------------------------------------------# 221 | num_pos = tf.maximum(K.sum(K.cast(object_mask, tf.float32)), 1) 222 | 223 | location_loss = K.sum(ciou_loss) * box_ratio / num_pos 224 | confidence_loss = K.mean(confidence_loss) * balance[l] * obj_ratio 225 | class_loss = K.sum(class_loss) * cls_ratio / num_pos / num_classes 226 | 227 | loss += location_loss + confidence_loss + class_loss 228 | # if print_loss: 229 | # loss = tf.Print(loss, [loss, location_loss, confidence_loss, class_loss], message='loss: ') 230 | 231 | return loss 232 | 233 | 234 | def get_lr_scheduler(lr_decay_type, lr, min_lr, total_iters, warmup_iters_ratio = 0.05, warmup_lr_ratio = 0.1, no_aug_iter_ratio = 0.05, step_num = 10): 235 | def yolox_warm_cos_lr(lr, min_lr, total_iters, warmup_total_iters, warmup_lr_start, no_aug_iter, iters): 236 | if iters <= warmup_total_iters: 237 | # lr = (lr - warmup_lr_start) * iters / float(warmup_total_iters) + warmup_lr_start 238 | lr = (lr - warmup_lr_start) * pow(iters / float(warmup_total_iters), 2 239 | ) + warmup_lr_start 240 | elif iters >= total_iters - no_aug_iter: 241 | lr = min_lr 242 | else: 243 | lr = min_lr + 0.5 * (lr - min_lr) * ( 244 | 1.0 245 | + math.cos( 246 | math.pi 247 | * (iters - warmup_total_iters) 248 | / (total_iters - warmup_total_iters - no_aug_iter) 249 | ) 250 | ) 251 | return lr 252 | 253 | def step_lr(lr, decay_rate, step_size, iters): 254 | if step_size < 1: 255 | raise ValueError("step_size must above 1.") 256 | n = iters // step_size 257 | out_lr = lr * decay_rate ** n 258 | return out_lr 259 | 260 | if lr_decay_type == "cos": 261 | warmup_total_iters = min(max(warmup_iters_ratio * total_iters, 1), 3) 262 | warmup_lr_start = max(warmup_lr_ratio * lr, 1e-6) 263 | no_aug_iter = min(max(no_aug_iter_ratio * total_iters, 1), 15) 264 | func = partial(yolox_warm_cos_lr ,lr, min_lr, total_iters, warmup_total_iters, warmup_lr_start, no_aug_iter) 265 | else: 266 | decay_rate = (min_lr / lr) ** (1 / (step_num - 1)) 267 | step_size = total_iters / step_num 268 | func = partial(step_lr, lr, decay_rate, step_size) 269 | 270 | return func 271 | -------------------------------------------------------------------------------- /utils/utils_bbox.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | from keras import backend as K 3 | 4 | 5 | #---------------------------------------------------# 6 | # 对box进行调整,使其符合真实图片的样子 7 | #---------------------------------------------------# 8 | def yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image): 9 | #-----------------------------------------------------------------# 10 | # 把y轴放前面是因为方便预测框和图像的宽高进行相乘 11 | #-----------------------------------------------------------------# 12 | box_yx = box_xy[..., ::-1] 13 | box_hw = box_wh[..., ::-1] 14 | input_shape = K.cast(input_shape, K.dtype(box_yx)) 15 | image_shape = K.cast(image_shape, K.dtype(box_yx)) 16 | 17 | if letterbox_image: 18 | #-----------------------------------------------------------------# 19 | # 这里求出来的offset是图像有效区域相对于图像左上角的偏移情况 20 | # new_shape指的是宽高缩放情况 21 | #-----------------------------------------------------------------# 22 | new_shape = K.round(image_shape * K.min(input_shape/image_shape)) 23 | offset = (input_shape - new_shape)/2./input_shape 24 | scale = input_shape/new_shape 25 | 26 | box_yx = (box_yx - offset) * scale 27 | box_hw *= scale 28 | 29 | box_mins = box_yx - (box_hw / 2.) 30 | box_maxes = box_yx + (box_hw / 2.) 31 | boxes = K.concatenate([box_mins[..., 0:1], box_mins[..., 1:2], box_maxes[..., 0:1], box_maxes[..., 1:2]]) 32 | boxes *= K.concatenate([image_shape, image_shape]) 33 | return boxes 34 | 35 | #---------------------------------------------------# 36 | # 将预测值的每个特征层调成真实值 37 | #---------------------------------------------------# 38 | def get_anchors_and_decode(feats, anchors, num_classes, input_shape, calc_loss=False): 39 | #---------------------------------------------------# 40 | # 计算先验框的数量,num_anchors = 3 41 | #---------------------------------------------------# 42 | num_anchors = len(anchors) 43 | #------------------------------------------# 44 | # grid_shape指的是特征层的高和宽 45 | #------------------------------------------# 46 | grid_shape = K.shape(feats)[1:3] 47 | #--------------------------------------------------------------------# 48 | # 获得各个特征点的坐标信息。生成的shape为(20, 20, num_anchors, 2) 49 | #--------------------------------------------------------------------# 50 | grid_x = K.tile(K.reshape(K.arange(0, stop=grid_shape[1]), [1, -1, 1, 1]), [grid_shape[0], 1, num_anchors, 1]) 51 | grid_y = K.tile(K.reshape(K.arange(0, stop=grid_shape[0]), [-1, 1, 1, 1]), [1, grid_shape[1], num_anchors, 1]) 52 | grid = K.cast(K.concatenate([grid_x, grid_y]), K.dtype(feats)) 53 | #---------------------------------------------------------------# 54 | # 将先验框进行拓展,生成的shape为(20, 20, num_anchors, 2) 55 | #---------------------------------------------------------------# 56 | anchors_tensor = K.reshape(K.constant(anchors), [1, 1, num_anchors, 2]) 57 | anchors_tensor = K.tile(anchors_tensor, [grid_shape[0], grid_shape[1], 1, 1]) 58 | 59 | #---------------------------------------------------# 60 | # 将预测结果调整成(batch_size, 20, 20, 3, 85) 61 | # 85可拆分成4 + 1 + 80 62 | # 4代表的是中心宽高的调整参数 63 | # 1代表的是框的置信度 64 | # 80代表的是种类的置信度 65 | # batch_size, 20, 20, 3, 5 + num_classes 66 | #---------------------------------------------------# 67 | feats = K.reshape(feats, [-1, grid_shape[0], grid_shape[1], num_anchors, num_classes + 5]) 68 | #------------------------------------------# 69 | # 对先验框进行解码,并进行归一化 70 | #------------------------------------------# 71 | box_xy = (K.sigmoid(feats[..., :2]) * 2 - 0.5 + grid) / K.cast(grid_shape[::-1], K.dtype(feats)) 72 | box_wh = (K.sigmoid(feats[..., 2:4]) * 2) ** 2 * anchors_tensor / K.cast(input_shape[::-1], K.dtype(feats)) 73 | #------------------------------------------# 74 | # 获得预测框的置信度 75 | #------------------------------------------# 76 | box_confidence = K.sigmoid(feats[..., 4:5]) 77 | box_class_probs = K.sigmoid(feats[..., 5:]) 78 | 79 | #---------------------------------------------------------------------# 80 | # 在计算loss的时候返回grid, feats, box_xy, box_wh 81 | # 在预测的时候返回box_xy, box_wh, box_confidence, box_class_probs 82 | #---------------------------------------------------------------------# 83 | if calc_loss == True: 84 | return grid, feats, box_xy, box_wh 85 | return box_xy, box_wh, box_confidence, box_class_probs 86 | 87 | #---------------------------------------------------# 88 | # 图片预测 89 | #---------------------------------------------------# 90 | def DecodeBox(outputs, 91 | anchors, 92 | num_classes, 93 | image_shape, 94 | input_shape, 95 | #-----------------------------------------------------------# 96 | # 13x13的特征层对应的anchor是[116,90],[156,198],[373,326] 97 | # 26x26的特征层对应的anchor是[30,61],[62,45],[59,119] 98 | # 52x52的特征层对应的anchor是[10,13],[16,30],[33,23] 99 | #-----------------------------------------------------------# 100 | anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]], 101 | max_boxes = 100, 102 | confidence = 0.5, 103 | nms_iou = 0.3, 104 | letterbox_image = True): 105 | 106 | box_xy = [] 107 | box_wh = [] 108 | box_confidence = [] 109 | box_class_probs = [] 110 | for i in range(len(outputs)): 111 | sub_box_xy, sub_box_wh, sub_box_confidence, sub_box_class_probs = \ 112 | get_anchors_and_decode(outputs[i], anchors[anchor_mask[i]], num_classes, input_shape) 113 | box_xy.append(K.reshape(sub_box_xy, [-1, 2])) 114 | box_wh.append(K.reshape(sub_box_wh, [-1, 2])) 115 | box_confidence.append(K.reshape(sub_box_confidence, [-1, 1])) 116 | box_class_probs.append(K.reshape(sub_box_class_probs, [-1, num_classes])) 117 | box_xy = K.concatenate(box_xy, axis = 0) 118 | box_wh = K.concatenate(box_wh, axis = 0) 119 | box_confidence = K.concatenate(box_confidence, axis = 0) 120 | box_class_probs = K.concatenate(box_class_probs, axis = 0) 121 | 122 | #------------------------------------------------------------------------------------------------------------# 123 | # 在图像传入网络预测前会进行letterbox_image给图像周围添加灰条,因此生成的box_xy, box_wh是相对于有灰条的图像的 124 | # 我们需要对其进行修改,去除灰条的部分。 将box_xy、和box_wh调节成y_min,y_max,xmin,xmax 125 | # 如果没有使用letterbox_image也需要将归一化后的box_xy, box_wh调整成相对于原图大小的 126 | #------------------------------------------------------------------------------------------------------------# 127 | boxes = yolo_correct_boxes(box_xy, box_wh, input_shape, image_shape, letterbox_image) 128 | box_scores = box_confidence * box_class_probs 129 | 130 | #-----------------------------------------------------------# 131 | # 判断得分是否大于score_threshold 132 | #-----------------------------------------------------------# 133 | mask = box_scores >= confidence 134 | max_boxes_tensor = K.constant(max_boxes, dtype='int32') 135 | boxes_out = [] 136 | scores_out = [] 137 | classes_out = [] 138 | #-----------------------------------------------------------# 139 | # 筛选出一定区域内属于同一种类得分最大的框 140 | #-----------------------------------------------------------# 141 | for c in range(num_classes): 142 | #-----------------------------------------------------------# 143 | # 取出所有box_scores >= score_threshold的框,和成绩 144 | #-----------------------------------------------------------# 145 | class_boxes = tf.boolean_mask(boxes, mask[:, c]) 146 | class_box_scores = tf.boolean_mask(box_scores[:, c], mask[:, c]) 147 | 148 | #-----------------------------------------------------------# 149 | # 非极大抑制 150 | # 保留一定区域内得分最大的框 151 | #-----------------------------------------------------------# 152 | nms_index = tf.image.non_max_suppression(class_boxes, class_box_scores, max_boxes_tensor, iou_threshold=nms_iou) 153 | 154 | #-----------------------------------------------------------# 155 | # 获取非极大抑制后的结果 156 | # 下列三个分别是:框的位置,得分与种类 157 | #-----------------------------------------------------------# 158 | class_boxes = K.gather(class_boxes, nms_index) 159 | class_box_scores = K.gather(class_box_scores, nms_index) 160 | classes = K.ones_like(class_box_scores, 'int32') * c 161 | 162 | boxes_out.append(class_boxes) 163 | scores_out.append(class_box_scores) 164 | classes_out.append(classes) 165 | boxes_out = K.concatenate(boxes_out, axis=0) 166 | scores_out = K.concatenate(scores_out, axis=0) 167 | classes_out = K.concatenate(classes_out, axis=0) 168 | 169 | return boxes_out, scores_out, classes_out 170 | 171 | 172 | if __name__ == "__main__": 173 | import matplotlib.pyplot as plt 174 | import numpy as np 175 | 176 | def sigmoid(x): 177 | s = 1 / (1 + np.exp(-x)) 178 | return s 179 | #---------------------------------------------------# 180 | # 将预测值的每个特征层调成真实值 181 | #---------------------------------------------------# 182 | def get_anchors_and_decode(feats, anchors, num_classes): 183 | # feats [batch_size, 20, 20, 3 * (5 + num_classes)] 184 | # anchors [3, 2] 185 | # num_classes 186 | 187 | #------------------------------------------# 188 | # grid_shape 3 189 | #------------------------------------------# 190 | num_anchors = len(anchors) 191 | #------------------------------------------# 192 | # grid_shape指的是特征层的高和宽 193 | # grid_shape [20, 20] 194 | # h = 20 195 | # w = 20 196 | #------------------------------------------# 197 | grid_shape = np.shape(feats)[1:3] 198 | #--------------------------------------------------------------------# 199 | # 获得各个特征点的坐标信息。生成的shape为(20, 20, num_anchors, 2) 200 | # [0, 1, 2, 3, 4 ……, 19] => [1, 20, 1, 1] => [20, 20, 3, 1] 201 | # [0, 1, 2, 3, 4 ……, 19] => [20, 1, 1, 1] => [20, 20, 3, 1] 202 | # grid_x [20, 20, 3, 1] 203 | # grid_y [20, 20, 3, 1] 204 | # grid [20, 20, 3, 2] 205 | #--------------------------------------------------------------------# 206 | grid_x = np.tile(np.reshape(np.arange(0, stop=grid_shape[1]), [1, -1, 1, 1]), [grid_shape[0], 1, num_anchors, 1]) 207 | grid_y = np.tile(np.reshape(np.arange(0, stop=grid_shape[0]), [-1, 1, 1, 1]), [1, grid_shape[1], num_anchors, 1]) 208 | grid = np.concatenate([grid_x, grid_y], -1) 209 | #---------------------------------------------------------------# 210 | # 将先验框进行拓展,生成的shape为(20, 20, num_anchors, 2) 211 | # [1, 1, 3, 2] 212 | # [20, 20, 3, 2] 213 | #---------------------------------------------------------------# 214 | anchors_tensor = np.reshape(anchors, [1, 1, num_anchors, 2]) 215 | anchors_tensor = np.tile(anchors_tensor, [grid_shape[0], grid_shape[1], 1, 1]) 216 | 217 | #---------------------------------------------------# 218 | # 将预测结果调整成(batch_size, 20, 20, 3, 85) 219 | # 85可拆分成4 + 1 + 80 220 | # 4代表的是中心宽高的调整参数 221 | # 1代表的是框的置信度 222 | # 80代表的是种类的置信度 223 | # [batch_size, 20, 20, 3 * (5 + num_classes)] 224 | # [batch_size, 20, 20, 3, 4 + 1 + num_classes] 225 | #---------------------------------------------------# 226 | feats = np.reshape(feats, [-1, grid_shape[0], grid_shape[1], num_anchors, num_classes + 5]) 227 | 228 | #------------------------------------------# 229 | # 对先验框进行解码,并进行归一化 230 | # 取出4个回归系数里面前2个序号的内容,取sigmoid,值固定到0-1之间 231 | # 乘上2,值固定到0-2之间 232 | # 减去0.5,值固定到-0.5-1.5之间 233 | # 加上网格坐标,获得预测框中心 234 | # 取出4个回归系数里面后2个序号的内容,取sigmoid,值固定到0-1之间 235 | # 乘上2,值固定到0-2之间 236 | # 取平方,值固定到0-4之间 237 | # 乘上先验框的宽高,最终获得预测框的宽高 238 | #------------------------------------------# 239 | box_xy = (sigmoid(feats[..., :2]) * 2 - 0.5 + grid) 240 | box_wh = (sigmoid(feats[..., 2:4]) * 2) ** 2 * anchors_tensor 241 | #------------------------------------------# 242 | # 获得预测框的置信度 243 | #------------------------------------------# 244 | box_confidence = sigmoid(feats[..., 4:5]) 245 | box_class_probs = sigmoid(feats[..., 5:]) 246 | 247 | grid_x = grid_x * 32 248 | grid_y = grid_y * 32 249 | box_xy = box_xy * 32 250 | 251 | point_h = 5 252 | point_w = 5 253 | 254 | from PIL import Image 255 | img = Image.open("img/street.jpg").resize([640, 640]) 256 | 257 | fig = plt.figure() 258 | ax = fig.add_subplot(121) 259 | plt.imshow(img, alpha=0.5) 260 | plt.ylim(-10, 650) 261 | plt.xlim(-10, 650) 262 | plt.scatter(grid_x, grid_y) 263 | plt.scatter(point_h * 32, point_w * 32, c='black') 264 | plt.gca().invert_yaxis() 265 | 266 | anchor_left = grid_x - anchors_tensor / 2 267 | anchor_top = grid_y - anchors_tensor / 2 268 | print(np.shape(box_xy)) 269 | rect1 = plt.Rectangle([anchor_left[point_h, point_w, 0, 0], anchor_top[point_h, point_w, 0, 1]], anchors_tensor[point_h, point_w, 0, 0], anchors_tensor[point_h, point_w, 0, 1], color="r", fill=False) 270 | rect2 = plt.Rectangle([anchor_left[point_h, point_w, 1, 0], anchor_top[point_h, point_w, 1, 1]], anchors_tensor[point_h, point_w, 1, 0], anchors_tensor[point_h, point_w, 1, 1], color="r", fill=False) 271 | rect3 = plt.Rectangle([anchor_left[point_h, point_w, 2, 0], anchor_top[point_h, point_w, 2, 1]], anchors_tensor[point_h, point_w, 2, 0], anchors_tensor[point_h, point_w, 2, 1], color="r", fill=False) 272 | 273 | ax.add_patch(rect1) 274 | ax.add_patch(rect2) 275 | ax.add_patch(rect3) 276 | 277 | ax = fig.add_subplot(122) 278 | plt.imshow(img, alpha=0.5) 279 | plt.ylim(-10, 650) 280 | plt.xlim(-10, 650) 281 | plt.scatter(grid_x, grid_y) 282 | plt.scatter(point_h * 32, point_w * 32, c='black') 283 | plt.scatter(box_xy[0, point_h, point_w, :, 0], box_xy[0, point_h, point_w, :, 1], c='r') 284 | plt.gca().invert_yaxis() 285 | 286 | pre_left = box_xy[...,0] - box_wh[...,0] / 2 287 | pre_top = box_xy[...,1] - box_wh[...,1] / 2 288 | 289 | rect1 = plt.Rectangle([pre_left[0, point_h, point_w, 0], pre_top[0, point_h, point_w, 0]], box_wh[0, point_h, point_w, 0, 0], box_wh[0, point_h, point_w, 0, 1], color="r", fill=False) 290 | rect2 = plt.Rectangle([pre_left[0, point_h, point_w, 1], pre_top[0, point_h, point_w, 1]], box_wh[0, point_h, point_w, 1, 0], box_wh[0, point_h, point_w, 1, 1], color="r", fill=False) 291 | rect3 = plt.Rectangle([pre_left[0, point_h, point_w, 2], pre_top[0, point_h, point_w, 2]], box_wh[0, point_h, point_w, 2, 0], box_wh[0, point_h, point_w, 2, 1], color="r", fill=False) 292 | 293 | ax.add_patch(rect1) 294 | ax.add_patch(rect2) 295 | ax.add_patch(rect3) 296 | 297 | plt.show() 298 | # 299 | feat = np.random.normal(-0.5,0.5, [4, 20, 20, 75]) 300 | anchors = [[116, 90], [156, 198], [373, 326]] 301 | get_anchors_and_decode(feat, anchors, 20) 302 | -------------------------------------------------------------------------------- /yolo.py: -------------------------------------------------------------------------------- 1 | import colorsys 2 | import os 3 | import time 4 | 5 | import numpy as np 6 | from keras import backend as K 7 | from PIL import ImageDraw, ImageFont 8 | 9 | from nets.yolo import yolo_body 10 | from utils.utils import (cvtColor, get_anchors, get_classes, preprocess_input, 11 | resize_image, show_config) 12 | from utils.utils_bbox import DecodeBox 13 | 14 | 15 | class YOLO(object): 16 | _defaults = { 17 | #--------------------------------------------------------------------------# 18 | # 使用自己训练好的模型进行预测一定要修改model_path和classes_path! 19 | # model_path指向logs文件夹下的权值文件,classes_path指向model_data下的txt 20 | # 21 | # 训练好后logs文件夹下存在多个权值文件,选择验证集损失较低的即可。 22 | # 验证集损失较低不代表mAP较高,仅代表该权值在验证集上泛化性能较好。 23 | # 如果出现shape不匹配,同时要注意训练时的model_path和classes_path参数的修改 24 | #--------------------------------------------------------------------------# 25 | "model_path" : 'model_data/yolov5_s.h5', 26 | "classes_path" : 'model_data/coco_classes.txt', 27 | #---------------------------------------------------------------------# 28 | # anchors_path代表先验框对应的txt文件,一般不修改。 29 | # anchors_mask用于帮助代码找到对应的先验框,一般不修改。 30 | #---------------------------------------------------------------------# 31 | "anchors_path" : 'model_data/yolo_anchors.txt', 32 | "anchors_mask" : [[6, 7, 8], [3, 4, 5], [0, 1, 2]], 33 | #---------------------------------------------------------------------# 34 | # 输入图片的大小,必须为32的倍数。 35 | #---------------------------------------------------------------------# 36 | "input_shape" : [640, 640], 37 | #---------------------------------------------------------------------# 38 | # 所使用的YoloV5的版本。s、m、l、x 39 | #---------------------------------------------------------------------# 40 | "phi" : 's', 41 | #---------------------------------------------------------------------# 42 | # 只有得分大于置信度的预测框会被保留下来 43 | #---------------------------------------------------------------------# 44 | "confidence" : 0.5, 45 | #---------------------------------------------------------------------# 46 | # 非极大抑制所用到的nms_iou大小 47 | #---------------------------------------------------------------------# 48 | "nms_iou" : 0.3, 49 | #---------------------------------------------------------------------# 50 | # 最大框的数量 51 | #---------------------------------------------------------------------# 52 | "max_boxes" : 100, 53 | #---------------------------------------------------------------------# 54 | # 该变量用于控制是否使用letterbox_image对输入图像进行不失真的resize, 55 | # 在多次测试后,发现关闭letterbox_image直接resize的效果更好 56 | #---------------------------------------------------------------------# 57 | "letterbox_image" : True, 58 | } 59 | 60 | @classmethod 61 | def get_defaults(cls, n): 62 | if n in cls._defaults: 63 | return cls._defaults[n] 64 | else: 65 | return "Unrecognized attribute name '" + n + "'" 66 | 67 | #---------------------------------------------------# 68 | # 初始化yolo 69 | #---------------------------------------------------# 70 | def __init__(self, **kwargs): 71 | self.__dict__.update(self._defaults) 72 | for name, value in kwargs.items(): 73 | setattr(self, name, value) 74 | self._defaults[name] = value 75 | 76 | #---------------------------------------------------# 77 | # 获得种类和先验框的数量 78 | #---------------------------------------------------# 79 | self.class_names, self.num_classes = get_classes(self.classes_path) 80 | self.anchors, self.num_anchors = get_anchors(self.anchors_path) 81 | 82 | #---------------------------------------------------# 83 | # 画框设置不同的颜色 84 | #---------------------------------------------------# 85 | hsv_tuples = [(x / self.num_classes, 1., 1.) for x in range(self.num_classes)] 86 | self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) 87 | self.colors = list(map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), self.colors)) 88 | self.input_image_shape = K.placeholder(shape=(2, )) 89 | 90 | self.sess = K.get_session() 91 | self.boxes, self.scores, self.classes = self.generate() 92 | 93 | show_config(**self._defaults) 94 | 95 | #---------------------------------------------------# 96 | # 载入模型 97 | #---------------------------------------------------# 98 | def generate(self): 99 | model_path = os.path.expanduser(self.model_path) 100 | assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.' 101 | 102 | self.yolo_model = yolo_body([None, None, 3], self.anchors_mask, self.num_classes, self.phi) 103 | self.yolo_model.load_weights(self.model_path) 104 | print('{} model, anchors, and classes loaded.'.format(model_path)) 105 | #---------------------------------------------------------# 106 | # 在yolo_eval函数中,我们会对预测结果进行后处理 107 | # 后处理的内容包括,解码、非极大抑制、门限筛选等 108 | #---------------------------------------------------------# 109 | boxes, scores, classes = DecodeBox( 110 | self.yolo_model.output, 111 | self.anchors, 112 | self.num_classes, 113 | self.input_image_shape, 114 | self.input_shape, 115 | anchor_mask = self.anchors_mask, 116 | max_boxes = self.max_boxes, 117 | confidence = self.confidence, 118 | nms_iou = self.nms_iou, 119 | letterbox_image = self.letterbox_image 120 | ) 121 | return boxes, scores, classes 122 | 123 | #---------------------------------------------------# 124 | # 检测图片 125 | #---------------------------------------------------# 126 | def detect_image(self, image, crop = False, count = False): 127 | #---------------------------------------------------------# 128 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 129 | # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB 130 | #---------------------------------------------------------# 131 | image = cvtColor(image) 132 | #---------------------------------------------------------# 133 | # 给图像增加灰条,实现不失真的resize 134 | # 也可以直接resize进行识别 135 | #---------------------------------------------------------# 136 | image_data = resize_image(image, (self.input_shape[1], self.input_shape[0]), self.letterbox_image) 137 | #---------------------------------------------------------# 138 | # 添加上batch_size维度,并进行归一化 139 | #---------------------------------------------------------# 140 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 141 | 142 | #---------------------------------------------------------# 143 | # 将图像输入网络当中进行预测! 144 | #---------------------------------------------------------# 145 | out_boxes, out_scores, out_classes = self.sess.run( 146 | [self.boxes, self.scores, self.classes], 147 | feed_dict={ 148 | self.yolo_model.input: image_data, 149 | self.input_image_shape: [image.size[1], image.size[0]], 150 | K.learning_phase(): 0}) 151 | 152 | print('Found {} boxes for {}'.format(len(out_boxes), 'img')) 153 | #---------------------------------------------------------# 154 | # 设置字体与边框厚度 155 | #---------------------------------------------------------# 156 | font = ImageFont.truetype(font='model_data/simhei.ttf', size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32')) 157 | thickness = int(max((image.size[0] + image.size[1]) // np.mean(self.input_shape), 1)) 158 | #---------------------------------------------------------# 159 | # 计数 160 | #---------------------------------------------------------# 161 | if count: 162 | print("top_label:", out_classes) 163 | classes_nums = np.zeros([self.num_classes]) 164 | for i in range(self.num_classes): 165 | num = np.sum(out_classes == i) 166 | if num > 0: 167 | print(self.class_names[i], " : ", num) 168 | classes_nums[i] = num 169 | print("classes_nums:", classes_nums) 170 | #---------------------------------------------------------# 171 | # 是否进行目标的裁剪 172 | #---------------------------------------------------------# 173 | if crop: 174 | for i, c in list(enumerate(out_boxes)): 175 | top, left, bottom, right = out_boxes[i] 176 | top = max(0, np.floor(top).astype('int32')) 177 | left = max(0, np.floor(left).astype('int32')) 178 | bottom = min(image.size[1], np.floor(bottom).astype('int32')) 179 | right = min(image.size[0], np.floor(right).astype('int32')) 180 | 181 | dir_save_path = "img_crop" 182 | if not os.path.exists(dir_save_path): 183 | os.makedirs(dir_save_path) 184 | crop_image = image.crop([left, top, right, bottom]) 185 | crop_image.save(os.path.join(dir_save_path, "crop_" + str(i) + ".png"), quality=95, subsampling=0) 186 | print("save crop_" + str(i) + ".png to " + dir_save_path) 187 | #---------------------------------------------------------# 188 | # 图像绘制 189 | #---------------------------------------------------------# 190 | for i, c in list(enumerate(out_classes)): 191 | predicted_class = self.class_names[int(c)] 192 | box = out_boxes[i] 193 | score = out_scores[i] 194 | 195 | top, left, bottom, right = box 196 | 197 | top = max(0, np.floor(top).astype('int32')) 198 | left = max(0, np.floor(left).astype('int32')) 199 | bottom = min(image.size[1], np.floor(bottom).astype('int32')) 200 | right = min(image.size[0], np.floor(right).astype('int32')) 201 | 202 | label = '{} {:.2f}'.format(predicted_class, score) 203 | draw = ImageDraw.Draw(image) 204 | label_size = draw.textsize(label, font) 205 | label = label.encode('utf-8') 206 | print(label, top, left, bottom, right) 207 | 208 | if top - label_size[1] >= 0: 209 | text_origin = np.array([left, top - label_size[1]]) 210 | else: 211 | text_origin = np.array([left, top + 1]) 212 | 213 | for i in range(thickness): 214 | draw.rectangle([left + i, top + i, right - i, bottom - i], outline=self.colors[c]) 215 | draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)], fill=self.colors[c]) 216 | draw.text(text_origin, str(label,'UTF-8'), fill=(0, 0, 0), font=font) 217 | del draw 218 | 219 | return image 220 | 221 | def get_FPS(self, image, test_interval): 222 | #---------------------------------------------------------# 223 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 224 | # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB 225 | #---------------------------------------------------------# 226 | image = cvtColor(image) 227 | #---------------------------------------------------------# 228 | # 给图像增加灰条,实现不失真的resize 229 | # 也可以直接resize进行识别 230 | #---------------------------------------------------------# 231 | image_data = resize_image(image, (self.input_shape[1], self.input_shape[0]), self.letterbox_image) 232 | #---------------------------------------------------------# 233 | # 添加上batch_size维度,并进行归一化 234 | #---------------------------------------------------------# 235 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 236 | 237 | #---------------------------------------------------------# 238 | # 将图像输入网络当中进行预测! 239 | #---------------------------------------------------------# 240 | out_boxes, out_scores, out_classes = self.sess.run( 241 | [self.boxes, self.scores, self.classes], 242 | feed_dict={ 243 | self.yolo_model.input: image_data, 244 | self.input_image_shape: [image.size[1], image.size[0]], 245 | K.learning_phase(): 0}) 246 | 247 | t1 = time.time() 248 | for _ in range(test_interval): 249 | out_boxes, out_scores, out_classes = self.sess.run( 250 | [self.boxes, self.scores, self.classes], 251 | feed_dict={ 252 | self.yolo_model.input: image_data, 253 | self.input_image_shape: [image.size[1], image.size[0]], 254 | K.learning_phase(): 0}) 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.yolo_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 get_map_txt(self, image_id, image, class_names, map_out_path): 303 | f = open(os.path.join(map_out_path, "detection-results/"+image_id+".txt"), "w", encoding='utf-8') 304 | #---------------------------------------------------------# 305 | # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。 306 | #---------------------------------------------------------# 307 | image = cvtColor(image) 308 | #---------------------------------------------------------# 309 | # 给图像增加灰条,实现不失真的resize 310 | # 也可以直接resize进行识别 311 | #---------------------------------------------------------# 312 | image_data = resize_image(image, (self.input_shape[1],self.input_shape[0]), self.letterbox_image) 313 | #---------------------------------------------------------# 314 | # 添加上batch_size维度,并进行归一化 315 | #---------------------------------------------------------# 316 | image_data = np.expand_dims(preprocess_input(np.array(image_data, dtype='float32')), 0) 317 | 318 | out_boxes, out_scores, out_classes = self.sess.run( 319 | [self.boxes, self.scores, self.classes], 320 | feed_dict={ 321 | self.yolo_model.input: image_data, 322 | self.input_image_shape: [image.size[1], image.size[0]], 323 | K.learning_phase(): 0 324 | }) 325 | 326 | for i, c in enumerate(out_classes): 327 | predicted_class = self.class_names[int(c)] 328 | score = str(out_scores[i]) 329 | top, left, bottom, right = out_boxes[i] 330 | if predicted_class not in class_names: 331 | continue 332 | 333 | 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)))) 334 | 335 | f.close() 336 | return 337 | 338 | def close_session(self): 339 | self.sess.close() 340 | -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import os 3 | 4 | import keras.backend as K 5 | import tensorflow as tf 6 | from keras.callbacks import (EarlyStopping, LearningRateScheduler, 7 | ModelCheckpoint, TensorBoard) 8 | from keras.layers import Conv2D, Dense, DepthwiseConv2D 9 | from keras.optimizers import SGD, Adam 10 | from keras.regularizers import l2 11 | from keras.utils.multi_gpu_utils import multi_gpu_model 12 | 13 | from nets.yolo import get_train_model, yolo_body 14 | from nets.yolo_training import get_lr_scheduler 15 | from utils.callbacks import EvalCallback, LossHistory, ParallelModelCheckpoint 16 | from utils.dataloader import YoloDatasets 17 | from utils.utils import get_anchors, get_classes, show_config 18 | 19 | tf.logging.set_verbosity(tf.logging.ERROR) 20 | 21 | ''' 22 | 训练自己的目标检测模型一定需要注意以下几点: 23 | 1、训练前仔细检查自己的格式是否满足要求,该库要求数据集格式为VOC格式,需要准备好的内容有输入图片和标签 24 | 输入图片为.jpg图片,无需固定大小,传入训练前会自动进行resize。 25 | 灰度图会自动转成RGB图片进行训练,无需自己修改。 26 | 输入图片如果后缀非jpg,需要自己批量转成jpg后再开始训练。 27 | 28 | 标签为.xml格式,文件中会有需要检测的目标信息,标签文件和输入图片文件相对应。 29 | 30 | 2、损失值的大小用于判断是否收敛,比较重要的是有收敛的趋势,即验证集损失不断下降,如果验证集损失基本上不改变的话,模型基本上就收敛了。 31 | 损失值的具体大小并没有什么意义,大和小只在于损失的计算方式,并不是接近于0才好。如果想要让损失好看点,可以直接到对应的损失函数里面除上10000。 32 | 训练过程中的损失值会保存在logs文件夹下的loss_%Y_%m_%d_%H_%M_%S文件夹中 33 | 34 | 3、训练好的权值文件保存在logs文件夹中,每个训练世代(Epoch)包含若干训练步长(Step),每个训练步长(Step)进行一次梯度下降。 35 | 如果只是训练了几个Step是不会保存的,Epoch和Step的概念要捋清楚一下。 36 | ''' 37 | if __name__ == "__main__": 38 | #---------------------------------------------------------------------# 39 | # train_gpu 训练用到的GPU 40 | # 默认为第一张卡、双卡为[0, 1]、三卡为[0, 1, 2] 41 | # 在使用多GPU时,每个卡上的batch为总batch除以卡的数量。 42 | #---------------------------------------------------------------------# 43 | train_gpu = [0,] 44 | #---------------------------------------------------------------------# 45 | # classes_path 指向model_data下的txt,与自己训练的数据集相关 46 | # 训练前一定要修改classes_path,使其对应自己的数据集 47 | #---------------------------------------------------------------------# 48 | classes_path = 'model_data/voc_classes.txt' 49 | #---------------------------------------------------------------------# 50 | # anchors_path 代表先验框对应的txt文件,一般不修改。 51 | # anchors_mask 用于帮助代码找到对应的先验框,一般不修改。 52 | #---------------------------------------------------------------------# 53 | anchors_path = 'model_data/yolo_anchors.txt' 54 | anchors_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]] 55 | #----------------------------------------------------------------------------------------------------------------------------# 56 | # 权值文件的下载请看README,可以通过网盘下载。模型的 预训练权重 对不同数据集是通用的,因为特征是通用的。 57 | # 模型的 预训练权重 比较重要的部分是 主干特征提取网络的权值部分,用于进行特征提取。 58 | # 预训练权重对于99%的情况都必须要用,不用的话主干部分的权值太过随机,特征提取效果不明显,网络训练的结果也不会好 59 | # 60 | # 如果训练过程中存在中断训练的操作,可以将model_path设置成logs文件夹下的权值文件,将已经训练了一部分的权值再次载入。 61 | # 同时修改下方的 冻结阶段 或者 解冻阶段 的参数,来保证模型epoch的连续性。 62 | # 63 | # 当model_path = ''的时候不加载整个模型的权值。 64 | # 65 | # 此处使用的是整个模型的权重,因此是在train.py进行加载的。 66 | # 如果想要让模型从0开始训练,则设置model_path = '',下面的Freeze_Train = Fasle,此时从0开始训练,且没有冻结主干的过程。 67 | # 68 | # 一般来讲,网络从0开始的训练效果会很差,因为权值太过随机,特征提取效果不明显,因此非常、非常、非常不建议大家从0开始训练! 69 | # 从0开始训练有两个方案: 70 | # 1、得益于Mosaic数据增强方法强大的数据增强能力,将UnFreeze_Epoch设置的较大(300及以上)、batch较大(16及以上)、数据较多(万以上)的情况下, 71 | # 可以设置mosaic=True,直接随机初始化参数开始训练,但得到的效果仍然不如有预训练的情况。(像COCO这样的大数据集可以这样做) 72 | # 2、了解imagenet数据集,首先训练分类模型,获得网络的主干部分权值,分类模型的 主干部分 和该模型通用,基于此进行训练。 73 | #----------------------------------------------------------------------------------------------------------------------------# 74 | model_path = 'model_data/yolov5_s.h5' 75 | #------------------------------------------------------# 76 | # input_shape 输入的shape大小,一定要是32的倍数 77 | #------------------------------------------------------# 78 | input_shape = [640, 640] 79 | #------------------------------------------------------# 80 | # phi 所使用的YoloV5的版本。s、m、l、x 81 | #------------------------------------------------------# 82 | phi = 's' 83 | #------------------------------------------------------------------# 84 | # mosaic 马赛克数据增强。 85 | # mosaic_prob 每个step有多少概率使用mosaic数据增强,默认50%。 86 | # 87 | # mixup 是否使用mixup数据增强,仅在mosaic=True时有效。 88 | # 只会对mosaic增强后的图片进行mixup的处理。 89 | # mixup_prob 有多少概率在mosaic后使用mixup数据增强,默认50%。 90 | # 总的mixup概率为mosaic_prob * mixup_prob。 91 | # 92 | # special_aug_ratio 参考YoloX,由于Mosaic生成的训练图片,远远脱离自然图片的真实分布。 93 | # 当mosaic=True时,本代码会在special_aug_ratio范围内开启mosaic。 94 | # 默认为前70%个epoch,100个世代会开启70个世代。 95 | #------------------------------------------------------------------# 96 | mosaic = True 97 | mosaic_prob = 0.5 98 | mixup = True 99 | mixup_prob = 0.5 100 | special_aug_ratio = 0.7 101 | #------------------------------------------------------------------# 102 | # label_smoothing 标签平滑。一般0.01以下。如0.01、0.005。 103 | #------------------------------------------------------------------# 104 | label_smoothing = 0 105 | 106 | #----------------------------------------------------------------------------------------------------------------------------# 107 | # 训练分为两个阶段,分别是冻结阶段和解冻阶段。设置冻结阶段是为了满足机器性能不足的同学的训练需求。 108 | # 冻结训练需要的显存较小,显卡非常差的情况下,可设置Freeze_Epoch等于UnFreeze_Epoch,Freeze_Train = True,此时仅仅进行冻结训练。 109 | # 110 | # 在此提供若干参数设置建议,各位训练者根据自己的需求进行灵活调整: 111 | # (一)从整个模型的预训练权重开始训练: 112 | # Adam: 113 | # Init_Epoch = 0,Freeze_Epoch = 50,UnFreeze_Epoch = 100,Freeze_Train = True,optimizer_type = 'adam',Init_lr = 1e-3,weight_decay = 0。(冻结) 114 | # Init_Epoch = 0,UnFreeze_Epoch = 100,Freeze_Train = False,optimizer_type = 'adam',Init_lr = 1e-3,weight_decay = 0。(不冻结) 115 | # SGD: 116 | # Init_Epoch = 0,Freeze_Epoch = 50,UnFreeze_Epoch = 300,Freeze_Train = True,optimizer_type = 'sgd',Init_lr = 1e-2,weight_decay = 5e-4。(冻结) 117 | # Init_Epoch = 0,UnFreeze_Epoch = 300,Freeze_Train = False,optimizer_type = 'sgd',Init_lr = 1e-2,weight_decay = 5e-4。(不冻结) 118 | # 其中:UnFreeze_Epoch可以在100-300之间调整。 119 | # (二)从0开始训练: 120 | # Init_Epoch = 0,UnFreeze_Epoch >= 300,Unfreeze_batch_size >= 16,Freeze_Train = False(不冻结训练) 121 | # 其中:UnFreeze_Epoch尽量不小于300。optimizer_type = 'sgd',Init_lr = 1e-2,mosaic = True。 122 | # (三)batch_size的设置: 123 | # 在显卡能够接受的范围内,以大为好。显存不足与数据集大小无关,提示显存不足(OOM或者CUDA out of memory)请调小batch_size。 124 | # 受到BatchNorm层影响,batch_size最小为2,不能为1。 125 | # 正常情况下Freeze_batch_size建议为Unfreeze_batch_size的1-2倍。不建议设置的差距过大,因为关系到学习率的自动调整。 126 | #----------------------------------------------------------------------------------------------------------------------------# 127 | #------------------------------------------------------------------# 128 | # 冻结阶段训练参数 129 | # 此时模型的主干被冻结了,特征提取网络不发生改变 130 | # 占用的显存较小,仅对网络进行微调 131 | # Init_Epoch 模型当前开始的训练世代,其值可以大于Freeze_Epoch,如设置: 132 | # Init_Epoch = 60、Freeze_Epoch = 50、UnFreeze_Epoch = 100 133 | # 会跳过冻结阶段,直接从60代开始,并调整对应的学习率。 134 | # (断点续练时使用) 135 | # Freeze_Epoch 模型冻结训练的Freeze_Epoch 136 | # (当Freeze_Train=False时失效) 137 | # Freeze_batch_size 模型冻结训练的batch_size 138 | # (当Freeze_Train=False时失效) 139 | #------------------------------------------------------------------# 140 | Init_Epoch = 0 141 | Freeze_Epoch = 50 142 | Freeze_batch_size = 16 143 | #------------------------------------------------------------------# 144 | # 解冻阶段训练参数 145 | # 此时模型的主干不被冻结了,特征提取网络会发生改变 146 | # 占用的显存较大,网络所有的参数都会发生改变 147 | # UnFreeze_Epoch 模型总共训练的epoch 148 | # SGD需要更长的时间收敛,因此设置较大的UnFreeze_Epoch 149 | # Adam可以使用相对较小的UnFreeze_Epoch 150 | # Unfreeze_batch_size 模型在解冻后的batch_size 151 | #------------------------------------------------------------------# 152 | UnFreeze_Epoch = 300 153 | Unfreeze_batch_size = 8 154 | #------------------------------------------------------------------# 155 | # Freeze_Train 是否进行冻结训练 156 | # 默认先冻结主干训练后解冻训练。 157 | #------------------------------------------------------------------# 158 | Freeze_Train = True 159 | 160 | #------------------------------------------------------------------# 161 | # 其它训练参数:学习率、优化器、学习率下降有关 162 | #------------------------------------------------------------------# 163 | #------------------------------------------------------------------# 164 | # Init_lr 模型的最大学习率 165 | # 当使用Adam优化器时建议设置 Init_lr=1e-3 166 | # 当使用SGD优化器时建议设置 Init_lr=1e-2 167 | # Min_lr 模型的最小学习率,默认为最大学习率的0.01 168 | #------------------------------------------------------------------# 169 | Init_lr = 1e-2 170 | Min_lr = Init_lr * 0.01 171 | #------------------------------------------------------------------# 172 | # optimizer_type 使用到的优化器种类,可选的有adam、sgd 173 | # 当使用Adam优化器时建议设置 Init_lr=1e-3 174 | # 当使用SGD优化器时建议设置 Init_lr=1e-2 175 | # momentum 优化器内部使用到的momentum参数 176 | # weight_decay 权值衰减,可防止过拟合 177 | # adam会导致weight_decay错误,使用adam时建议设置为0。 178 | #------------------------------------------------------------------# 179 | optimizer_type = "sgd" 180 | momentum = 0.937 181 | weight_decay = 5e-4 182 | #------------------------------------------------------------------# 183 | # lr_decay_type 使用到的学习率下降方式,可选的有'step'、'cos' 184 | #------------------------------------------------------------------# 185 | lr_decay_type = 'cos' 186 | #------------------------------------------------------------------# 187 | # save_period 多少个epoch保存一次权值 188 | #------------------------------------------------------------------# 189 | save_period = 10 190 | #------------------------------------------------------------------# 191 | # save_dir 权值与日志文件保存的文件夹 192 | #------------------------------------------------------------------# 193 | save_dir = 'logs' 194 | #------------------------------------------------------------------# 195 | # eval_flag 是否在训练时进行评估,评估对象为验证集 196 | # 安装pycocotools库后,评估体验更佳。 197 | # eval_period 代表多少个epoch评估一次,不建议频繁的评估 198 | # 评估需要消耗较多的时间,频繁评估会导致训练非常慢 199 | # 此处获得的mAP会与get_map.py获得的会有所不同,原因有二: 200 | # (一)此处获得的mAP为验证集的mAP。 201 | # (二)此处设置评估参数较为保守,目的是加快评估速度。 202 | #------------------------------------------------------------------# 203 | eval_flag = True 204 | eval_period = 10 205 | #------------------------------------------------------------------# 206 | # num_workers 用于设置是否使用多线程读取数据,1代表关闭多线程 207 | # 开启后会加快数据读取速度,但是会占用更多内存 208 | # keras里开启多线程有些时候速度反而慢了许多 209 | # 在IO为瓶颈的时候再开启多线程,即GPU运算速度远大于读取图片的速度。 210 | #------------------------------------------------------------------# 211 | num_workers = 1 212 | 213 | #------------------------------------------------------# 214 | # train_annotation_path 训练图片路径和标签 215 | # val_annotation_path 验证图片路径和标签 216 | #------------------------------------------------------# 217 | train_annotation_path = '2007_train.txt' 218 | val_annotation_path = '2007_val.txt' 219 | 220 | #------------------------------------------------------# 221 | # 设置用到的显卡 222 | #------------------------------------------------------# 223 | os.environ["CUDA_VISIBLE_DEVICES"] = ','.join(str(x) for x in train_gpu) 224 | ngpus_per_node = len(train_gpu) 225 | print('Number of devices: {}'.format(ngpus_per_node)) 226 | 227 | #----------------------------------------------------# 228 | # 获取classes和anchor 229 | #----------------------------------------------------# 230 | class_names, num_classes = get_classes(classes_path) 231 | anchors, num_anchors = get_anchors(anchors_path) 232 | 233 | K.clear_session() 234 | #------------------------------------------------------# 235 | # 创建yolo模型 236 | #------------------------------------------------------# 237 | model_body = yolo_body((None, None, 3), anchors_mask, num_classes, phi) 238 | if model_path != '': 239 | #------------------------------------------------------# 240 | # 载入预训练权重 241 | #------------------------------------------------------# 242 | print('Load weights {}.'.format(model_path)) 243 | model_body.load_weights(model_path, by_name=True, skip_mismatch=True) 244 | 245 | if ngpus_per_node > 1: 246 | model = multi_gpu_model(model_body, gpus=ngpus_per_node) 247 | model = get_train_model(model, input_shape, num_classes, anchors, anchors_mask, label_smoothing) 248 | else: 249 | model = get_train_model(model_body, input_shape, num_classes, anchors, anchors_mask, label_smoothing) 250 | 251 | #---------------------------# 252 | # 读取数据集对应的txt 253 | #---------------------------# 254 | with open(train_annotation_path, encoding='utf-8') as f: 255 | train_lines = f.readlines() 256 | with open(val_annotation_path, encoding='utf-8') as f: 257 | val_lines = f.readlines() 258 | num_train = len(train_lines) 259 | num_val = len(val_lines) 260 | 261 | show_config( 262 | classes_path = classes_path, anchors_path = anchors_path, anchors_mask = anchors_mask, model_path = model_path, input_shape = input_shape, \ 263 | Init_Epoch = Init_Epoch, Freeze_Epoch = Freeze_Epoch, UnFreeze_Epoch = UnFreeze_Epoch, Freeze_batch_size = Freeze_batch_size, Unfreeze_batch_size = Unfreeze_batch_size, Freeze_Train = Freeze_Train, \ 264 | Init_lr = Init_lr, Min_lr = Min_lr, optimizer_type = optimizer_type, momentum = momentum, lr_decay_type = lr_decay_type, \ 265 | save_period = save_period, save_dir = save_dir, num_workers = num_workers, num_train = num_train, num_val = num_val 266 | ) 267 | #---------------------------------------------------------# 268 | # 总训练世代指的是遍历全部数据的总次数 269 | # 总训练步长指的是梯度下降的总次数 270 | # 每个训练世代包含若干训练步长,每个训练步长进行一次梯度下降。 271 | # 此处仅建议最低训练世代,上不封顶,计算时只考虑了解冻部分 272 | #----------------------------------------------------------# 273 | wanted_step = 5e4 if optimizer_type == "sgd" else 1.5e4 274 | total_step = num_train // Unfreeze_batch_size * UnFreeze_Epoch 275 | if total_step <= wanted_step: 276 | if num_train // Unfreeze_batch_size == 0: 277 | raise ValueError('数据集过小,无法进行训练,请扩充数据集。') 278 | wanted_epoch = wanted_step // (num_train // Unfreeze_batch_size) + 1 279 | print("\n\033[1;33;44m[Warning] 使用%s优化器时,建议将训练总步长设置到%d以上。\033[0m"%(optimizer_type, wanted_step)) 280 | print("\033[1;33;44m[Warning] 本次运行的总训练数据量为%d,Unfreeze_batch_size为%d,共训练%d个Epoch,计算出总训练步长为%d。\033[0m"%(num_train, Unfreeze_batch_size, UnFreeze_Epoch, total_step)) 281 | print("\033[1;33;44m[Warning] 由于总训练步长为%d,小于建议总步长%d,建议设置总世代为%d。\033[0m"%(total_step, wanted_step, wanted_epoch)) 282 | 283 | for layer in model_body.layers: 284 | if isinstance(layer, DepthwiseConv2D): 285 | layer.add_loss(l2(weight_decay)(layer.depthwise_kernel)) 286 | elif isinstance(layer, Conv2D) or isinstance(layer, Dense): 287 | layer.add_loss(l2(weight_decay)(layer.kernel)) 288 | 289 | #------------------------------------------------------# 290 | # 主干特征提取网络特征通用,冻结训练可以加快训练速度 291 | # 也可以在训练初期防止权值被破坏。 292 | # Init_Epoch为起始世代 293 | # Freeze_Epoch为冻结训练的世代 294 | # UnFreeze_Epoch总训练世代 295 | # 提示OOM或者显存不足请调小Batch_size 296 | #------------------------------------------------------# 297 | if True: 298 | if Freeze_Train: 299 | freeze_layers = {'s': 125, 'm': 179, 'l': 234, 'x': 290}[phi] 300 | for i in range(freeze_layers): model_body.layers[i].trainable = False 301 | print('Freeze the first {} layers of total {} layers.'.format(freeze_layers, len(model_body.layers))) 302 | 303 | #-------------------------------------------------------------------# 304 | # 如果不冻结训练的话,直接设置batch_size为Unfreeze_batch_size 305 | #-------------------------------------------------------------------# 306 | batch_size = Freeze_batch_size if Freeze_Train else Unfreeze_batch_size 307 | start_epoch = Init_Epoch 308 | end_epoch = Freeze_Epoch if Freeze_Train else UnFreeze_Epoch 309 | 310 | #-------------------------------------------------------------------# 311 | # 判断当前batch_size,自适应调整学习率 312 | #-------------------------------------------------------------------# 313 | nbs = 64 314 | lr_limit_max = 1e-3 if optimizer_type == 'adam' else 5e-2 315 | lr_limit_min = 3e-4 if optimizer_type == 'adam' else 5e-4 316 | Init_lr_fit = min(max(batch_size / nbs * Init_lr, lr_limit_min), lr_limit_max) 317 | Min_lr_fit = min(max(batch_size / nbs * Min_lr, lr_limit_min * 1e-2), lr_limit_max * 1e-2) 318 | 319 | optimizer = { 320 | 'adam' : Adam(lr = Init_lr_fit, beta_1 = momentum), 321 | 'sgd' : SGD(lr = Init_lr_fit, momentum = momentum, nesterov=True) 322 | }[optimizer_type] 323 | model.compile(optimizer = optimizer, loss={'yolo_loss': lambda y_true, y_pred: y_pred}) 324 | 325 | #---------------------------------------# 326 | # 获得学习率下降的公式 327 | #---------------------------------------# 328 | lr_scheduler_func = get_lr_scheduler(lr_decay_type, Init_lr_fit, Min_lr_fit, UnFreeze_Epoch) 329 | 330 | epoch_step = num_train // batch_size 331 | epoch_step_val = num_val // batch_size 332 | 333 | if epoch_step == 0 or epoch_step_val == 0: 334 | raise ValueError('数据集过小,无法进行训练,请扩充数据集。') 335 | 336 | train_dataloader = YoloDatasets(train_lines, input_shape, anchors, batch_size, num_classes, anchors_mask, Init_Epoch, UnFreeze_Epoch, \ 337 | mosaic=mosaic, mixup=mixup, mosaic_prob=mosaic_prob, mixup_prob=mixup_prob, train=True, special_aug_ratio=special_aug_ratio) 338 | val_dataloader = YoloDatasets(val_lines, input_shape, anchors, batch_size, num_classes, anchors_mask, Init_Epoch, UnFreeze_Epoch, \ 339 | mosaic=False, mixup=False, mosaic_prob=0, mixup_prob=0, train=False, special_aug_ratio=0) 340 | 341 | #-------------------------------------------------------------------------------# 342 | # 训练参数的设置 343 | # logging 用于设置tensorboard的保存地址 344 | # checkpoint 用于设置权值保存的细节,period用于修改多少epoch保存一次 345 | # lr_scheduler 用于设置学习率下降的方式 346 | # early_stopping 用于设定早停,val_loss多次不下降自动结束训练,表示模型基本收敛 347 | #-------------------------------------------------------------------------------# 348 | time_str = datetime.datetime.strftime(datetime.datetime.now(),'%Y_%m_%d_%H_%M_%S') 349 | log_dir = os.path.join(save_dir, "loss_" + str(time_str)) 350 | logging = TensorBoard(log_dir) 351 | loss_history = LossHistory(log_dir) 352 | if ngpus_per_node > 1: 353 | checkpoint = ParallelModelCheckpoint(model_body, os.path.join(save_dir, "ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5"), 354 | monitor = 'val_loss', save_weights_only = True, save_best_only = False, period = save_period) 355 | checkpoint_last = ParallelModelCheckpoint(model_body, os.path.join(save_dir, "last_epoch_weights.h5"), 356 | monitor = 'val_loss', save_weights_only = True, save_best_only = False, period = 1) 357 | checkpoint_best = ParallelModelCheckpoint(model_body, os.path.join(save_dir, "best_epoch_weights.h5"), 358 | monitor = 'val_loss', save_weights_only = True, save_best_only = True, period = 1) 359 | else: 360 | checkpoint = ModelCheckpoint(os.path.join(save_dir, "ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5"), 361 | monitor = 'val_loss', save_weights_only = True, save_best_only = False, period = save_period) 362 | checkpoint_last = ModelCheckpoint(os.path.join(save_dir, "last_epoch_weights.h5"), 363 | monitor = 'val_loss', save_weights_only = True, save_best_only = False, period = 1) 364 | checkpoint_best = ModelCheckpoint(os.path.join(save_dir, "best_epoch_weights.h5"), 365 | monitor = 'val_loss', save_weights_only = True, save_best_only = True, period = 1) 366 | early_stopping = EarlyStopping(monitor='val_loss', min_delta = 0, patience = 10, verbose = 1) 367 | lr_scheduler = LearningRateScheduler(lr_scheduler_func, verbose = 1) 368 | eval_callback = EvalCallback(model_body, input_shape, anchors, anchors_mask, class_names, num_classes, val_lines, log_dir, \ 369 | eval_flag=eval_flag, period=eval_period) 370 | callbacks = [logging, loss_history, checkpoint, checkpoint_last, checkpoint_best, lr_scheduler, eval_callback] 371 | 372 | if start_epoch < end_epoch: 373 | print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) 374 | model.fit_generator( 375 | generator = train_dataloader, 376 | steps_per_epoch = epoch_step, 377 | validation_data = val_dataloader, 378 | validation_steps = epoch_step_val, 379 | epochs = end_epoch, 380 | initial_epoch = start_epoch, 381 | use_multiprocessing = True if num_workers > 1 else False, 382 | workers = num_workers, 383 | callbacks = callbacks 384 | ) 385 | #---------------------------------------# 386 | # 如果模型有冻结学习部分 387 | # 则解冻,并设置参数 388 | #---------------------------------------# 389 | if Freeze_Train: 390 | batch_size = Unfreeze_batch_size 391 | start_epoch = Freeze_Epoch if start_epoch < Freeze_Epoch else start_epoch 392 | end_epoch = UnFreeze_Epoch 393 | 394 | #-------------------------------------------------------------------# 395 | # 判断当前batch_size,自适应调整学习率 396 | #-------------------------------------------------------------------# 397 | nbs = 64 398 | lr_limit_max = 1e-3 if optimizer_type == 'adam' else 5e-2 399 | lr_limit_min = 3e-4 if optimizer_type == 'adam' else 5e-4 400 | Init_lr_fit = min(max(batch_size / nbs * Init_lr, lr_limit_min), lr_limit_max) 401 | Min_lr_fit = min(max(batch_size / nbs * Min_lr, lr_limit_min * 1e-2), lr_limit_max * 1e-2) 402 | #---------------------------------------# 403 | # 获得学习率下降的公式 404 | #---------------------------------------# 405 | lr_scheduler_func = get_lr_scheduler(lr_decay_type, Init_lr_fit, Min_lr_fit, UnFreeze_Epoch) 406 | lr_scheduler = LearningRateScheduler(lr_scheduler_func, verbose = 1) 407 | callbacks = [logging, loss_history, checkpoint, checkpoint_last, checkpoint_best, lr_scheduler, eval_callback] 408 | 409 | for i in range(len(model_body.layers)): 410 | model_body.layers[i].trainable = True 411 | model.compile(optimizer = optimizer, loss={'yolo_loss': lambda y_true, y_pred: y_pred}) 412 | 413 | epoch_step = num_train // batch_size 414 | epoch_step_val = num_val // batch_size 415 | 416 | if epoch_step == 0 or epoch_step_val == 0: 417 | raise ValueError("数据集过小,无法继续进行训练,请扩充数据集。") 418 | 419 | train_dataloader.batch_size = Unfreeze_batch_size 420 | val_dataloader.batch_size = Unfreeze_batch_size 421 | 422 | print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size)) 423 | model.fit_generator( 424 | generator = train_dataloader, 425 | steps_per_epoch = epoch_step, 426 | validation_data = val_dataloader, 427 | validation_steps = epoch_step_val, 428 | epochs = end_epoch, 429 | initial_epoch = start_epoch, 430 | use_multiprocessing = True if num_workers > 1 else False, 431 | workers = num_workers, 432 | callbacks = callbacks 433 | ) 434 | -------------------------------------------------------------------------------- /常见问题汇总.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 | -------------------------------------------------------------------------------- /utils/dataloader.py: -------------------------------------------------------------------------------- 1 | import math 2 | from random import shuffle, sample 3 | 4 | import cv2 5 | import keras 6 | import numpy as np 7 | from PIL import Image 8 | from utils.utils import cvtColor, preprocess_input 9 | 10 | 11 | class YoloDatasets(keras.utils.Sequence): 12 | def __init__(self, annotation_lines, input_shape, anchors, batch_size, num_classes, anchors_mask, epoch_now, epoch_length, \ 13 | mosaic, mixup, mosaic_prob, mixup_prob, train, special_aug_ratio = 0.7): 14 | self.annotation_lines = annotation_lines 15 | self.length = len(self.annotation_lines) 16 | 17 | self.input_shape = input_shape 18 | self.anchors = anchors 19 | self.batch_size = batch_size 20 | self.num_classes = num_classes 21 | self.anchors_mask = anchors_mask 22 | self.epoch_now = epoch_now - 1 23 | self.epoch_length = epoch_length 24 | self.mosaic = mosaic 25 | self.mosaic_prob = mosaic_prob 26 | self.mixup = mixup 27 | self.mixup_prob = mixup_prob 28 | self.train = train 29 | self.special_aug_ratio = special_aug_ratio 30 | 31 | self.threshold = 4 32 | 33 | def __len__(self): 34 | return math.ceil(len(self.annotation_lines) / float(self.batch_size)) 35 | 36 | def __getitem__(self, index): 37 | image_data = [] 38 | box_data = [] 39 | for i in range(index * self.batch_size, (index + 1) * self.batch_size): 40 | i = i % self.length 41 | #---------------------------------------------------# 42 | # 训练时进行数据的随机增强 43 | # 验证时不进行数据的随机增强 44 | #---------------------------------------------------# 45 | if self.mosaic and self.rand() < self.mosaic_prob and self.epoch_now < self.epoch_length * self.special_aug_ratio: 46 | lines = sample(self.annotation_lines, 3) 47 | lines.append(self.annotation_lines[i]) 48 | shuffle(lines) 49 | image, box = self.get_random_data_with_Mosaic(lines, self.input_shape) 50 | 51 | if self.mixup and self.rand() < self.mixup_prob: 52 | lines = sample(self.annotation_lines, 1) 53 | image_2, box_2 = self.get_random_data(lines[0], self.input_shape, random = self.train) 54 | image, box = self.get_random_data_with_MixUp(image, box, image_2, box_2) 55 | else: 56 | image, box = self.get_random_data(self.annotation_lines[i], self.input_shape, random = self.train) 57 | image_data.append(preprocess_input(np.array(image, np.float32))) 58 | box_data.append(box) 59 | 60 | image_data = np.array(image_data) 61 | box_data = np.array(box_data) 62 | y_true = self.preprocess_true_boxes(box_data, self.input_shape, self.anchors, self.num_classes) 63 | return [image_data, *y_true], np.zeros(self.batch_size) 64 | 65 | def on_epoch_end(self): 66 | self.epoch_now += 1 67 | shuffle(self.annotation_lines) 68 | 69 | def rand(self, a=0, b=1): 70 | return np.random.rand()*(b-a) + a 71 | 72 | def get_random_data(self, annotation_line, input_shape, max_boxes=500, jitter=.3, hue=.1, sat=0.7, val=0.4, random=True): 73 | line = annotation_line.split() 74 | #------------------------------# 75 | # 读取图像并转换成RGB图像 76 | #------------------------------# 77 | image = Image.open(line[0]) 78 | image = cvtColor(image) 79 | #------------------------------# 80 | # 获得图像的高宽与目标高宽 81 | #------------------------------# 82 | iw, ih = image.size 83 | h, w = input_shape 84 | #------------------------------# 85 | # 获得预测框 86 | #------------------------------# 87 | box = np.array([np.array(list(map(int,box.split(',')))) for box in line[1:]]) 88 | 89 | if not random: 90 | scale = min(w/iw, h/ih) 91 | nw = int(iw*scale) 92 | nh = int(ih*scale) 93 | dx = (w-nw)//2 94 | dy = (h-nh)//2 95 | 96 | #---------------------------------# 97 | # 将图像多余的部分加上灰条 98 | #---------------------------------# 99 | image = image.resize((nw,nh), Image.BICUBIC) 100 | new_image = Image.new('RGB', (w,h), (128,128,128)) 101 | new_image.paste(image, (dx, dy)) 102 | image_data = np.array(new_image, np.float32) 103 | 104 | #---------------------------------# 105 | # 对真实框进行调整 106 | #---------------------------------# 107 | box_data = np.zeros((max_boxes,5)) 108 | if len(box)>0: 109 | np.random.shuffle(box) 110 | box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx 111 | box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy 112 | box[:, 0:2][box[:, 0:2]<0] = 0 113 | box[:, 2][box[:, 2]>w] = w 114 | box[:, 3][box[:, 3]>h] = h 115 | box_w = box[:, 2] - box[:, 0] 116 | box_h = box[:, 3] - box[:, 1] 117 | box = box[np.logical_and(box_w>1, box_h>1)] 118 | if len(box)>max_boxes: box = box[:max_boxes] 119 | box_data[:len(box)] = box 120 | 121 | return image_data, box_data 122 | 123 | #------------------------------------------# 124 | # 对图像进行缩放并且进行长和宽的扭曲 125 | #------------------------------------------# 126 | new_ar = iw/ih * self.rand(1-jitter,1+jitter) / self.rand(1-jitter,1+jitter) 127 | scale = self.rand(.25, 2) 128 | if new_ar < 1: 129 | nh = int(scale*h) 130 | nw = int(nh*new_ar) 131 | else: 132 | nw = int(scale*w) 133 | nh = int(nw/new_ar) 134 | image = image.resize((nw,nh), Image.BICUBIC) 135 | 136 | #------------------------------------------# 137 | # 将图像多余的部分加上灰条 138 | #------------------------------------------# 139 | dx = int(self.rand(0, w-nw)) 140 | dy = int(self.rand(0, h-nh)) 141 | new_image = Image.new('RGB', (w,h), (128,128,128)) 142 | new_image.paste(image, (dx, dy)) 143 | image = new_image 144 | 145 | #------------------------------------------# 146 | # 翻转图像 147 | #------------------------------------------# 148 | flip = self.rand()<.5 149 | if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT) 150 | 151 | image_data = np.array(image, np.uint8) 152 | #---------------------------------# 153 | # 对图像进行色域变换 154 | # 计算色域变换的参数 155 | #---------------------------------# 156 | r = np.random.uniform(-1, 1, 3) * [hue, sat, val] + 1 157 | #---------------------------------# 158 | # 将图像转到HSV上 159 | #---------------------------------# 160 | hue, sat, val = cv2.split(cv2.cvtColor(image_data, cv2.COLOR_RGB2HSV)) 161 | dtype = image_data.dtype 162 | #---------------------------------# 163 | # 应用变换 164 | #---------------------------------# 165 | x = np.arange(0, 256, dtype=r.dtype) 166 | lut_hue = ((x * r[0]) % 180).astype(dtype) 167 | lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) 168 | lut_val = np.clip(x * r[2], 0, 255).astype(dtype) 169 | 170 | image_data = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) 171 | image_data = cv2.cvtColor(image_data, cv2.COLOR_HSV2RGB) 172 | 173 | #---------------------------------# 174 | # 对真实框进行调整 175 | #---------------------------------# 176 | box_data = np.zeros((max_boxes,5)) 177 | if len(box)>0: 178 | np.random.shuffle(box) 179 | box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx 180 | box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy 181 | if flip: box[:, [0,2]] = w - box[:, [2,0]] 182 | box[:, 0:2][box[:, 0:2]<0] = 0 183 | box[:, 2][box[:, 2]>w] = w 184 | box[:, 3][box[:, 3]>h] = h 185 | box_w = box[:, 2] - box[:, 0] 186 | box_h = box[:, 3] - box[:, 1] 187 | box = box[np.logical_and(box_w>1, box_h>1)] # discard invalid box 188 | if len(box)>max_boxes: box = box[:max_boxes] 189 | box_data[:len(box)] = box 190 | 191 | return image_data, box_data 192 | 193 | def merge_bboxes(self, bboxes, cutx, cuty): 194 | merge_bbox = [] 195 | for i in range(len(bboxes)): 196 | for box in bboxes[i]: 197 | tmp_box = [] 198 | x1, y1, x2, y2 = box[0], box[1], box[2], box[3] 199 | 200 | if i == 0: 201 | if y1 > cuty or x1 > cutx: 202 | continue 203 | if y2 >= cuty and y1 <= cuty: 204 | y2 = cuty 205 | if x2 >= cutx and x1 <= cutx: 206 | x2 = cutx 207 | 208 | if i == 1: 209 | if y2 < cuty or x1 > cutx: 210 | continue 211 | if y2 >= cuty and y1 <= cuty: 212 | y1 = cuty 213 | if x2 >= cutx and x1 <= cutx: 214 | x2 = cutx 215 | 216 | if i == 2: 217 | if y2 < cuty or x2 < cutx: 218 | continue 219 | if y2 >= cuty and y1 <= cuty: 220 | y1 = cuty 221 | if x2 >= cutx and x1 <= cutx: 222 | x1 = cutx 223 | 224 | if i == 3: 225 | if y1 > cuty or x2 < cutx: 226 | continue 227 | if y2 >= cuty and y1 <= cuty: 228 | y2 = cuty 229 | if x2 >= cutx and x1 <= cutx: 230 | x1 = cutx 231 | tmp_box.append(x1) 232 | tmp_box.append(y1) 233 | tmp_box.append(x2) 234 | tmp_box.append(y2) 235 | tmp_box.append(box[-1]) 236 | merge_bbox.append(tmp_box) 237 | return merge_bbox 238 | 239 | 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): 240 | h, w = input_shape 241 | min_offset_x = self.rand(0.3, 0.7) 242 | min_offset_y = self.rand(0.3, 0.7) 243 | 244 | image_datas = [] 245 | box_datas = [] 246 | index = 0 247 | for line in annotation_line: 248 | #---------------------------------# 249 | # 每一行进行分割 250 | #---------------------------------# 251 | line_content = line.split() 252 | #---------------------------------# 253 | # 打开图片 254 | #---------------------------------# 255 | image = Image.open(line_content[0]) 256 | image = cvtColor(image) 257 | 258 | #---------------------------------# 259 | # 图片的大小 260 | #---------------------------------# 261 | iw, ih = image.size 262 | #---------------------------------# 263 | # 保存框的位置 264 | #---------------------------------# 265 | box = np.array([np.array(list(map(int,box.split(',')))) for box in line_content[1:]]) 266 | 267 | #---------------------------------# 268 | # 是否翻转图片 269 | #---------------------------------# 270 | flip = self.rand()<.5 271 | if flip and len(box)>0: 272 | image = image.transpose(Image.FLIP_LEFT_RIGHT) 273 | box[:, [0,2]] = iw - box[:, [2,0]] 274 | 275 | #------------------------------------------# 276 | # 对图像进行缩放并且进行长和宽的扭曲 277 | #------------------------------------------# 278 | new_ar = iw/ih * self.rand(1-jitter,1+jitter) / self.rand(1-jitter,1+jitter) 279 | scale = self.rand(.4, 1) 280 | if new_ar < 1: 281 | nh = int(scale*h) 282 | nw = int(nh*new_ar) 283 | else: 284 | nw = int(scale*w) 285 | nh = int(nw/new_ar) 286 | image = image.resize((nw, nh), Image.BICUBIC) 287 | 288 | #-----------------------------------------------# 289 | # 将图片进行放置,分别对应四张分割图片的位置 290 | #-----------------------------------------------# 291 | if index == 0: 292 | dx = int(w*min_offset_x) - nw 293 | dy = int(h*min_offset_y) - nh 294 | elif index == 1: 295 | dx = int(w*min_offset_x) - nw 296 | dy = int(h*min_offset_y) 297 | elif index == 2: 298 | dx = int(w*min_offset_x) 299 | dy = int(h*min_offset_y) 300 | elif index == 3: 301 | dx = int(w*min_offset_x) 302 | dy = int(h*min_offset_y) - nh 303 | 304 | new_image = Image.new('RGB', (w,h), (128,128,128)) 305 | new_image.paste(image, (dx, dy)) 306 | image_data = np.array(new_image) 307 | 308 | index = index + 1 309 | box_data = [] 310 | #---------------------------------# 311 | # 对box进行重新处理 312 | #---------------------------------# 313 | if len(box)>0: 314 | np.random.shuffle(box) 315 | box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx 316 | box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy 317 | box[:, 0:2][box[:, 0:2]<0] = 0 318 | box[:, 2][box[:, 2]>w] = w 319 | box[:, 3][box[:, 3]>h] = h 320 | box_w = box[:, 2] - box[:, 0] 321 | box_h = box[:, 3] - box[:, 1] 322 | box = box[np.logical_and(box_w>1, box_h>1)] 323 | box_data = np.zeros((len(box),5)) 324 | box_data[:len(box)] = box 325 | 326 | image_datas.append(image_data) 327 | box_datas.append(box_data) 328 | 329 | #---------------------------------# 330 | # 将图片分割,放在一起 331 | #---------------------------------# 332 | cutx = int(w * min_offset_x) 333 | cuty = int(h * min_offset_y) 334 | 335 | new_image = np.zeros([h, w, 3]) 336 | new_image[:cuty, :cutx, :] = image_datas[0][:cuty, :cutx, :] 337 | new_image[cuty:, :cutx, :] = image_datas[1][cuty:, :cutx, :] 338 | new_image[cuty:, cutx:, :] = image_datas[2][cuty:, cutx:, :] 339 | new_image[:cuty, cutx:, :] = image_datas[3][:cuty, cutx:, :] 340 | 341 | new_image = np.array(new_image, np.uint8) 342 | #---------------------------------# 343 | # 对图像进行色域变换 344 | # 计算色域变换的参数 345 | #---------------------------------# 346 | r = np.random.uniform(-1, 1, 3) * [hue, sat, val] + 1 347 | #---------------------------------# 348 | # 将图像转到HSV上 349 | #---------------------------------# 350 | hue, sat, val = cv2.split(cv2.cvtColor(new_image, cv2.COLOR_RGB2HSV)) 351 | dtype = new_image.dtype 352 | #---------------------------------# 353 | # 应用变换 354 | #---------------------------------# 355 | x = np.arange(0, 256, dtype=r.dtype) 356 | lut_hue = ((x * r[0]) % 180).astype(dtype) 357 | lut_sat = np.clip(x * r[1], 0, 255).astype(dtype) 358 | lut_val = np.clip(x * r[2], 0, 255).astype(dtype) 359 | 360 | new_image = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))) 361 | new_image = cv2.cvtColor(new_image, cv2.COLOR_HSV2RGB) 362 | 363 | #---------------------------------# 364 | # 对框进行进一步的处理 365 | #---------------------------------# 366 | new_boxes = self.merge_bboxes(box_datas, cutx, cuty) 367 | 368 | #---------------------------------# 369 | # 将box进行调整 370 | #---------------------------------# 371 | box_data = np.zeros((max_boxes, 5)) 372 | if len(new_boxes)>0: 373 | if len(new_boxes)>max_boxes: new_boxes = new_boxes[:max_boxes] 374 | box_data[:len(new_boxes)] = new_boxes 375 | return new_image, box_data 376 | 377 | def get_random_data_with_MixUp(self, image_1, box_1, image_2, box_2, max_boxes=500): 378 | new_image = np.array(image_1, np.float32) * 0.5 + np.array(image_2, np.float32) * 0.5 379 | 380 | box_1_wh = box_1[:, 2:4] - box_1[:, 0:2] 381 | box_1_valid = box_1_wh[:, 0] > 0 382 | 383 | box_2_wh = box_2[:, 2:4] - box_2[:, 0:2] 384 | box_2_valid = box_2_wh[:, 0] > 0 385 | 386 | new_boxes = np.concatenate([box_1[box_1_valid, :], box_2[box_2_valid, :]], axis=0) 387 | #---------------------------------# 388 | # 将box进行调整 389 | #---------------------------------# 390 | box_data = np.zeros((max_boxes, 5)) 391 | if len(new_boxes)>0: 392 | if len(new_boxes)>max_boxes: new_boxes = new_boxes[:max_boxes] 393 | box_data[:len(new_boxes)] = new_boxes 394 | return new_image, box_data 395 | 396 | def get_near_points(self, x, y, i, j): 397 | sub_x = x - i 398 | sub_y = y - j 399 | if sub_x > 0.5 and sub_y > 0.5: 400 | return [[0, 0], [1, 0], [0, 1]] 401 | elif sub_x < 0.5 and sub_y > 0.5: 402 | return [[0, 0], [-1, 0], [0, 1]] 403 | elif sub_x < 0.5 and sub_y < 0.5: 404 | return [[0, 0], [-1, 0], [0, -1]] 405 | else: 406 | return [[0, 0], [1, 0], [0, -1]] 407 | 408 | def preprocess_true_boxes(self, true_boxes, input_shape, anchors, num_classes): 409 | assert (true_boxes[..., 4] [9,2] 457 | #-----------------------------------------------------------# 458 | anchors = np.array(anchors, np.float32) 459 | 460 | #-----------------------------------------------------------# 461 | # 长宽要大于0才有效 462 | #-----------------------------------------------------------# 463 | valid_mask = boxes_wh[..., 0]>0 464 | 465 | for b in range(m): 466 | #-----------------------------------------------------------# 467 | # 对每一张图进行处理 468 | #-----------------------------------------------------------# 469 | wh = boxes_wh[b, valid_mask[b]] 470 | 471 | if len(wh) == 0: continue 472 | #-------------------------------------------------------# 473 | # wh : num_true_box, 2 474 | # np.expand_dims(wh, 1) : num_true_box, 1, 2 475 | # anchors : 9, 2 476 | # np.expand_dims(anchors, 0) : 1, 9, 2 477 | # 478 | # ratios_of_gt_anchors代表每一个真实框和每一个先验框的宽高的比值 479 | # ratios_of_gt_anchors : num_true_box, 9, 2 480 | # ratios_of_anchors_gt代表每一个先验框和每一个真实框的宽高的比值 481 | # ratios_of_anchors_gt : num_true_box, 9, 2 482 | # 483 | # ratios : num_true_box, 9, 4 484 | # max_ratios代表每一个真实框和每一个先验框的宽高的比值的最大值 485 | # max_ratios : num_true_box, 9 486 | #-------------------------------------------------------# 487 | ratios_of_gt_anchors = np.expand_dims(wh, 1) / np.expand_dims(anchors, 0) 488 | ratios_of_anchors_gt = np.expand_dims(anchors, 0) / np.expand_dims(wh, 1) 489 | ratios = np.concatenate([ratios_of_gt_anchors, ratios_of_anchors_gt], axis = -1) 490 | max_ratios = np.max(ratios, axis = -1) 491 | 492 | for t, ratio in enumerate(max_ratios): 493 | #-------------------------------------------------------# 494 | # ratio : 9 495 | #-------------------------------------------------------# 496 | over_threshold = ratio < self.threshold 497 | over_threshold[np.argmin(ratio)] = True 498 | #-----------------------------------------------------------# 499 | # 找到每个真实框所属的特征层 500 | #-----------------------------------------------------------# 501 | for l in range(num_layers): 502 | for k, n in enumerate(self.anchors_mask[l]): 503 | if not over_threshold[n]: 504 | continue 505 | #-----------------------------------------------------------# 506 | # floor用于向下取整,找到真实框所属的特征层对应的x、y轴坐标 507 | #-----------------------------------------------------------# 508 | i = np.floor(true_boxes[b,t,0] * grid_shapes[l][1]).astype('int32') 509 | j = np.floor(true_boxes[b,t,1] * grid_shapes[l][0]).astype('int32') 510 | offsets = self.get_near_points(true_boxes[b,t,0] * grid_shapes[l][1], true_boxes[b,t,1] * grid_shapes[l][0], i, j) 511 | for offset in offsets: 512 | local_i = i + offset[0] 513 | local_j = j + offset[1] 514 | 515 | if local_i >= grid_shapes[l][1] or local_i < 0 or local_j >= grid_shapes[l][0] or local_j < 0: 516 | continue 517 | 518 | if box_best_ratios[l][b, local_j, local_i, k] != 0: 519 | if box_best_ratios[l][b, local_j, local_i, k] > ratio[n]: 520 | y_true[l][b, local_j, local_i, k, :] = 0 521 | else: 522 | continue 523 | #-----------------------------------------------------------# 524 | # c指的是当前这个真实框的种类 525 | #-----------------------------------------------------------# 526 | c = true_boxes[b, t, 4].astype('int32') 527 | #-----------------------------------------------------------# 528 | # y_true的shape为(m,20,20,3,85)(m,40,40,3,85)(m,80,80,3,85) 529 | # 最后的85可以拆分成4+1+80,4代表的是框的中心与宽高、 530 | # 1代表的是置信度、80代表的是种类 531 | #-----------------------------------------------------------# 532 | y_true[l][b, local_j, local_i, k, 0:4] = true_boxes[b, t, 0:4] 533 | y_true[l][b, local_j, local_i, k, 4] = 1 534 | y_true[l][b, local_j, local_i, k, 5+c] = 1 535 | box_best_ratios[l][b, local_j, local_i, k] = ratio[n] 536 | 537 | return y_true 538 | --------------------------------------------------------------------------------