yolo v3系列之训练自己的数据集(下篇)

本文主要讨论如何对于检测结果进行测评

参考repo:https://github.com/Cartucho/mAP

测评代码已经上传到我的github,欢迎star

测评说明:

一.生成txt文件

通过读https://github.com/Cartucho/mAP的源代码,我们发现我们仅仅需要生成两种txt即可,一种是预测的txt放到predicted文件夹下,另外一种就是ground truth的txt放到ground-truth文件夹下。

1)生成ground truth的txt文件,write_gt_txt.py,主要思路:原来的wider数据集的gt文件太难解析了,我们通过运行wider_annotation.py生成了wider_val.txt文件,对于该文件进行解析,容易许多

# -*- coding:utf-8 -*- 
__author__ = 'xuy'

'''
主要参考wider_annotation.py文件,验证集val-dataset将xmin,ymin,xmax,ymax的文件输出到mAP的gt文件夹下
生成的这个文件可以用来给draw_gt.py提供数据
具体内容格式参考mAP文件夹下的my_ground-truth文件
我们可以根据由wider_annotation.py生成的WIDER_train_val.txt[一共3226张图片]文件来进行更改
'''
import os

input_file='/home/xuy/code/keras-yolo3-detection/wider_dataset/WIDER_val.txt'
output_path='/home/xuy/code/mAP/ground-truth/'


def read_file(data_file, mode='more'):
    """
    读文件, 原文件和数据文件
    :return: 单行或数组
    """
    try:
        with open(data_file, 'r') as f:
            if mode == 'one':#只有一个候选框
                output = f.read()
                return output
            elif mode == 'more':#有多个候选框,因此需要readlines
                output = f.readlines()
                # return map(str.strip, output)
                return output
            else:
                return list()
    except IOError:
        return list()

data_lines=read_file(input_file)
for data_line in data_lines:
    data_line=data_line.split()#data_line是每一组的信息,data_line[0]是路径,data_line[1...-1]是5位数组结果
    pic_filename=os.path.basename(data_line[0])
    # print(data_line[-1])
    portion = os.path.splitext(pic_filename)
    if portion[1] == '.jpg':
        txt_result = output_path + portion[0] + '.txt'
    # print('txt_result的路径是:' + txt_result)#每个文件的txt输出路径
    #需要遍历data_line【1~  -1】
    # for data in range(1,len(data_line)):
    #     print(data[])
    for i in range(1,len(data_line)):
        xmin,ymin,xmax,ymax,class_label=data_line[i].split(',')
        print(xmin,ymin,xmax,ymax)
        with open(txt_result, 'a')as new_f:
            new_f.write('face'+' '+xmin+' '+ymin+' '+xmax+' '+ymax+'\n')




2)生成预测坐标位置的txt文件,在yolo3_predict_pic.py文件中

#!/usr/bin/env python
# -- coding: utf-8 --
"""
Copyright (c) 2018. All rights reserved.
Created by C. L. Wang on 2018/7/4
"""

"""
Run a YOLO_v3 style detection model on test images.
"""

import colorsys
import os
from timeit import default_timer as timer

import numpy as np
from PIL import Image, ImageFont, ImageDraw
from keras import backend as K
from keras.layers import Input
from yolo3.model import yolo_eval, yolo_body
from yolo3.utils import letterbox_image

#用来存储预测结果的txt文件
predict_result = '/home/xuy/code/mAP/predicted/'
#wider数据集的val-set的图片
img_root_path = '/home/xuy/code/keras-yolo3-detection/wider_dataset/WIDER_val/images'
#img_path是单个图片的测试
# img_path = '/home/xuy/code/keras-yolo3-detection/wider_dataset/WIDER_train/images/0--Parade/0_Parade_marchingband_1_5.jpg'  # 先拿单张图片测试一下
#将预测结果的图片输出的路径
result_path = '/home/xuy/code/keras-yolo3-detection/result/'
def iterbrowse(path):
    for home, dirs, files in os.walk(path):
        for filename in files:
            yield os.path.join(home, filename)
class YOLO(object):
    def __init__(self):
        self.anchors_path = 'configs/yolo_anchors.txt'  # Anchors
        # self.model_path = 'model_data/yolo_weights.h5'  # 模型文件
        self.model_path = '/home/xuy/code/keras-yolo3-detection/logs/trained_weights_final_train.h5'  # 模型文件
        # self.classes_path = 'configs/coco_classes.txt'  # 类别文件
        self.classes_path = '/home/xuy/code/keras-yolo3-detection/configs/wider_classes.txt'  # 类别文件

        self.score = 0.1
        # self.iou = 0.45
        self.iou = 0.20
        self.class_names = self._get_class()  # 获取类别
        self.anchors = self._get_anchors()  # 获取anchor
        self.sess = K.get_session()
        self.model_image_size = (416, 416)  # fixed size or (None, None), hw
        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.'

        num_anchors = len(self.anchors)  # anchors的数量
        num_classes = len(self.class_names)  # 类别数

        # 加载模型参数
        self.yolo_model = yolo_body(Input(shape=(None, None, 3)), 3, num_classes)
        self.yolo_model.load_weights(model_path)

        print('{} model, {} anchors, and {} classes loaded.'.format(model_path, num_anchors, num_classes))

        # 不同的框,不同的颜色
        hsv_tuples = [(float(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))  # RGB
        np.random.seed(10101)
        np.random.shuffle(self.colors)
        np.random.seed(None)

        # 根据检测参数,过滤框
        self.input_image_shape = K.placeholder(shape=(2,))
        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,img_path):#检测每一张图片的人脸位置
        start = timer()  # 起始时间
        pic_filename=os.path.basename(img_path)
        # txt_filename=pic_filename.replace("jpg","txt")
        portion=os.path.splitext(pic_filename)
        if portion[1]=='.jpg':
            txt_result=predict_result+portion[0]+'.txt'
        print('txt_result的路径是:'+txt_result)
        if self.model_image_size != (None, None):  # 416x416, 416=32*13,必须为32的倍数,最小尺度是除以32
            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('detector size {}'.format(image_data.shape))
        image_data /= 255.  # 转换0~1
        image_data = np.expand_dims(image_data, 0)  # 添加批次维度,将图片增加1维

        # 参数盒子、得分、类别;输入图像0~1,4维;原始图像的尺寸
        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'))  # 检测出的框

        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]) // 512  # 厚度
        with open(txt_result,'a')as new_f:
            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'))
                print(label, (left, top), (right, bottom))  # 边框,这个就是【置信值,xmin,ymin,xmax,ymax】,可以做一下mAP值的分析了
                new_f.write(str(label)+" "+ str(left) + " " + str(top) + " " + str(right) + " " + str(bottom) + '\n')
                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)  # 文字内容,face+是人脸的概率值
                del draw

        end = timer()
        print(end - start)  # 检测执行时间
        return image

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


def detect_img_for_test(yolo):

    for img_path in iterbrowse(img_root_path):
        print('img_path的路径是:'+img_path)
        image = Image.open(img_path)
        filename=os.path.basename(img_path)
        print('filename'+filename)
        r_image = yolo.detect_image(image,img_path)
        # r_image.show()  # 先显示,然后再保存
        r_image.save(result_path+filename)







    # for parent,dirnames,filenames in os.walk(img_root_path):    #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
    #     for dirname in dirnames:
    #         for filename in filenames:
    #             img_path=img_root_path+'/'+dirname+'/'+filename
    #             print(img_path)
            #     image = Image.open(img_path)
            #     r_image = yolo.detect_image(image)
            #     # r_image.show()  # 先显示,然后再保存
            #     r_image.save(result_path+filename)


    # image = Image.open(img_path)
    # r_image = yolo.detect_image(image)
    # # r_image.show()#先显示,然后再保存
    # r_image.save('/home/xuy/code/keras-yolo3-detection/' + 'result2.jpg')


    yolo.close_session()


if __name__ == '__main__':
    detect_img_for_test(YOLO())

二.使用main.py文件对于这两个文件夹进行测评

直接运行mAP这个repo当中的main.py即可

python main.py -na

na表示禁止图片以动画形式播放。

三.最终结果:

mAP大概是34.6%左右

 

猜你喜欢

转载自blog.csdn.net/mdjxy63/article/details/81294941
今日推荐