|
| 1 | +import os |
| 2 | +import argparse |
| 3 | +import numpy as np |
| 4 | +from keras import backend as K |
| 5 | +from keras.models import load_model |
| 6 | +from keras.layers import Input |
| 7 | +import tensorflow as tf |
| 8 | + |
| 9 | +from yolo4.model import yolo_eval, yolo4_body |
| 10 | + |
| 11 | +# 执行参数 python convertToH5.py --input_size 608 --min_score 0.3 --iou 0.5 --model_path model_data/yolov4.h5 --weights_path model_data/yolov4.weights |
| 12 | +# 外部参数配置 |
| 13 | +parser = argparse.ArgumentParser() |
| 14 | +parser.add_argument('--input_size', type=int, default=608, help='Image input size 320 416 512 608.') |
| 15 | +parser.add_argument('--min_score', type=float, default=0.3, help='minimum output score.') |
| 16 | +parser.add_argument('--iou', type=float, default=0.5, help='target threshold.') |
| 17 | +parser.add_argument('--model_path', type=str, default='model_data/yolov4.h5', help='model save type.') |
| 18 | +parser.add_argument('--weights_path', type=str, default='model_data/yolov4.weights', help='weight file.') |
| 19 | +ARGS = parser.parse_args() |
| 20 | + |
| 21 | +# 数据集识别80类别 |
| 22 | +CLASSES = {0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorbike', 4: 'aeroplane', 5: 'bus', 6: 'train', 7: 'truck', |
| 23 | + 8: 'boat', 9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12: 'parking meter', 13: 'bench', |
| 24 | + 14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', |
| 25 | + 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', |
| 26 | + 29: 'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sports ball', 33: 'kite', 34: 'baseball bat', |
| 27 | + 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle', |
| 28 | + 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', |
| 29 | + 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', |
| 30 | + 55: 'cake', 56: 'chair', 57: 'sofa', 58: 'potted plant', 59: 'bed', 60: 'dining table', 61: 'toilet', |
| 31 | + 62: 'tvmonitor', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone', |
| 32 | + 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', |
| 33 | + 75: 'vase', 76: 'scissors', 77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'} |
| 34 | + |
| 35 | +anchors = np.array([12,16, 19,36, 40,28, 36,75, 76,55, 72,146, 142,110, 192,243, 459,401], dtype=np.float) |
| 36 | + |
| 37 | +class Yolo4(object): |
| 38 | + |
| 39 | + def __init__(self, score, iou, model_path, weights_path,input_size, gpu_num=1): |
| 40 | + self.score = score |
| 41 | + self.input_size = input_size |
| 42 | + self.weights_path = weights_path |
| 43 | + self.model_path = model_path |
| 44 | + self.iou = iou |
| 45 | + self.gpu_num = gpu_num |
| 46 | + self.load_yolo() |
| 47 | + |
| 48 | + # 加载权重 |
| 49 | + def load_weights(self,model, weights_file): |
| 50 | + wf = open(weights_file, 'rb') |
| 51 | + major, minor, revision, seen, _ = np.fromfile(wf, dtype=np.int32, count=5) |
| 52 | + |
| 53 | + j = 0 |
| 54 | + for i in range(110): |
| 55 | + conv_layer_name = 'conv2d_%d' % i if i > 0 else 'conv2d' |
| 56 | + bn_layer_name = 'batch_normalization_%d' % j if j > 0 else 'batch_normalization' |
| 57 | + |
| 58 | + conv_layer = model.get_layer(conv_layer_name) |
| 59 | + filters = conv_layer.filters |
| 60 | + k_size = conv_layer.kernel_size[0] |
| 61 | + in_dim = conv_layer.input_shape[-1] |
| 62 | + |
| 63 | + if i not in [93, 101, 109]: |
| 64 | + # darknet weights: [beta, gamma, mean, variance] |
| 65 | + bn_weights = np.fromfile(wf, dtype=np.float32, count=4 * filters) |
| 66 | + # tf weights: [gamma, beta, mean, variance] |
| 67 | + bn_weights = bn_weights.reshape((4, filters))[[1, 0, 2, 3]] |
| 68 | + bn_layer = model.get_layer(bn_layer_name) |
| 69 | + j += 1 |
| 70 | + else: |
| 71 | + conv_bias = np.fromfile(wf, dtype=np.float32, count=filters) |
| 72 | + |
| 73 | + # darknet shape (out_dim, in_dim, height, width) |
| 74 | + conv_shape = (filters, in_dim, k_size, k_size) |
| 75 | + conv_weights = np.fromfile( |
| 76 | + wf, dtype=np.float32, count=np.product(conv_shape)) |
| 77 | + # tf shape (height, width, in_dim, out_dim) |
| 78 | + conv_weights = conv_weights.reshape(conv_shape).transpose([2, 3, 1, 0]) |
| 79 | + |
| 80 | + if i not in [93, 101, 109]: |
| 81 | + conv_layer.set_weights([conv_weights]) |
| 82 | + bn_layer.set_weights(bn_weights) |
| 83 | + else: |
| 84 | + conv_layer.set_weights([conv_weights, conv_bias]) |
| 85 | + |
| 86 | + assert len(wf.read()) == 0, 'failed to read all data' |
| 87 | + wf.close() |
| 88 | + |
| 89 | + # 保存为h5模型 |
| 90 | + def load_yolo(self): |
| 91 | + model_path = os.path.expanduser(self.model_path) |
| 92 | + assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.' |
| 93 | + |
| 94 | + self.class_names = CLASSES |
| 95 | + self.anchors = np.array(anchors).reshape(-1, 2) |
| 96 | + |
| 97 | + num_anchors = len(self.anchors) |
| 98 | + num_classes = len(self.class_names) |
| 99 | + |
| 100 | + self.sess = tf.compat.v1.Session() |
| 101 | + |
| 102 | + # Load model, or construct model and load weights. |
| 103 | + self.yolo4_model = yolo4_body(Input(shape=(self.input_size, self.input_size, 3)), num_anchors//3, num_classes) |
| 104 | + |
| 105 | + # Read and convert darknet weight |
| 106 | + self.load_weights(self.yolo4_model, self.weights_path) |
| 107 | + |
| 108 | + self.yolo4_model.save(self.model_path) |
| 109 | + |
| 110 | + self.input_image_shape = K.placeholder(shape=(2, )) |
| 111 | + self.boxes, self.scores, self.classes = yolo_eval( |
| 112 | + self.yolo4_model.output, |
| 113 | + self.anchors, |
| 114 | + len(self.class_names), |
| 115 | + self.input_image_shape, |
| 116 | + score_threshold=self.score |
| 117 | + ) |
| 118 | + print('Dome.') |
| 119 | + |
| 120 | + def close_session(self): |
| 121 | + self.sess.close() |
| 122 | + |
| 123 | +if __name__ == '__main__': |
| 124 | + |
| 125 | + yolo4_model = Yolo4(ARGS.min_score, ARGS.iou, ARGS.model_path, ARGS.weights_path, ARGS.input_size) |
| 126 | + |
| 127 | + yolo4_model.close_session() |
0 commit comments