如何使用yolo批量标注图片
时间: 2024-05-06 17:15:30 浏览: 15
要使用YOLO进行批量标注图片,可以按照以下步骤:
1. 准备数据集:将需要标注的图片保存在一个文件夹中,并在该文件夹中创建一个labels子文件夹用于保存标注结果。
2. 安装YOLO:按照YOLO官方文档的指引,安装YOLO。
3. 创建标注文件:使用YOLO提供的labelImg工具或其他标注工具,创建标注文件。标注文件应该包含每张图片中所有目标的类别和位置信息。
4. 将标注文件转换为YOLO格式:将标注文件转换为YOLO所需的格式。YOLO要求每个标注文件包含一行数据,该行数据应该包含目标的类别和位置信息。位置信息应该是目标在图片中的中心点坐标、宽度和高度,以及相对于图片大小的比例。
5. 执行批量标注脚本:编写一个Python脚本,使用YOLO提供的API读取每个图片和相应的标注文件,并将标注结果保存在labels子文件夹中。
以下是一个简单的Python脚本示例:
```
import os
import cv2
import numpy as np
import glob
# 标注文件所在目录
label_dir = "labels"
# 图片文件所在目录
image_dir = "images"
# YOLO配置文件
cfg_file = "yolov3.cfg"
# YOLO权重文件
weight_file = "yolov3.weights"
# YOLO类别文件
class_file = "coco.names"
# 加载YOLO模型
net = cv2.dnn.readNetFromDarknet(cfg_file, weight_file)
# 加载类别文件
classes = []
with open(class_file, "r") as f:
classes = [line.strip() for line in f.readlines()]
# 遍历图片文件
for image_file in glob.glob(os.path.join(image_dir, "*.jpg")):
# 加载图片
image = cv2.imread(image_file)
height, width, channels = image.shape
# 执行YOLO检测
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
outputs = net.forward(output_layers)
# 解析YOLO输出
boxes = []
confidences = []
class_ids = []
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# 标注结果保存到文件
label_file = os.path.join(label_dir, os.path.basename(image_file).replace(".jpg", ".txt"))
with open(label_file, "w") as f:
for i in range(len(boxes)):
class_name = classes[class_ids[i]]
x, y, w, h = boxes[i]
x_rel = x / width
y_rel = y / height
w_rel = w / width
h_rel = h / height
f.write(f"{class_name} {x_rel:.6f} {y_rel:.6f} {w_rel:.6f} {h_rel:.6f}\n")
```
该脚本使用OpenCV的DNN模块执行YOLO检测,并将标注结果保存到labels子文件夹中。