keras-yolov3在Caltech上计算mAP的过程

keras-yolov3在Caltech上计算mAP的过程

聿默 2020-05-06 19:01:08 112 收藏
文章标签: keras-yolov3Caltech测试mAP
版权
首先说明,本篇只为记录使用前人成果应用到在Caltech数据集上做的数据集实验上,代码参考部分主要是下面的几个,都很好用,参考中最后两篇给了我写这部分总结的灵感,感谢。

代码参考:

https://github.com/qqwweee/keras-yolo3

https://github.com/plsong/keras-yolo3-test

https://github.com/Cartucho/mAP

 

目录

0.环境

1.Caltech数据集与训练

2.使用keras-yolo3-test输出测试结果txt文件

2.0classes_path改为voc_classes

2.1直接读test目录图像,改为通过test.txt读取图像

2.2将检测结果按照一定格式保存到以图像名命名的txt文件中

3.利用mAP-master中convert_gt_xml.py将gt_xml解析为txt

4.测试mAP

4.1取gt与dr文件数相同、文件名一一对应

4.2测试mAP

参考

 

0.环境
windows
keras
python3.6.8
glob
shutil
keras==2.1.5
h5py
1.Caltech数据集与训练
数据集转为voc(转好的数据大概有12万多),流程与代码可以参考:

https://blog.csdn.net/a1103688841/article/details/84135248

https://github.com/shadowwalker00/CaltechPestrain2VOC

 

训练参考这个:

https://github.com/qqwweee/keras-yolo3/blob/master/README.md

生成了h5模型。

2.使用keras-yolo3-test输出测试结果txt文件
修改三个地方:

2.0classes_path改为voc_classes
"classes_path": 'model_data/voc_classes.txt',
2.1直接读test目录图像,改为通过test.txt读取图像
path = "test图像路径"
for filename in os.listdir(path):
image_path = path + filename
改为:

path = "test.txt路径"
img_path = "图像路径"
with open(path + 'Main/test.txt') as f:
lines = f.readlines()
for filename in lines:
filename = filename.split("\n")[0]
image_path = img_path + filename + '.jpg'
2.2将检测结果按照一定格式保存到以图像名命名的txt文件中
按照以下格式保存到txt文件中:

predicted_class score left top right bottom
此处做了三处修改: 

1.
def detect_image(self, image, txtfilename):

2.
# 检测结果写入
txt_file = open(txtfilename, 'a')
txt_file.write(predicted_class + ' '+ str(score) +' '+ str(left) +' '+ str(top) + ' '+ str(right) + ' '+ str(bottom)+'\n')
txt_file.close()

3.
result_save_path = result_path + '/' + filename + '.txt'
portion = os.path.split(image_path)
file.write(portion[1]+' detect_result:\n')
image = Image.open(image_path)
r_image = yolo.detect_image(image, result_save_path)
file.write('\n')
#r_image.show() 显示检测结果
# result_save_path = './result/' + filename + '.txt'
print('detect result save to....:'+ result_save_path)
以上均修改后的代码:

# -*- coding: utf-8 -*-
"""
功能:keras-yolov3 进行批量测试 并 保存结果
项目来源:https://github.com/qqwweee/keras-yolo3
"""

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.txt文件地址' #test.txt文件地址
img_path = '图片的位置' #图片的位置
# path = './test/' #待检测图片的位置

# 创建创建一个存储检测结果的dir
result_path = './input/detection-results'
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/voc_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, txtfilename):
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))

# 检测结果写入
txt_file = open(txtfilename, 'a')
txt_file.write(predicted_class + ' '+ str(score) +' '+ str(left) +' '+ str(top) + ' '+ str(right) + ' '+ str(bottom)+'\n')
txt_file.close()

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()
with open(path + 'Main/test.txt') as f:
lines = f.readlines()
for filename in lines:
# for filename in os.listdir(path):
filename = filename.split("\n")[0]
image_path = img_path + filename + '.jpg'
result_save_path = result_path + '/' + filename + '.txt'
portion = os.path.split(image_path)
file.write(portion[1]+' detect_result:\n')
image = Image.open(image_path)
r_image = yolo.detect_image(image, result_save_path)
file.write('\n')
#r_image.show() 显示检测结果
# result_save_path = './result/' + filename + '.txt'
print('detect result save to....:'+ result_save_path)
# r_image.save(result_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()
3.利用mAP-master中convert_gt_xml.py将gt_xml解析为txt
voc数据格式的test.txt中读取xml文件名称,然后将xml文件解析为txt

import sys
import os
import glob
import xml.etree.ElementTree as ET


result_path = './input/ground-truth'
if not os.path.exists(result_path):
os.makedirs(result_path)

# make sure that the cwd() in the beginning is the location of the python script (so that every path makes sense)
os.chdir(os.path.dirname(os.path.abspath(__file__)))

# change directory to the one with the files to be changed
parent_path = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
parent_path = os.path.abspath(os.path.join(parent_path, os.pardir))
GT_PATH = os.path.join(parent_path, 'input','ground-truth')
#print(GT_PATH)
os.chdir(GT_PATH)
path = 'test.txt文件地址' #test.txt文件地址
xml_path = '图片的位置' #图片的位置

with open(path + 'Main/test.txt') as f:
lines = f.readlines()

# create VOC format files
if len(lines) == 0:
print("Error: no .xml files found in ground-truth")
sys.exit()
else:
for tmp_file in lines:
# print(tmp_file)
# 1. create new file (VOC format)
tmp_file = tmp_file.split("\n")[0] + '.xml'
print(tmp_file)
txt_file = result_path + '/' + tmp_file
tmp_file = xml_path + tmp_file
with open(txt_file.replace(".xml", ".txt"), "a") as new_f:
root = ET.parse(tmp_file).getroot()
for obj in root.findall('object'):
obj_name = obj.find('name').text
bndbox = obj.find('bndbox')
left = bndbox.find('xmin').text
top = bndbox.find('ymin').text
right = bndbox.find('xmax').text
bottom = bndbox.find('ymax').text
new_f.write("%s %s %s %s %s\n" % (obj_name, left, top, right, bottom))
# 2. move old file (xml format) to backup
# os.rename(tmp_file, os.path.join("backup", tmp_file))
print("Conversion completed!")
4.测试mAP
如果gt与dr中文件数量不一样,就先完成4.1;一样的话直接进行4.2测试mAP步骤。

4.1取gt与dr文件数相同、文件名一一对应
这一步,使用的\mAP-master\scripts\extra\intersect-gt-and-dr.py,运行后,会分别将\input\detection-results与ground-truth中对方没有的文件放到对应目录的backup_no_matches_found文件夹下。

由于我已经将scripts放到了keras-yolov3-master目录下,所以在该目录下直接运行下面命令:

python ./scripts/extra/intersect-gt-and-dr.py


4.2测试mAP
将\mAP-master\main.py复制到keras-yolov3-master目录下,并修改名称为yolo_test_mAP.py,并运行:

python yolo_test_mAP.py
发现mAP-master写得非常友好,几乎不需要做什么其他的修改,出现了什么问题,也会提示该用什么代码解决。

截取了其中一部分动画显示:

 

 

参考
1.keras-yolo3

2.keras-yolo3-test

3.mAP

4.Caltech行人数据集转化VOC数据集

5.CaltechPestrain2VOC

6.keras-yolo3/blob/master/README.md

7.【yoloV3-keras】 keras-yolov3 进行批量测试 并 保存结果

8.【YOLOV3-keras-MAP】YOLOV3-keras版本的mAP计算
————————————————
版权声明:本文为CSDN博主「聿默」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_35975447/java/article/details/105953974

posted on 2020-07-07 12:32  曹明  阅读(497)  评论(0)    收藏  举报