yolov8训练初体验

最近在爬一些数据,有些网址的验证码比较难搞,于是使用yolov8来解决。

一、数据打标签并转为txt

使用的软件为X-AnyLabeling。内置各种模型,方便打标。

打标完成后由于是json格式,所以我们使用python转换即可


import json
import os

#矩形框时

def labelme_to_yolo(label_me_json_file, cls2id_dict):
    label_me_json = json.load(open(label_me_json_file, mode='r', encoding='UTF-8'))
    shapes = label_me_json['shapes']
    img_width, img_height = label_me_json['imageWidth'], label_me_json['imageHeight']
    img_path = label_me_json['imagePath']
    img_data = label_me_json['imageData'] if 'imageData' in label_me_json else ''

    labels = []
    for s in shapes:
        s_type = s['shape_type']
        s_type = s_type.lower()
        if s_type == 'rectangle':
            pts = s['points']
            x1, y1 = pts[0]  # left corner
            x2, y2 = pts[1]  # right corner
            x = (x1 + x2) / 2 / img_width
            y = (y1 + y2) / 2 / img_height
            w = abs(x2 - x1) / img_width
            h = abs(y2 - y1) / img_height
            cid = cls2id_dict[s['label']]
            labels.append(f'{cid} {x} {y} {w} {h}')

    return labels


def write_label2txt(save_txt_path, label_list):
    f = open(save_txt_path, "w", encoding="UTF-8")

    for label in label_list:
        temp_list = label.split(" ")
        f.write(temp_list[0])
        f.write(" ")
        f.write(temp_list[1])
        f.write(" ")
        f.write(temp_list[2])
        f.write(" ")
        f.write(temp_list[3])
        f.write(" ")
        f.write(temp_list[4])
        f.write("\n")


if __name__ == '__main__':
    # 原始图片文件夹路径
    img_dir = r"D:\pic\pic"
    # 原始JSON标签文件夹路径
    json_dir = r"D:\pic\label_json"
    # 生成保存TXT文件夹路径
    save_dir = r"D:\pic\label_txt"
    # 类别和序号的映射字典
    cls2id_dict = {"building1": "0"}

    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    for json_name in os.listdir(json_dir):
        json_path = os.path.join(json_dir, json_name)
        txt_name = json_name.split(".")[0] + ".txt"
        save_txt_path = os.path.join(save_dir, txt_name)
        labels = labelme_to_yolo(json_path, cls2id_dict)
        write_label2txt(save_txt_path, labels)
# 处理 X-Anylabeling 多边形矩阵的标注 json 转化 txt,提取点
import json
import os

name2id = { '球体'  : 0,
            '立方体': 1,
            '圆锥体': 2,
            '圆柱体': 3,
            '多面体': 4
           }  # 修改你的类别并且赋与 index


def decode_json(json_floder_path, txt_outer_path, json_name):
    txt_name = os.path.join(txt_outer_path,json_name[:-5]) + '.txt'
    with open(txt_name, 'a') as f:
        json_path = os.path.join(json_floder_path, json_name)
        data = json.load(open(json_path, 'r', encoding='utf8', errors='ignore'))
        img_w = data['imageWidth']
        img_h = data['imageHeight']
        isshape_type = data['shapes'][0]['shape_type']
        print(isshape_type)
        dw = 1. / (img_w)
        dh = 1. / (img_h)
        for i in data['shapes']:
            label_name = i['label']
            if (i['shape_type'] == 'polygon'):
                point = []
                for lk in range(len(i['points'])):
                    x = float(i['points'][lk][0])
                    y = float(i['points'][lk][1])
                    point_x = x * dw
                    point_y = y * dh
                    point.append(point_x)
                    point.append(point_y)
                try:
                    formatted_line = f"{name2id[label_name]} {' '.join(str(a) for a in point)}\n"
                    f.write(formatted_line)
                except KeyError:
                    print(f"Warning: Label name '{label_name}' not found in name2id mapping.")
        f.close()


if __name__ == "__main__":
    json_floder_path = r'D:\pic\label_json'  # 存放 json 的文件夹的绝对路径
    txt_outer_path = r'D:\pic\label_txt'  # 存放 txt 的文件夹绝对路径
    json_names = os.listdir(json_floder_path)
    flagcount = 0
    for json_name in json_names:
        decode_json(json_floder_path, txt_outer_path, json_name)
        flagcount += 1

    print('-----------转化完毕------------')

二、使用yolov8训练

2.1 将图片和标签分别放在datasets目录下

2.2创建yaml文件

trian为训练的图片

val为预测的图片


train: D:\\software\\PyCharm\\workspace\\ultralytics\\datasest\\mypic\\images 
val: D:\\software\\PyCharm\\workspace\\SomeTry\\yanzhengma\\val 

names:
  0: '球体'
  1: '立方体'
  2: '圆锥体'
  3: '圆柱体'
  4: '多面体'

2.3 创建训练代码

YOLOv8文档

from ultralytics import YOLO


model = YOLO('yolov8n.pt')
model.train(data='mypic.yaml', epochs=100, imgsz=640, batch=8)





#用训练后的模型进行预测
yolo predict model=runs/detect/train/weights/best.pt source=D:\\software\\PyCharm\\workspace\\SomeTry\\yanzhengma\\val\\1719060455810geetest_image.jpg


训练结果

<think>嗯,用户想知道如何在x-anylabeling工具中导出ADE20K格式的标注文件。首先,我需要回忆一下ADE20K格式的具体要求。ADE20K数据集通常使用带有颜色编码的PNG图像作为标注,每个像素的颜色对应一个特定的类别。此外,可能还需要一个包含类别信息的文本文件,比如class_definitions.txt,里面列有每个类别的名称、颜色值等信息。 接下来,我得考虑x-anylabeling是否支持导出这种格式。根据用户提供的引用内容,比如引用[1]提到下载文件放到annotator/ckpts目录,这可能与工具中的某些插件或模型有关,但不确定是否直接影响导出功能。引用[3]讨论了掩码处理的方法,可能涉及到标注的生成方式,但同样需要确认工具的导出选项。 假设x-anylabeling支持导出为常见的格式如COCO或Pascal VOC,用户可能需要通过转换工具将现有格式转为ADE20K。或者,工具内部是否有直接的导出选项。可能需要分步骤说明:完成标注后,进入导出菜单,选择ADE20K格式,指定路径,并检查生成的标注文件和class_definitions.txt是否正确。 另外,用户可能遇到的问题包括导出的格式不正确,颜色编码不匹配,或者缺少必要的文件。这时需要建议用户检查颜色映射是否正确,或者是否需要手动编辑class_definitions文件。同时,参考引用[2]中提到的开放集合目标检测,可能涉及到类别定义的灵活性,但ADE20K格式是固定类别,所以需要确保标注时使用的类别与class_definitions一致。 总结步骤应该是:标注完成后,在导出选项中选择ADE20K格式,确认输出路径,验证生成的文件是否符合要求。如果工具不支持直接导出,可能需要编写脚本转换现有格式(如JSON)到ADE20K所需的PNG和文本文件。同时,注意颜色编码的准确性,确保每个类别的像素值与class_definitions.txt中的定义匹配。</think>在X-AnyLabeling导出ADE20K格式标注文件的操作流程如下: 1. **完成标注工作** - 使用矩形框/多边形工具完成图像标注,确保每个实例的类别名称与ADE20K数据集类别体系兼容[^2] 2. **导出标注文件** ```python # 导出功能伪代码逻辑 def export_ADE20K(annotations): for img in annotations: # 生成带颜色编码的标注图 color_mask = np.zeros((height, width, 3)) # 生成class_definitions.txt with open('class_definitions.txt', 'w') as f: for cls in classes: f.write(f"{cls.name} {cls.color[0]} {cls.color[1]} {cls.color[2]}\n") # 保存标注图像 cv2.imwrite(f"{img_id}_seg.png", color_mask) ``` 3. **文件结构要求** - 标注图像命名规范:`原文件名_seg.png` - 颜色编码文件:`class_definitions.txt` - 目录结构示例: ``` dataset/ ├── images/ │ ├── image1.jpg │ └── image2.jpg └── annotations/ ├── image1_seg.png ├── image2_seg.png └── class_definitions.txt ``` 4. **验证导出结果** - 使用图像查看工具确认标注图的颜色编码正确性 - 检查class_definitions.txt文件格式是否符合要求: ``` sky 0 128 128 building 128 0 0 tree 128 128 0 ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值