电力设备类输电线路覆冰检测数据集 json格式 2千张
·
数据集描述:
电力设备类输电线路覆冰检测数据集 json格式
2千张

1

1

1

采用了点标注的方式,味着每个标注点代表了覆冰区域的一个关键点。训练能够识别和检测输电线路覆冰的模型,需要将这些点标注转换为边界框标注,以便于目标检测模型(如YOLOv8)进行学习。
1. 数据预处理
1.1 将点标注转换为边界框标注
假设JSON文件中存储了每个图像的点标注信息,编写一个脚本来将这些点标注转换为边界框标注。以下是一个简单的Python示例,说明如何实现这一点:
import json
import os
from collections import defaultdict
def points_to_bbox(points):
"""将点列表转换为边界框"""
x_coords = [point[0] for point in points]
y_coords = [point[1] for point in points]
x_min, x_max = min(x_coords), max(x_coords)
y_min, y_max = min(y_coords), max(y_coords)
return [x_min, y_min, x_max, y_max]
def convert_json_to_yolo(json_dir, img_dir, output_dir, class_mapping):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(json_dir):
if filename.endswith('.json'):
with open(os.path.join(json_dir, filename), 'r') as f:
data = json.load(f)
image_filename = data['imagePath']
image_path = os.path.join(img_dir, image_filename)
img = cv2.imread(image_path)
height, width, _ = img.shape
label_filename = os.path.splitext(filename)[0] + '.txt'
label_path = os.path.join(output_dir, label_filename)
with open(label_path, 'w') as out_file:
for shape in data['shapes']:
label = shape['label']
if label not in class_mapping:
continue
cls_id = class_mapping[label]
points = shape['points']
bbox_2d = points_to_bbox(points)
x_min, y_min, x_max, y_max = bbox_2d
# 转换为YOLO格式
x_center = ((x_min + x_max) / 2) / width
y_center = ((y_min + y_max) / 2) / height
w = (x_max - x_min) / width
h = (y_max - y_min) / height
out_file.write(f"{cls_id} {x_center} {y_center} {w} {h}\n")
# 示例使用
class_mapping = {"Ice": 0}
json_dir = 'path/to/jsons'
img_dir = 'path/to/images'
output_dir = 'path/to/labels'
convert_json_to_yolo(json_dir, img_dir, output_dir, class_mapping)
2. 训练模型
2.1 准备数据集
数据集按照YOLOv8的要求组织好,包括images和labels目录,并且有一个data.yaml文件来描述数据集的信息。
2.2 开始训练
使用Ultralytics的YOLOv8库开始训练模型。如果您已经安装了必要的依赖项,可以使用以下代码开始训练:
from ultralytics import YOLO
model = YOLO('yolov8s.pt') # 加载预训练模型
results = model.train(
data='path/to/data.yaml', # 数据集配置文件路径
epochs=100, # 训练周期数
imgsz=640, # 输入图像大小
batch=16, # 每批次样本数量
device=0, # 使用第0号GPU
project='runs/detect/icedetection', # 结果保存位置
name='exp', # 实验名称
save=True, # 是否保存最佳模型
)
📊 YOLOv8 评估及推理代码详解
✅ 一、推理代码(Inference)
1. 单张图片推理
from ultralytics import YOLO
import cv2
# 加载训练好的模型权重
model = YOLO('runs/ice_detection/exp/weights/best.pt')
# 图像路径
img_path = 'dataset/images/val/0001.jpg'
# 执行推理
results = model(img_path)
# 可视化结果
for r in results:
im_array = r.plot() # 绘制检测结果
im = cv2.cvtColor(im_array, cv2.COLOR_RGB2BGR) # 转换颜色空间以便OpenCV显示
cv2.imshow('Detection Result', im)
cv2.waitKey(0) # 等待按键
cv2.destroyAllWindows() # 关闭窗口
2. 视频流推理
cap = cv2.VideoCapture('video.mp4') # 替换为你的视频路径
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
results = model(frame) # 对每一帧进行推理
for r in results:
im_array = r.plot()
im = cv2.cvtColor(im_array, cv2.COLOR_RGB2BGR)
cv2.imshow('Video Detection', im)
if cv2.waitKey(1) == ord('q'): # 按下 'q' 键退出
break
cap.release()
cv2.destroyAllWindows()
📈 二、模型评估(Validation)
YOLOv8 提供了内置的验证功能,可以快速评估模型在验证集上的性能。
1. 使用命令行评估
yolo task=detect mode=val model=runs/ice_detection/exp/weights/best.pt data=data.yaml
2. 使用 Python API 进行评估
from ultralytics import YOLO
# 加载训练好的模型
model = YOLO('runs/ice_detection/exp/weights/best.pt')
# 执行验证
metrics = model.val(data='data.yaml') # data.yaml 是你的数据配置文件
# 打印关键指标
print("mAP50:", metrics.box.map50) # 在 IoU=0.5 时的 mAP
print("mAP50-95:", metrics.box.map) # 在 IoU=0.5~0.95 时的 mAP
print("Precision:", metrics.box.precision) # 精度
print("Recall:", metrics.box.recall) # 召回率
3. 评估结果说明
| 指标 | 含义 |
|---|---|
map50 | 在 IoU 阈值为 0.5 时的平均精度 |
map | 在 IoU 阈值从 0.5 到 0.95 的平均精度 |
precision | 精度,即预测为正类中真正为正类的比例 |
recall | 召回率,即实际为正类中被正确预测的比例 |
📁 三、数据集结构回顾
确保你的数据集结构如下:
dataset/
├── images/
│ ├── train/
│ └── val/
├── labels/
│ ├── train/
│ └── val/
└── data.yaml
data.yaml 示例内容:
train: dataset/images/train
val: dataset/images/val
nc: 1
names: ['Ice']
🧪 四、选:自定义评估指标(如 PR 曲线)
YOLOv8 会自动保存 PR 曲线和混淆矩阵在 runs/val/exp/ 目录下。你也可以使用 sklearn 自定义绘制 PR 曲线:
from sklearn.metrics import precision_recall_curve
import matplotlib.pyplot as plt
# 假设你有真实标签 y_true 和预测置信度 y_scores
precision, recall, thresholds = precision_recall_curve(y_true, y_scores)
plt.plot(recall, precision, marker='.')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision-Recall Curve')
plt.grid()
plt.show()
更多推荐
所有评论(0)