我是靠谱客的博主 迷路花生,这篇文章主要介绍yolov3 keras版本yolo.py各函数解析,现在分享给大家,希望可以做个参考。

 class yolo:获取信息、预训练模型地址、anchor文件位置、类别文件位置、score阈值、IOU阈值、输入图像尺寸、gpu数量。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
#用于融合所有的组件 class YOLO(object): _defaults = { "model_path": 'model_data/yolo.h5', #训练好的模型 "anchors_path": 'model_data/yolo_anchors.txt', # anchor box 9个, 从小到大排列 "classes_path": 'model_data/coco_classes.txt', #类别数 "score" : 0.3, #score 阈值 "iou" : 0.45, #iou 阈值 "model_image_size" : (416, 416), #输入图像尺寸 "gpu_num" : 1, #gpu数量 }

 def get_defaults(cls, n):读取默认值(上边的信息)

复制代码
1
2
3
4
5
6
7
# 使用类方法 @classmethod def get_defaults(cls, n): if n in cls._defaults: return cls._defaults[n] else: return "Unrecognized attribute name '" + n + "'"

 def __init__(self, **kwargs):建立默认值,更新用户覆盖,获取类别名称,anchor,获取keras已经建立的session、boxes.score,类别。

复制代码
1
2
3
4
5
6
7
def __init__(self, **kwargs): self.__dict__.update(self._defaults) # set up default values self.__dict__.update(kwargs) # and update with user overrides self.class_names = self._get_class() #获取类别名称 self.anchors = self._get_anchors() #anchor self.sess = K.get_session() #获取keras已经建立的session self.boxes, self.scores, self.classes = self.generate() #由generate()函数完成目标检测

 def _get_class(self):通过读取类别文件获取类别名。

复制代码
1
2
3
4
5
6
def _get_class(self): classes_path = os.path.expanduser(self.classes_path) #把path中包含的"~"和"~user"转换成用户目录 with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] #默认删除字符串头和尾的空格和换行符 return class_names

def _get_anchors(self):和类别相似,读取anchor文件中的数据。

复制代码
1
2
3
4
5
6
7
def _get_anchors(self): anchors_path = os.path.expanduser(self.anchors_path) with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2)

def generate(self):

①加载权重参数文件,生成检测框,得分,以及对应类别

②利用model.py中的yolo_eval函数生成检测框,得分,所属类别

③初始化时调用generate函数生成图片的检测框,得分,所属类别(self.boxes, self.scores, self.classes)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def generate(self): model_path = os.path.expanduser(self.model_path)#获取model路径 assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.' #判断model是否以h5结尾 # Load model, or construct model and load weights. num_anchors = len(self.anchors) #num_anchors = 9。yolov3有9个先验框 num_classes = len(self.class_names) #num_cliasses = 80。 #coco集一共80类 is_tiny_version = num_anchors==6 # default setting try: self.yolo_model = load_model(model_path, compile=False) except: self.yolo_model = tiny_yolo_body(Input(shape=(None,None,3)), num_anchors//2, num_classes) if is_tiny_version else yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes) self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match else: #[-1]:网络最后一层输出。 output_shape[-1]:输出维度的最后一维。 -> (?,13,13,255) # 255 = 9/3*(80+5). 9/3:每层特征图对应3个anchor box 80:80个类别 5:4+1,框的4个值+1个置信度 assert self.yolo_model.layers[-1].output_shape[-1] == num_anchors/len(self.yolo_model.output) * (num_classes + 5), 'Mismatch between model and given anchor and class sizes' print('{} model, anchors, and classes loaded.'.format(model_path)) # Generate colors for drawing bounding boxes. # 生成绘制边框的颜色。 # h(色调):x/len(self.class_names) s(饱和度):1.0 v(明亮):1.0 # 对于80种coco目标,确定每一种目标框的绘制颜色,即:将(x/80, 1.0, 1.0)的颜色转换为RGB格式,并随机调整颜色以便于肉眼识别, # 其中:一个1.0表示饱和度,一个1.0表示亮度 hsv_tuples = [(x / len(self.class_names), 1., 1.) for x in range(len(self.class_names))] self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) #hsv转换为rgb self.colors = list( # hsv取值范围在【0,1】,而RBG取值范围在【0,255】,所以乘上255 map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), self.colors)) np.random.seed(10101) # Fixed seed for consistent colors across runs.# np.random.seed():产生随机种子。固定种子为一致的颜色 np.random.shuffle(self.colors) # Shuffle colors to decorrelate adjacent classes. # 调整颜色来装饰相邻的类 np.random.seed(None) # Reset seed to default. #重置种子为默认 # Generate output tensor targets for filtered bounding boxes. self.input_image_shape = K.placeholder(shape=(2, )) #K.placeholder:keras中的占位符 相当于分配空间 #shape = (2,) 代表该张量有一个维度,第一个维度长度为2,一维数组1行2列 # 若GPU个数大于等于2,调用multi_gpu_model() if self.gpu_num>=2: self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num) boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors, #yolo_eval():yolo评估函数 len(self.class_names), self.input_image_shape, score_threshold=self.score, iou_threshold=self.iou) return boxes, scores, classes

def detect_image(self, image):(重要)

开始计时->①调用letterbox_image函数,即:先生成一个用“绝对灰”R128-G128-B128填充的416×416新图片,然后用按比例缩放(采样方式:BICUBIC)后的输入图片粘贴,粘贴不到的部分保留为灰色。②model_image_size定义的宽和高必须是32的倍数;若没有定义model_image_size,将输入的尺寸调整为32的倍数,并调用letterbox_image函数进行缩放。③将缩放后的图片数值除以255,做归一化。④将(416,416,3)数组调整为(1,416,416,3)元祖,满足网络输入的张量格式:image_data。

->①运行self.sess.run()输入参数:输入图片416×416,学习模式0测试/1训练。self.yolo_model.input: image_data,self.input_image_shape: [image.size[1], image.size[0]],K.learning_phase(): 0。②self.generate(),读取:model路径、anchor box、coco类别、加载模型yolo.h5.,对于80中coco目标,确定每一种目标框的绘制颜色,即:将(x/80,1.0,1.0)的颜色转换为RGB格式,并随机调整颜色一遍肉眼识别,其中:一个1.0表示饱和度,一个1.0表示亮度。③若GPU>2调用multi_gpu_model()

->①yolo_eval(self.yolo_model.output),max_boxes=20,每张图没类最多检测20个框。②将anchor_box分为3组,分别分配给三个尺度,yolo_model输出的feature map③特征图越小,感受野越大,对大目标越敏感,选大的anchor box->分别对三个feature map运行out_boxes, out_scores, out_classes,返回boxes、scores、classes。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#detect_image作用: #要求进行检测的图片尺寸是32的倍数,原因:在网络中,执行的是5次步长为2的卷积操作,即 #图片的默认尺寸是416*416,因为在最底层中的特征图大小是13*13,所以13*32=416 def detect_image(self, image): start = timer() #定时器 # 调用letterbox_image()函数,即:先生成一个用“绝对灰”R128-G128-B128“填充的416x416新图片, # 然后用按比例缩放(采样方法:BICUBIC)后的输入图片粘贴,粘贴不到的部分保留为灰色 if self.model_image_size != (None, None): #判断图片是否存在 assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required' assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required' # assert断言语句的语法格式 model_image_size[0][1]指图像的w和h,且必须是32的整数倍 boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size))) #letterbox_image对图像调整成输入尺寸(w,h) else: new_image_size = (image.width - (image.width % 32), image.height - (image.height % 32)) boxed_image = letterbox_image(image, new_image_size) image_data = np.array(boxed_image, dtype='float32') print(image_data.shape) #(416,416,3) image_data /= 255. #将缩放后图片的数值除以255,做归一化 image_data = np.expand_dims(image_data, 0) # Add batch dimension. #批量添加一维 -> (1,416,416,3) 为了符合网络的输入格式 -> (bitch, w, h, c) out_boxes, out_scores, out_classes = self.sess.run( [self.boxes, self.scores, self.classes], #目的为了求boxes,scores,classes,具体计算方式定义在generate()函数内。在yolo.py第61行 feed_dict={ #喂参数 self.yolo_model.input: image_data, #图像数据 self.input_image_shape: [image.size[1], image.size[0]], #图像尺寸416x416 K.learning_phase(): 0 #学习模式 0:测试模型。 1:训练模式 }) # 绘制边框,自动设置边框宽度,绘制边框和类别文字,使用Pillow绘图库(PIL,头有声明) print('Found {} boxes for {}'.format(len(out_boxes), 'img')) # 设置字体 font = ImageFont.truetype(font='font/FiraMono-Medium.otf', size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32')) # 设置目标框线条的宽度 thickness = (image.size[0] + image.size[1]) // 300 #厚度 # 对于c个目标类别中的每个目标框i,调用Pillow画图 for i, c in reversed(list(enumerate(out_classes))): predicted_class = self.class_names[c] #类别 #目标类别的名字 box = out_boxes[i] #框 score = out_scores[i] #置信度 label = '{} {:.2f}'.format(predicted_class, score) #标签 draw = ImageDraw.Draw(image) #输出:绘制输入的原始图片 label_size = draw.textsize(label, font) #标签文字 #返回label的宽和高(多少个pixels) top, left, bottom, right = box # 目标框的上、左两个坐标小数点后一位四舍五入 top = max(0, np.floor(top + 0.5).astype('int32')) left = max(0, np.floor(left + 0.5).astype('int32')) # 目标框的下、右两个坐标小数点后一位四舍五入,与图片的尺寸相比,取最小值 bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32')) right = min(image.size[0], np.floor(right + 0.5).astype('int32')) print(label, (left, top), (right, bottom)) #边框 # 确定标签(label)起始点位置:左、下 if top - label_size[1] >= 0: #标签文字 text_origin = np.array([left, top - label_size[1]]) else: text_origin = np.array([left, top + 1]) # My kingdom for a good redistributable image drawing library. # 画目标框,线条宽度为thickness for i in range(thickness): #画框 draw.rectangle( [left + i, top + i, right - i, bottom - i], outline=self.colors[c]) # 画标签框 draw.rectangle( #文字背景 [tuple(text_origin), tuple(text_origin + label_size)], fill=self.colors[c]) # 填写标签内容 draw.text(text_origin, label, fill=(0, 0, 0), font=font) #文案 del draw # 结束计时 end = timer() print(end - start) return image

最后

以上就是迷路花生最近收集整理的关于yolov3 keras版本yolo.py各函数解析的全部内容,更多相关yolov3内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(78)

评论列表共有 0 条评论

立即
投稿
返回
顶部