本文主要是介绍使用自制COCO数据集进行PaddleDetection模型训练,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本次模型训练基于百度飞浆的Baseline:
19届智能车百度创意组识别 - 飞桨AI Studio星河社区 (baidu.com)
一、收集数据及数据处理
- 用摄像头拍摄实物,这里先选用baseline中给好的数据集。
- 创建VOC文件夹,文件夹里包含Annotations和JPEGImages两个文件夹。需要进行标注操作的图片将会放在JPEGImages文件夹里,标注生成的xml文件将会放在Annotations文件夹里。
- 图片重命名。统一命名格式,便于进行增广操作。
命名格式示例:000001.jpg
、00XXXX.jpg
。 - 上述重命名步骤会用到的python文件:
import os# 指定图片所在的文件夹名称
folder_name = 'image_set'
# 获取当前工作目录
current_directory = os.getcwd()
# 构建文件夹的完整路径
folder_path = os.path.join(current_directory, folder_name)# 检查文件夹是否存在
if not os.path.exists(folder_path):print(f"警告:未找到名为 '{folder_name}' 的文件夹。")
else:# 确保文件夹路径以斜杠结束if not folder_path.endswith('/'):folder_path += '/'# 获取文件夹内所有的文件名列表file_list = os.listdir(folder_path)# 初始化计数器counter = 1# 遍历文件列表并重命名图片for filename in sorted(file_list, key=lambda x: x.lower()): # 按字母顺序排序if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):# 构建新的文件名,确保编号始终为5位数字new_filename = f'{counter:06d}{os.path.splitext(filename)[1]}'# 构建完整的原始文件路径和新文件路径old_file_path = os.path.join(folder_path, filename)new_file_path = os.path.join(folder_path, new_filename)# 重命名文件os.rename(old_file_path, new_file_path)# 更新计数器counter += 1print("图片重命名完成。")
使用方法:将该python文件与“JPEGImages”文件夹放在同一目录下(即VOC文件夹),打开Windows终端,输入python指令运行即可。python img_rename.py
。使用方法也可根据自己的需求灵活变化。
二、用labelimg进行数据集图片标注
lbelimg和labelme的使用方法很相似,安装的步骤也很相似。但是labelimg可以选择的标注类型比较多,有voc的xml,也有yolo。而labelme的好像只有json格式的,所以本次目标检测数据集标注选择labelimg。
相关教程:
labelme的开源GitHub库:labelme_github
labelimg的GitHub开源地址:labeimg_github
CSDN的安装教程:labelme的安装及使用_labelme安装-CSDN博客
labelimg安装教程:图像标注工具labelImg安装教程及使用方法_labelimg的安装和使用
labelimg的简单安装:pip install labelimg -i https://pypi.tuna.tsinghua.edu.cn/simple
- 打开labelimg标注工具。打开“Anaconda Prompt”终端,输入
activate labelme
(这里填写你自己配的装有labelimg的conda环境);输入labelimg
,运行工具。 - 标注结果如下图所示:
三、数据集增广
数据集增广需要用到“ImgAug”软件。
GitHub链接:Fafa-DL/Image-Augmentation: Image augmentation for object detection, segmentation and classification (github.com)
- 增广选项:
- Noise噪声、G-Blur高斯模糊、Bright亮度,这三个是常用的,根据具体场景不同可以加入HSV色域、V-Flip垂直翻转。(V-Flip在翻转图片的同时,也会对xml文件进行处理,使得标注结果仍然准确。这个软件做的还是很细的。)
- 时刻注意已有图片编号,每次标注前都要调整“起始输出编号”。
- 增广结果如下:
- 增广之后生成的xml文件可能有小错误:filename与path的文件名部分不匹配,这里是匹配的,如果遇到不匹配的情况,如要使用下面提到的工具来处理。
- 使用方法:将该python文件与Annotations文件夹放在同一目录下,打开终端运行该python文件即可。
import os
import xml.etree.ElementTree as ETdef process_xml(xml_file):# 解析XML文件tree = ET.parse(xml_file)root = tree.getroot()# 获取<filename>和<path>元素filename_elem = root.find('filename')path_elem = root.find('path')if filename_elem is not None and path_elem is not None:# 获取filename和path的文本内容filename = filename_elem.textpath = path_elem.text# 从path中提取文件名path_filename = os.path.basename(path)# 比较filename和path中的文件名if filename != path_filename:# 将path中的文件名替换为filenamenew_path = os.path.join(os.path.dirname(path), filename)path_elem.text = new_path# 将修改后的内容写回XML文件tree.write(xml_file)def process_xml_files(xml_dir):# 遍历指定文件夹下的所有文件for filename in os.listdir(xml_dir):# 只处理XML文件if filename.endswith('.xml'):xml_file = os.path.join(xml_dir, filename)# 对每个XML文件进行处理process_xml(xml_file)# 指定包含XML文件的文件夹路径
xml_dir = 'Annotations'# 处理文件夹中的所有XML文件
process_xml_files(xml_dir)
四、将VOC类型的数据集转换成COCO类型
- VOC与COCO的讲解:VOC和COCO数据集讲解_voc数据集和coco数据集区别-CSDN博客
- 在步骤“一.2"中,我们已经创建了VOC文件夹,将以下python代码放在与VOC文件夹的同一目录下,打开终端运行即可。
import os
import random
import shutil
import json
import glob
import xml.etree.ElementTree as ETdef get(root, name):vars = root.findall(name)return varsdef get_and_check(root, name, length):vars = root.findall(name)if len(vars) == 0:raise ValueError("Can not find %s in %s." % (name, root.tag))if length > 0 and len(vars) != length:raise ValueError("The size of %s is supposed to be %d, but is %d."% (name, length, len(vars)))if length == 1:vars = vars[0]return varsdef get_filename_as_int(filename):try:filename = filename.replace("\\", "/")filename = os.path.splitext(os.path.basename(filename))[0]return int(filename)except:raise ValueError("Filename %s is supposed to be an integer." % (filename))# 获取数据集中类别的名字
def get_categories(xml_files):classes_names = []for xml_file in xml_files:tree = ET.parse(xml_file)root = tree.getroot()for member in root.findall("object"):classes_names.append(member[0].text)classes_names = list(set(classes_names))classes_names.sort()print(f"类别名字为{classes_names}")return {name: i for i, name in enumerate(classes_names)}def convert(xml_files, json_file):json_dict = {"images": [], "type": "instances", "annotations": [], "categories": []}if PRE_DEFINE_CATEGORIES is not None:categories = PRE_DEFINE_CATEGORIESelse:categories = get_categories(xml_files)bnd_id = START_BOUNDING_BOX_IDfor xml_file in xml_files:tree = ET.parse(xml_file)root = tree.getroot()path = get(root, "path")if len(path) == 1:filename = os.path.basename(path[0].text)elif len(path) == 0:filename = get_and_check(root, "filename", 1).textelse:raise ValueError("%d paths found in %s" % (len(path), xml_file))## The filename must be a numberimage_id = get_filename_as_int(filename)size = get_and_check(root, "size", 1)width = int(get_and_check(size, "width", 1).text)height = int(get_and_check(size, "height", 1).text)image = {"file_name": filename,"height": height,"width": width,"id": image_id,}json_dict["images"].append(image)## Currently we do not support segmentation.# segmented = get_and_check(root, 'segmented', 1).text# assert segmented == '0'for obj in get(root, "object"):category = get_and_check(obj, "name", 1).textif category not in categories:new_id = len(categories)categories[category] = new_idcategory_id = categories[category]bndbox = get_and_check(obj, "bndbox", 1)xmin = int(get_and_check(bndbox, "xmin", 1).text) - 1ymin = int(get_and_check(bndbox, "ymin", 1).text) - 1xmax = int(get_and_check(bndbox, "xmax", 1).text)ymax = int(get_and_check(bndbox, "ymax", 1).text)assert xmax > xminassert ymax > ymino_width = abs(xmax - xmin)o_height = abs(ymax - ymin)ann = {"area": o_width * o_height,"iscrowd": 0,"bbox": [xmin, ymin, o_width, o_height],"category_id": category_id,"ignore": 0,"image_id": image_id,"id": bnd_id,# "segmentation": [], # segmentation暂时用不上,paddle里也没有用这个}json_dict["annotations"].append(ann)bnd_id = bnd_id + 1for cate, cid in categories.items():cat = {"supercategory": "none", "id": cid, "name": cate}json_dict["categories"].append(cat)os.makedirs(os.path.dirname(json_file), exist_ok=True)json_fp = open(json_file, "w")json_str = json.dumps(json_dict)json_fp.write(json_str)json_fp.close()# 新建文件夹
def mkdir(path):path = path.strip()path = path.rstrip("\\")isExists = os.path.exists(path)if not isExists:os.makedirs(path)print(path + ' ----- folder created')return Trueelse:print(path + ' ----- folder existed')return Falseif __name__ == '__main__':# 验证集比例valRatio = 0.2# 测试集比例testRatio = 0.1# 获取当前脚本路径main_path = os.getcwd()# voc格式的图片和xml存放路径voc_images = os.path.join(main_path, 'VOC', 'JPEGImages')voc_annotations = os.path.join(main_path, 'VOC', 'Annotations')# 获取xml数量xmlNum = len(os.listdir(voc_annotations))val_files_num = int(xmlNum * valRatio)test_files_num = int(xmlNum * testRatio)coco_path = os.path.join(main_path, 'COCO')# coco_images = os.path.join(main_path, 'COCO', 'images')coco_json_annotations = os.path.join(main_path, 'COCO', 'annotations')coco_train2017 = os.path.join(main_path, 'COCO', 'train')coco_val2017 = os.path.join(main_path, 'COCO', 'valid')coco_test2017 = os.path.join(main_path, 'COCO', 'test')xml_val = os.path.join(main_path, 'xml', 'xml_val')xml_test = os.path.join(main_path, 'xml', 'xml_test')xml_train = os.path.join(main_path, 'xml', 'xml_train')mkdir(coco_path)# mkdir(coco_images)mkdir(coco_json_annotations)mkdir(xml_val)mkdir(xml_test)mkdir(xml_train)mkdir(coco_train2017)mkdir(coco_val2017)if testRatio:mkdir(coco_test2017)for i in os.listdir(voc_images):img_path = os.path.join(voc_images, i)shutil.copy(img_path, coco_train2017)# voc images copy to coco imagesfor i in os.listdir(voc_annotations):img_path = os.path.join(voc_annotations, i)shutil.copy(img_path, xml_train)print("\n\n %s files copied to %s" % (val_files_num, xml_val))for i in range(val_files_num):if len(os.listdir(xml_train)) > 0:random_file = random.choice(os.listdir(xml_train))# print("%d) %s"%(i+1,random_file))source_file = "%s/%s" % (xml_train, random_file)# 分离文件名font, ext = random_file.split('.')valJpgPathList = [j for j in os.listdir(coco_train2017) if j.startswith(font)]if random_file not in os.listdir(xml_val):shutil.move(source_file, xml_val)shutil.move(os.path.join(coco_train2017, valJpgPathList[0]), coco_val2017)else:random_file = random.choice(os.listdir(xml_train))source_file = "%s/%s" % (xml_train, random_file)shutil.move(source_file, xml_val)# 分离文件名font, ext = random_file.split('.')valJpgPathList = [j for j in os.listdir(coco_train2017) if j.startswith(font)]shutil.move(os.path.join(coco_train2017, valJpgPathList[0]), coco_val2017)else:print('The folders are empty, please make sure there are enough %d file to move' % (val_files_num))breakfor i in range(test_files_num):if len(os.listdir(xml_train)) > 0:random_file = random.choice(os.listdir(xml_train))# print("%d) %s"%(i+1,random_file))source_file = "%s/%s" % (xml_train, random_file)# 分离文件名font, ext = random_file.split('.')testJpgPathList = [j for j in os.listdir(coco_train2017) if j.startswith(font)]if random_file not in os.listdir(xml_test):shutil.move(source_file, xml_test)shutil.move(os.path.join(coco_train2017, testJpgPathList[0]), coco_test2017)else:random_file = random.choice(os.listdir(xml_train))source_file = "%s/%s" % (xml_train, random_file)shutil.move(source_file, xml_test)# 分离文件名font, ext = random_file.split('.')testJpgPathList = [j for j in os.listdir(coco_train2017) if j.startswith(font)]shutil.move(os.path.join(coco_train2017, testJpgPathList[0]), coco_test2017)else:print('The folders are empty, please make sure there are enough %d file to move' % (val_files_num))breakprint("\n\n" + "*" * 27 + "[ Done ! Go check your file ]" + "*" * 28)START_BOUNDING_BOX_ID = 1PRE_DEFINE_CATEGORIES = Nonexml_val_files = glob.glob(os.path.join(xml_val, "*.xml"))xml_test_files = glob.glob(os.path.join(xml_test, "*.xml"))xml_train_files = glob.glob(os.path.join(xml_train, "*.xml"))convert(xml_val_files, os.path.join(coco_json_annotations, 'valid.json'))convert(xml_train_files, os.path.join(coco_json_annotations, 'train.json'))if testRatio:convert(xml_test_files, os.path.join(coco_json_annotations, 'test.json'))# 删除文件夹try:shutil.rmtree(xml_train)shutil.rmtree(xml_val)shutil.rmtree(xml_test)shutil.rmtree(os.path.join(main_path, 'xml'))except:print(f'xml文件删除失败,请手动删除{xml_train, xml_val, xml_test}')
- VOC2COCO的结果:
- 文件夹train、valid、test里存放的是图片文件,本次目标检测模型训练中暂时用不到这三个文件。
五、PaddleDetection模型训练
- 将上述生成的三个json文件下载到AIStudio平台中。
- images文件夹下放的是本次模型训练需要用到的所有图片(也就是train、valid、test里存放的图片文件的总和)。
- **修改yml文件参数:num_classes
- 参考baseline的指引开始模型的训练、导出、推理。
- 推理结果如下:
这篇关于使用自制COCO数据集进行PaddleDetection模型训练的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!