DeepLearning · 2020年6月25日 0

计算Keras框架下的YOLO v3目标检测算法的mAP

一、储备基础知识

1、初识mAP

根据我们的认知,mAP本质是各类AP的平均值,AP又是什么?

AP:Average Precision,代表的是训练结果的精度

既然mAP是AP(Average Precision)的平均值,那么首先要了解AP的定义和计算方法。要了解AP的定义,首先需要区别什么是精(Precision),什么是准(Accuracy)

Precision指精度,意味着随机误差(Random Error)小,即方差(Variance)小,描述了实际值的扰动情况。

Accuracy指准度,意味着系统误差(System Error)小,即偏差(Bias) 小,描述了的实际值与真实结果的偏离程度,准确度高,意味着误差(Error)小

Error = Bias + Variance

所谓精与准:举个例子

知道了这些概念后,我们先把这些玩意放在这…

2、TP、FN、FP、TN

想必机器学习和深度学习入门的时候,一大部分人都看过吴恩达老师的网课,或者有听过类似的教学。

在学习过程中有一个东西给大家留下的印象应该是比较深刻的:

True Positive(TP):正实际为正实际为正

False Negative(FN): 预测为负实际为正

False Positive(FP): 预测为负实际为正

True Negative(TN): 预测为负实际为负

简单来说:

T或者F代表的是该样本 是否被正确分类。
P或者N代表的是该样本 原本是正样本还是负样本。

所以这些变量与参数的关系也是显然易见的。

举个例子:有60个正样本,40个负样本,系统预测了50个正样本,其中40个是预测正确的正样本;预测了50个负样本,其中30个是预测正确的负样本。TP=40,FP=10;FN=20,TN=30。

那么:

Precision(精确度) = 40/(40+10)=80%

Recall(召回率) = 40/(40+20)=66.7%;

Accuracy(准确度) = (40+30)/(40+10+30+20) = 70%

F1 Score = 240/(240+10+20) = 72.7%

好了我们总结一下:

Precision是预测为正实际为正占预测为正的比例

Recall是预测为正实际为正占总体正样本的比例

Accuracy是预测为主实际为主和预测为负实际为主占总样本的比例。

F1 Score是Precision与Recall的调和平均(harmonic mean),是综合Precision与Recall的评估指标,用于综合反映整体的指标。

但你现在有没有发现一个问题?

3、IOU

我们知道计算AP的原理了,mAP也就是除以类别数,但是计算这些东西的原料:TP、FN、FP、TN又该怎么得到呢?

我们YOLO目标检测出来的输出,本质上是一个框,加上识别出来的类别名称。那么这样的输出怎么给他转化呢?

IOU的定义:IoU (Intersection over union)交并比,预测框(Prediction)与原标记框(Ground truth)之间的重叠度(Overlap),最理想情况是完全重叠,即比值=1

用图说话:

假如我们是要做这样的一个奇怪的目标,蓝色的是我们提前标注好的,橙色的是我们训练的模型做出来的。

IOU说白了就是两个框图重合面积与覆盖总面积的比值。

所以我们要把测试结果做成TP…这些原材料,就是设定一个固定的阈值,让IOU比它大的时候认为是true(1),小的时候认为是False(0),这样下来一个简单的分类器就做好了。

那再想想,我们是怎么算这个IOU呢?

我想,对于这整个训练出来的结果,应该不会太过陌生:

我的意思是说,我们只需要对测试集的图片用已有的训练模型(h5文件)进行识别,就可以得到每个测试集的输出,其输出形式其实有很多种,包括:

带有框的图片、xml文件、txt文件

这里面的核心信息包括:类别、置信度、框的坐标与大小

IOU的计算方式就显然易见了:框的坐标和大小即足够了。

(当然,你也要准备好打好标签的测试集ground truth)


二、开始计算

到这了就非常非常简单了,默认使用的是voc数据集

我们需要准备几个原材料:

  • ground truth:也就是你自己打好标签的voc测试集
  • detection results:训练模型识别出来后输出的txt文件
  • mAP计算源码

1、原材料1

voc测试集:一般来说在自己数据集划分时都有保留一部分作为测试集,这部分需要人工打好标签,关于怎么打标签,未来有时间我会出一个简单的教程。

另外,如果你使用的是coco数据集,如何对其进行转化这就要靠你的咯(未来可能有时间我也再写一下)

如果你手头仅有xml文件,没关系足够了

2、原材料2

yolo_test.py我们需要一个test调用模型识别自己的测试集:

源码如下,自行取用更改:(比较长)

# -*- coding: utf-8 -*-

import colorsys
import os
from timeit import default_timer as timer
import time

import numpy as np
from keras import backend as K
from keras.models import load_model
from keras.layers import Input
from PIL import Image, ImageFont, ImageDraw

from yolo3.model import yolo_eval, yolo_body, tiny_yolo_body
from yolo3.utils import letterbox_image
from keras.utils import multi_gpu_model

path = './test/'  #待检测图片的位置

# 创建创建一个存储检测结果的dir
result_path = './result'
if not os.path.exists(result_path):
    os.makedirs(result_path)

# result如果之前存放的有文件,全部清除
for i in os.listdir(result_path):
    path_file = os.path.join(result_path,i)  
    if os.path.isfile(path_file):
        os.remove(path_file)

#创建一个记录检测结果的文件
txt_path =result_path + '/result.txt'
file = open(txt_path,'w')  

class YOLO(object):
    _defaults = {
        "model_path": 'model_data/yolo.h5',
        "anchors_path": 'model_data/yolo_anchors.txt',
        "classes_path": 'model_data/coco_classes.txt',
        "score" : 0.3,
        "iou" : 0.45,
        "model_image_size" : (416, 416),
        "gpu_num" : 1,
    }

    @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):
        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()
        self.sess = K.get_session()
        self.boxes, self.scores, self.classes = self.generate()

    def _get_class(self):
        classes_path = os.path.expanduser(self.classes_path)
        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):
        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_path = os.path.expanduser(self.model_path)
        assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'

        # Load model, or construct model and load weights.
        num_anchors = len(self.anchors)
        num_classes = len(self.class_names)
        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:
            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.
        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))
        self.colors = list(
            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.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, ))
        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,
                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):
        start = timer() # 开始计时

        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'
            boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))
        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) #打印图片的尺寸
        image_data /= 255.
        image_data = np.expand_dims(image_data, 0)  # Add batch dimension.

        out_boxes, out_scores, out_classes = self.sess.run(
            [self.boxes, self.scores, self.classes],
            feed_dict={
                self.yolo_model.input: image_data,
                self.input_image_shape: [image.size[1], image.size[0]],
                K.learning_phase(): 0
            })

        print('Found {} boxes for {}'.format(len(out_boxes), 'img')) # 提示用于找到几个bbox

        font = ImageFont.truetype(font='font/FiraMono-Medium.otf',
                    size=np.floor(2e-2 * image.size[1] + 0.2).astype('int32'))
        thickness = (image.size[0] + image.size[1]) // 500

        # 保存框检测出的框的个数
        #file.write('find  '+str(len(out_boxes))+' target(s) \n')

        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)

            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'))

            # 写入检测位置            
            #file.write(predicted_class+'  score: '+str(score)+' \nlocation: top: '+str(top)+'、 bottom: '+str(bottom)+'、 left: '+str(left)+'、 right: '+str(right)+'\n')
            
            print(label, (left, top), (right, bottom))

            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.
            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('time consume:%.3f s '%(end - start))
        return image

    def close_session(self):
        self.sess.close()


# 图片检测

if __name__ == '__main__':

    t1 = time.time()
    yolo = YOLO()   
    for filename in os.listdir(path):        
        image_path = path+'/'+filename
        portion = os.path.split(image_path)
        file.write(portion[1]+' detect_result:\n')        
        image = Image.open(image_path)
        r_image = yolo.detect_image(image)
        file.write('\n')
        #r_image.show() 显示检测结果
        image_save_path = './result/result_'+portion[1]        
        print('detect result save to....:'+image_save_path)
        r_image.save(image_save_path)

    time_sum = time.time() - t1
   # file.write('time sum: '+str(time_sum)+'s') 
    print('time sum:',time_sum)
    file.close() 
    yolo.close_session()

我们要求的输出格式是:

eye 86 274 146 305
eye 214 273 282 303
nose 138 334 220 385
mouth 139 404 220 437

classname left top right bottom

3、原材料3

源码链接:https://github.com/Cartucho/mAP

文件我也po了


最后我们就可以快乐输出了

由于我的项目和比赛结果时间的一些原因,现阶段我无法对其进行公开和分析评价

过一段时间国赛告一段落,我就po出来并好好分析

(一定要提醒我!提醒我!)