使用深度学习目标检测框架yolov8训练车站行为摔倒袭击异常行为检测数据集,构建车站行为异常检测系统,识别摔打,袭击,破坏公共物品,包括数据集准备、模型训练和结果评估

使用深度学习目标检测框架yolov8训练车站行为摔倒袭击异常行为检测数据集,构建车站行为异常检测系统,识别摔打,袭击,破坏公共物品,包括数据集准备、模型训练和结果评估在这里插入图片描述
车站行为异常检测数据集,2295张,、
在这里插入图片描述

yolo和voc两种标注方式

4类,标注数量:
NORMAL正常: 2770
FALLDOWN摔倒: 1210
ASSAULT袭击: 794
VANDALISM破坏公共物品: 86
image num: 2295

基于车站行为异常检测数据集进行目标检测任务。数据集包含2295张图片,并且标注为YOLO和VOC两种格式。以下是详细的步骤,包括数据准备、模型训练和评估。
在这里插入图片描述

文章代码及内容仅供参考

环境准备

确保您已经安装了以下软件和库:

  • Python 3.8 或更高版本
  • PyTorch 1.9 或更高版本
  • torchvision 0.10 或更高版本
  • OpenCV
  • numpy
  • pandas
  • matplotlib
  • scikit-image
  • albumentations(用于数据增强)

您可以使用以下命令安装所需的Python库:

pip install torch torchvision opencv-python numpy pandas matplotlib scikit-image albumentations ultralytics

数据集准备

假设您的数据集已经按照标准格式组织好,并且包含训练集、验证集和测试集。以下是数据集的预期结构:在这里插入图片描述


datasets/
└── station_behavior_detection/
    ├── images/
    │   ├── train/
    │   ├── val/
    │   └── test/
    ├── labels_yolo/
    │   ├── train/
    │   ├── val/
    │   └── test/
    ├── labels_voc/
    │   ├── Annotations/
    │   ├── ImageSets/
    │       └── Main/
    └── data.yaml
类别描述文件 (data.yaml)

根据提供的信息,整理出以下类别描述文件:

[<title="YOLOv8 Data Configuration File">]
train: ../datasets/station_behavior_detection/images/train/
val: ../datasets/station_behavior_detection/images/val/

nc: 4  # number of classes
names: ['NORMAL', 'FALLDOWN', 'ASSAULT', 'VANDALISM']  # list of class names

训练代码

我们将使用YOLOv8进行训练。首先,克隆YOLOv8仓库并设置环境。

git clone https://github.com/ultralytics/ultralytics.git
cd ultralytics
pip install -r requirements.txt
准备配置文件

我们已经在上一步中创建了 data.yaml 文件。

训练模型

使用以下命令开始训练:

yolo task=detect mode=train model=yolov8n.pt data=../datasets/station_behavior_detection/data.yaml epochs=100 imgsz=640 batch=16

结果评估

训练完成后,可以使用以下命令评估模型性能:

yolo task=detect mode=val model=runs/detect/train/weights/best.pt data=../datasets/station_behavior_detection/data.yaml

使用说明

  1. 配置路径

    • 确保 datasets/station_behavior_detection/ 目录结构正确。
    • 确保 data.yaml 中的路径和类别名称正确。
  2. 运行脚本

    • 在终端中依次运行训练脚本和评估脚本。
  3. 注意事项

    • 根据需要调整超参数和训练设置。
    • 可以通过修改 model 参数来选择不同的YOLOv8模型架构(如 yolov8s.pt, yolov8m.pt, yolov8l.pt, yolov8x.pt)。

示例

假设您的数据集文件夹结构如下:

datasets/
└── station_behavior_detection/
    ├── images/
    │   ├── train/
    │   ├── val/
    │   └── test/
    ├── labels_yolo/
    │   ├── train/
    │   ├── val/
    │   └── test/
    ├── labels_voc/
    │   ├── Annotations/
    │   ├── ImageSets/
    │       └── Main/
    └── data.yaml

并且 images/ 目录包含所有的图片,labels_yolo/ 目录包含对应的TXT标注文件。运行上述脚本后,您可以查看训练日志和最终的模型权重文件。

转换VOC标注到YOLO标注

如果您的数据集同时提供了VOC格式的标注,但您希望统一使用YOLO格式,可以编写一个脚本来转换标注格式。

[<title="Convert VOC to YOLO Format">]
import os
import xml.etree.ElementTree as ET
import cv2

def convert_voc_to_yolo(voc_annotations_dir, yolo_labels_dir, image_dir):
    # Create the output directory if it doesn't exist
    os.makedirs(yolo_labels_dir, exist_ok=True)
    
    # Get all annotation files in the directory
    annotation_files = [f for f in os.listdir(voc_annotations_dir) if f.endswith('.xml')]
    
    for ann_file in annotation_files:
        tree = ET.parse(os.path.join(voc_annotations_dir, ann_file))
        root = tree.getroot()
        
        image_filename = root.find('filename').text
        image_path = os.path.join(image_dir, image_filename)
        image = cv2.imread(image_path)
        height, width, _ = image.shape
        
        with open(os.path.join(yolo_labels_dir, ann_file.replace('.xml', '.txt')), 'w') as f:
            for obj in root.findall('object'):
                label_name = obj.find('name').text
                bbox = obj.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)
                
                # Convert bounding box coordinates from Pascal VOC format to YOLO format
                x_center = (xmin + xmax) / 2.0 / width
                y_center = (ymin + ymax) / 2.0 / height
                bbox_width = (xmax - xmin) / width
                bbox_height = (ymax - ymin) / height
                
                # Map label name to class ID
                class_id_map = {
                    'NORMAL': 0,
                    'FALLDOWN': 1,
                    'ASSAULT': 2,
                    'VANDALISM': 3
                }
                class_id = class_id_map[label_name]
                
                f.write(f"{class_id} {x_center} {y_center} {bbox_width} {bbox_height}\n")

# Example usage
voc_annotations_dir = '../datasets/station_behavior_detection/labels_voc/Annotations'
yolo_labels_dir = '../datasets/station_behavior_detection/labels_yolo'
image_dir = '../datasets/station_behavior_detection/images'

convert_voc_to_yolo(voc_annotations_dir, yolo_labels_dir, image_dir)

总结

可以构建一个全面的车站行为异常检测系统,包括数据集准备、模型训练和结果评估。以下是所有相关的代码文件:

  1. YOLOv8数据集配置文件 (data.yaml)
  2. 训练命令
  3. VOC到YOLO格式转换脚本

希望这些信息对你有所帮助!如果您有任何问题或需要进一步的帮助,请告诉我。

完整代码总结

以下是完整的配置文件和训练命令:

YOLOv8数据集配置文件 (data.yaml)
[<title="YOLOv8 Data Configuration File">]
train: ../datasets/station_behavior_detection/images/train/
val: ../datasets/station_behavior_detection/images/val/

nc: 4  # number of classes
names: ['NORMAL', 'FALLDOWN', 'ASSAULT', 'VANDALISM']  # list of class names
训练命令
yolo task=detect mode=train model=yolov8n.pt data=../datasets/station_behavior_detection/data.yaml epochs=100 imgsz=640 batch=16
评估命令
yolo task=detect mode=val model=runs/detect/train/weights/best.pt data=../datasets/station_behavior_detection/data.yaml
VOC到YOLO格式转换脚本
[<title="Convert VOC to YOLO Format">]
import os
import xml.etree.ElementTree as ET
import cv2

def convert_voc_to_yolo(voc_annotations_dir, yolo_labels_dir, image_dir):
    # Create the output directory if it doesn't exist
    os.makedirs(yolo_labels_dir, exist_ok=True)
    
    # Get all annotation files in the directory
    annotation_files = [f for f in os.listdir(voc_annotations_dir) if f.endswith('.xml')]
    
    for ann_file in annotation_files:
        tree = ET.parse(os.path.join(voc_annotations_dir, ann_file))
        root = tree.getroot()
        
        image_filename = root.find('filename').text
        image_path = os.path.join(image_dir, image_filename)
        image = cv2.imread(image_path)
        height, width, _ = image.shape
        
        with open(os.path.join(yolo_labels_dir, ann_file.replace('.xml', '.txt')), 'w') as f:
            for obj in root.findall('object'):
                label_name = obj.find('name').text
                bbox = obj.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)
                
                # Convert bounding box coordinates from Pascal VOC format to YOLO format
                x_center = (xmin + xmax) / 2.0 / width
                y_center = (ymin + ymax) / 2.0 / height
                bbox_width = (xmax - xmin) / width
                bbox_height = (ymax - ymin) / height
                
                # Map label name to class ID
                class_id_map = {
                    'NORMAL': 0,
                    'FALLDOWN': 1,
                    'ASSAULT': 2,
                    'VANDALISM': 3
                }
                class_id = class_id_map[label_name]
                
                f.write(f"{class_id} {x_center} {y_center} {bbox_width} {bbox_height}\n")

# Example usage
voc_annotations_dir = '../datasets/station_behavior_detection/labels_voc/Annotations'
yolo_labels_dir = '../datasets/station_behavior_detection/labels_yolo'
image_dir = '../datasets/station_behavior_detection/images'

convert_voc_to_yolo(voc_annotations_dir, yolo_labels_dir, image_dir)

hope这些信息能帮助您顺利进行模型训练和评估。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值