侧边栏壁纸
博主头像
dsmggm 博主等级

行动起来,活在当下

  • 累计撰写 36 篇文章
  • 累计创建 1 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

YOLO目标检测模型训练

dsmggm
2025-08-07 / 0 评论 / 0 点赞 / 0 阅读 / 0 字

本教程使用开源项目为AntiCAP_trainer进行训练,使用labelImg进行标注

目标标注

初始化labelimg项目环境后,安装依赖

pip install pyqt5 lxml

初始化pyrcc

pyrcc5 -o libs/resources.py resources.qrc

运行 labelImg.py 成功启动labelimg如下图
设置自动保存,方法:“查看”-“自动保存模式”

image-ndq0.png

注:如果遇到闪退,可以尝试重置软件,方法:“文件”-“全部重置”

image-thwb.png
更改存储方式为json文件

image-gpwb.png

格式对应:
CreateML => json
YOLO => txt
PascalVOC => xml

image-gofj.png

处理json格式

生成的json格式无法直接使用,需要进行处理后才能正常训练
使用python批量处理

import os
import json

def convert_json_format(input_file, output_file):
    """将自定义格式的JSON转换为LabelMe格式"""
    with open(input_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    # 检查数据格式
    if isinstance(data, list) and len(data) > 0:
        original_data = data[0]
    else:
        original_data = data
    
    # 构建新的LabelMe格式数据
    new_data = {
        "imagePath": original_data.get("image", ""),
        "verified": original_data.get("verified", False),
        "shapes": []
    }
    
    # 转换annotations为shapes
    for annotation in original_data.get("annotations", []):
        label = annotation.get("label", "")
        coordinates = annotation.get("coordinates", {})
        
        if coordinates:
            x = coordinates.get("x", 0)
            y = coordinates.get("y", 0)
            width = coordinates.get("width", 0)
            height = coordinates.get("height", 0)
            
            # 计算边界框的两个对角点
            x_min = x - width / 2
            y_min = y - height / 2
            x_max = x + width / 2
            y_max = y + height / 2
            
            shape = {
                "label": label,
                "points": [
                    [x_min, y_min],
                    [x_max, y_max]
                ]
            }
            new_data["shapes"].append(shape)
    
    # 保存转换后的数据
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(new_data, f, ensure_ascii=False, indent=2)

# 批量转换目录中的所有JSON文件
def batch_convert(input_dir, output_dir):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    for filename in os.listdir(input_dir):
        if filename.endswith('.json'):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)
            convert_json_format(input_path, output_path)
            print(f"已转换: {filename}")

# 使用示例
if __name__ == "__main__":
    input_directory = r"./"  # 输入目录,包含自定义格式的JSON文件
    output_directory = r"./out"  # 输出目录,保存转换后的LabelMe格式JSON文件
    
    batch_convert(input_directory, output_directory)
    print("所有文件转换完成!")

模型训练

初始化AntiCAP_trainer项目

pip install pyyaml pillow ultralytics

创建文件夹,否则报错

创建文件夹Classification_Detection_Train\Train_Sets\train里面要创建imageslabels
创建文件夹Classification_Detection_Train\Train_Sets\val里面要创建imageslabels

image-n59u.png

运行Classification_Detection_Train\Classification_Detection_Train.py进行训练

将图片文件与json文件放在Classification_Detection_Train\Train_Sets\LABELME_DATA文件夹中,程序会自动分配训练集跟验证集
配置可根据Classification_Detection_Train.py内容更改
运行训练

image-aeha.png

训练结束后模型文件位于Classification_Detection_Train\Out_Model
使用Classification_Detection_Train\pred.py进行测试

0

评论区