使用YOLOv8实现YOLO格式标签的自动标注

1 准备

(1)已经训练好的yolov8权重文件('yolov8/runs/detect/train/weights/best.pt')

(2)需要自动标注的图片文件('/image/*.jpg')

2 开始标注

import torch
from ultralytics import YOLO


class Yolov8Detect():
    def __init__(self, weights):
        cuda = True if torch.cuda.is_available() else False
        self.device = torch.device('cuda:0' if cuda else 'cpu')
        self.detect_model = YOLO(weights)
        self.detect_model.to(self.device)


    def inferences(self, inputs):
        results = self.detect_model(inputs)
        for result in results:
            label_text = []
            boxes = result.boxes
            for box in boxes:
                cat_num = int(box.cls.cpu())
                label_text.append([cat_num, box.xywhn.cpu().numpy()])
            save_path = inputs.replace('jpg', 'txt')
            txt_construct(save_path, label_text=label_text)


def txt_construct(save_path, label_text):
    with open(save_path, 'w') as file:
        file.truncate()
    for label in label_text:
        with open(save_path, 'a') as txt_file:
            label_ = label[0]
            size = label[1][0].tolist()
            size_string = ' '.join(map(str, size))
            result = f'{label_} {size_string}'
            print('result', result)
            txt_file.write(str(result))
            txt_file.write('\n')



if __name__ == '__main__':

    #model_path替换成自己的model路径
    model_path = '/best.pt'
    model = Yolov8Detect(model_path)
    import glob

    #image_path替换成需要自动标注的文件路径
    image_path = glob.glob('/*.jpg')
    for img_path in image_path[:]:
        model.inferences(img_path)

  生成的.txt文件会保存在图片所在文件夹中。

### 使用YOLO进行自动标注的方法 对于希望利用YOLO模型实现自动标注的需求,存在多种工具和方法可供选择。其中一种推荐的方式是结合使用YOLO与`labelImg`完成初步的自动标注工作[^1]。 #### 利用YOLO与labelImg组合进行自动标注 - **准备阶段** 需要先准备好训练好的YOLO权重文件以及待处理的数据集图片路径列表。确保安装了Python环境和支持库如OpenCV等必要组件。 - **执行自动标注过程** 可编写脚本加载预训练的YOLO模型并遍历指定目录下的所有图像文件,逐一对每张图做推理预测获取边界框坐标信息作为初始标签数据。这些临时生成的结果可按照`labelImg`所接受的标准格式保存下来以便后续导入该软件进一步编辑调整。 ```python import cv2 from yolov7 import YOLOv7 # 假设这是自定义封装的一个接口类来简化调用原生API的过程 model = YOLOv7('path/to/weights') # 加载YOLO v7或其他版本模型实例化对象 image_paths = ['img1.jpg', 'img2.png'] # 图片集合 for img_path in image_paths: frame = cv2.imread(img_path) boxes = model.detect(frame) # 调用detect函数传入单帧画面得到返回值boxes即为检测出来的矩形区域位置参数 with open(f"{img_path}.txt", "w") as f: for box in boxes: label, confidence, (x_center, y_center), width_height = box line = f"{label} {confidence:.6f} {x_center:.6f} {y_center:.6f} {width_height[0]:.6f} {width_height[1]:.6f}\n" f.write(line) print("Automatic labeling completed.") ``` 此段代码展示了如何通过读取一系列静态图片输入给定YOLO模型来进行批量式的快速标记操作,并将产生的元数据记录成`.txt`纯文本形式供其他程序解析读写。 #### 更高级别的自动标注方案 除了上述基础方式外还有更复杂的解决方案被提出过,在某些情况下能够提供更高的精度和效率。比如有文章提到基于YOLOv10实现了从简单固定的模式向智能化程度更高的动态适应型转变,后者能更好地应对复杂场景中的挑战从而提升整体性能表现[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值