一、表面钢材检测的目标检测算法研究
课程要求:使用NEU-DET数据集,共计1800张图像,设计要求尽可能提高各种缺陷的检测精度。
数据格式转换
将xml文件转为yolo的txt格式,并确认不同种类缺陷数量,名称。在本项目中,存在缺陷有6种:[‘crazing’, ‘patches’, ‘inclusion’, ‘pitted_surface’, ‘rolled-in_scale’, ‘scratches’]。
下面为xml转yolo的一个例程 (非原创)。
# xml2yolo
# Dataset Classes:['holothurian', 'echinus', 'starfish', 'scallop', 'waterweeds']
import xml.etree.ElementTree as ET
import os, cv2
import numpy as np
from os import listdir
from os.path import join
classes = []
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = (box[0] + box[1]) / 2.0 - 1
y = (box[2] + box[3]) / 2.0 - 1
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def convert_annotation(xmlpath, xmlname):
with open(xmlpath, "r", encoding='utf-8') as in_file:
txtname = xmlname[:-4] + '.txt'
txtfile = os.path.join(txtpath, txtname)
tree = ET.parse(in_file)
root = tree.getroot()
filename = root.find('filename')
img = cv2.imdecode(np.fromfile('{}/{}.{}'.format(imgpath, xmlname[:-4], postfix), np.uint8), cv2.IMREAD_COLOR)
h, w = img.shape[:2]
res = []
for obj in root.iter('object'):
try:
difficult = obj.find('difficult').text
except:
difficult = 0
cls = obj.find('name').text
if cls not in classes:
classes.append(cls)
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
bb = convert((w, h), b)
res.append(str(cls_id) + " " + " ".join([str(a) for a in bb]))
if len(res) != 0:
with open(txtfile, 'w+') as f:
f.write('\n'.join(res))
if __name__ == "__main__":
postfix = 'jpg'
imgpath = 'E:/DATA_MV/NEU-DET/IMAGES'
xmlpath = 'E:/DATA_MV/NEU-DET/ANNOTATIONS'
txtpath = 'E:/DATA_MV/NEU-DET/txt'
if not os.path.exists(txtpath):
os.makedirs(txtpath, exist_ok=True)
list = os.listdir(xmlpath)
error_file_list = []
for i in range(0, len(list)):
try:
path = os.path.join(xmlpath, list[i])
FLAG = '.xml' in path
if ('.xml' in path) or ('.XML' in path):
convert_annotation(path, list[i])
print(f'file {list[i]} convert success.')
else:
print(f'file {list[i]} is not xml format.')
except Exception as e:
print(f'file {list[i]} convert error.')
print(f'error message:\n{e}')
error_file_list.append(list[i])
print(f'this file convert failure\n{error_file_list}')
print(f'Dataset Classes:{classes}')
yolo目标检测精度测试
笔者计划在yoloV3、yoloV5、yoloV7、yoloV8等具有代表性的yolo模型上测试一下数据精度。考虑到实际部署的要求,拟采用yoloV3-tiny、yoloV5s、yoloV7-tiny、yoloV8n四个模型进行测试,并比较结果。在测试中,考虑到数据集的特征,笔者将数据集按照train:val:test=7:1:2的格式进行了随机划分。
此外,尽管yoloV8中已经对过去的yolo版本进行了兼容,但是如果需要修改网络结构,将每个版本源码重新整理仍然是一件有必要的事情。考虑到官网的yoloV8除目标检测外,还有其他笔者不需要的功能,故对yoloV8进行了整理。仅保留了yoloV8中目标检测相关任务,并使yoloV8在python3.7环境下可顺利运行。
yoloV8可以实现几行代码完成训练测试,但是需要将相关库安装至自己对应的虚拟环境中,但一般不修改库文件
改进思路
对网络结构进行改进:所给图像为1X200X200的灰度图像,可以专为这种图像进行网络结构设计。
图像预处理