yolov7 训练自己数据

1、 打标签

 

 导出为voc格式

2、voc to yolo

import os
import shutil
import cv2
from lxml import etree

def VOC2Yolo(class_num, voc_img_path, voc_xml_path, yolo_txt_save_path, yolo_img_save_path=None):
    xmls = os.listdir(voc_xml_path)
    xmls = [x for x in xmls if x.endswith('.xml')]
    if yolo_img_save_path is not None:
        if not os.path.exists(yolo_img_save_path):
            os.mkdir(yolo_img_save_path)
    if not os.path.exists(yolo_txt_save_path):
        os.mkdir(yolo_txt_save_path)
    all_xmls = len(xmls)
    for idx, one_xml in enumerate(xmls):
        xl = etree.parse(os.path.join(voc_xml_path, one_xml))
        root = xl.getroot()
        objects = root.findall('object')
        img_size = root.find('size')
        img_w = 0
        img_h = 0
        if img_size:
            img_width = img_size.find('width')
            if img_width is not None:
                img_w = int(img_width.text)
            img_height = img_size.find('height')
            if img_height is not None:
                img_h = int(img_height.text)
        label_lines = []
        for ob in objects:
            one_annotation = {}
            label = ob.find('name').text
            one_annotation['tag'] = label
            one_annotation['flag'] = False
            bbox = ob.find('bndbox')
            xmin = int(bbox.find('xmin').text)
            ymin = int(bbox.find('ymin').text)
            xmax = int(bbox.find('xmax').text)
            ymax = int(bbox.find('ymax').text)
            if img_w == 0 or img_h == 0:
                img = cv2.imread(os.path.join(voc_img_path, one_xml.replace('.xml', '.jpg')))
                img_h, img_w = img.shape[:2]
            bbox_w = (xmax - xmin) / img_w
            bbox_h = (ymax - ymin) / img_h
            bbox_cx = (xmin + xmax) / 2 / img_w
            bbox_cy = (ymin + ymax) / 2 / img_h
            try:
                bbox_label = class_num[label]
                label_lines.append(f'{bbox_label} {bbox_cx} {bbox_cy} {bbox_w} {bbox_h}' + '\n')
            except Exception as e:
                print("not find number label in class_num ", e, one_xml)
                label_lines = []
                break
        if len(label_lines):
            with open(os.path.join(yolo_txt_save_path, one_xml.replace('.xml', '.txt')), 'w') as fp:
                fp.writelines(label_lines)
            if yolo_img_save_path is not None:
                shutil.copy(os.path.join(voc_img_path, one_xml.replace('.xml', '.jpg')),
                            os.path.join(yolo_img_save_path))
        print(f"processing: {idx}/{all_xmls}")


if __name__ == '__main__':
    VOC2Yolo(
        class_num={'头碎': 0},  # 标签种类
        voc_img_path=r"C:\Users\wj\Desktop\headbroken_crop", # 数据集图片文件夹存储路径
        voc_xml_path=r"C:\Users\wj\Desktop\headbroken_voc_crop\outputs", # 标签xml文件夹存储路径
        yolo_txt_save_path=r"C:\Users\wj\Desktop\yolo" # 将要生成的txt文件夹存储路径
    )

 3、 txt

 

import glob

#存放图片的地址
train_image_path = r"/media/wlj/soft_D/WLJ/WJJ/yolov7-main/crop/images/train/"
valid_image_path = r"/media/wlj/soft_D/WLJ/WJJ/yolov7-main/crop/images/valid/"
#生成的txt的路径
txt_path = r"/media/wlj/soft_D/WLJ/WJJ/yolov7-main/crop/"

def generate_train_and_val(image_path, txt_file):
    with open(txt_file, 'w') as tf:
        for jpg_file in glob.glob(image_path + '*.jpg'):
            tf.write(jpg_file + '\n')

generate_train_and_val(train_image_path, txt_path + 'train.txt')
generate_train_and_val(valid_image_path, txt_path + 'valid.txt')

数据集格式如图 

 

4、修改参数 

 

 创建自己的data.yaml

 train:训练集img地址; 

val:验证机img地址;

nc:种类数量

names:种类名字

 

 weights:去github下载预训练权重,放在自己的目录下

cfg:改成自己的目录下的yolov7.yaml 把nc改为自己的类别数

data: 刚才自己创建的data.yaml

epoches:训练轮数

batch_size:小批次数量,(2060s 640*640 最大开4,开8爆显存)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用YOLOv7训练自己的数据集,您需要执行以下步骤: 1. 准备数据集:首先,您需要准备一个包含训练图像和相应标注文件的数据集。标注文件应该是YOLO格式(.txt),每个文件对应于一个图像,并包含每个对象的类别和位置信息。 2. 下载YOLOv7代码:您需要从YOLOv7的GitHub存储库中下载代码。您可以使用以下命令克隆存储库: ``` git clone https://github.com/WongKinYiu/yolov7.git ``` 3. 配置YOLOv7:在下载代码后,您需要编辑“yolov7.cfg”文件来配置YOLOv7模型的参数,如类别数量和输入图像的大小等。 4. 转换数据集:YOLOv7需要将数据集转换为Darknet格式,因此您需要使用提供的脚本将数据集转换为Darknet格式: ``` python3 train.py --img 640 --batch 16 --epochs 10 --data ./data/custom.data --cfg ./models/yolov7.cfg --weights yolov7.pt --name yolov7-custom ``` 其中,--data参数指定您的自定义数据集的路径,--cfg参数指定您的自定义配置文件,--weights参数指定预训练模型的路径,--name参数指定模型的名称。 5. 训练模型:使用以下命令开始训练模型: ``` python3 train.py --img 640 --batch 16 --epochs 10 --data ./data/custom.data --cfg ./models/yolov7.cfg --weights yolov7.pt --name yolov7-custom ``` 6. 测试模型:训练完成后,您可以使用以下命令对模型进行测试: ``` python3 detect.py --weights ./runs/train/yolov7-custom/weights/best.pt --img 640 --conf 0.5 --source ./data/samples/ ``` 其中,--weights参数指定训练好的模型的路径,--img参数指定输入图像的大小,--conf参数指定置信度阈值,--source参数指定要检测的图像文件夹。 希望这些步骤可以帮助您训练自己的YOLOv7模型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值