当前位置: 首页 > news >正文

yolov8训练模型、测试视频

yolov8先训练生成best.pt文件,用这个生成的模型进行视频的测试

因为本来用的代码生成的测试视频打不开,格式应该是损坏了,或者部分帧没有正常保存吧。

修改了一下代码,现状可以正常打开生成的视频了。

1、训练代码train.py

import os

# os.environ["CUDA_VISIBLE_DEVICES"] = "3"  # 同样是选择第3块GPU

from ultralytics import YOLO

# Load a model
# model = YOLO("yolov8n.yaml")  # build a new model from YAML
# model = YOLO("yolov8n.pt")  # load a pretrained model (recommended for training)

# ffs = os.listdir("cfg1116/new_cfg")
# for ff in ffs:
model = YOLO(f"cfg1116/yolov8n.yaml")  # build from YAML and transfer weights
# Train the model
# results = model.train(data=r"/mnt/disk3/sunjiahui/CV-code/v8_all/data.yaml", epochs=5, imgsz=1280, workers=0, batch=2, device=[2])
results = model.train(
    data=r"/mnt/disk3/sunjiahui/CV-code/v8_all/data.yaml",
    epochs=500,
    imgsz=1280,
    workers=0,
    batch=2,
    device=[0],
    hsv_h=0.015,  # HSV色调变化
    hsv_s=0.7,    # HSV饱和度变化
    hsv_v=0.4,    # HSV亮度变化
    degrees=0.0,  # 旋转角度
    translate=0.1,  # 平移比例
    scale=0.5,    # 缩放比例
    shear=0.0,    # 剪切变换
    perspective=0.0,  # 透视变换
    flipud=0.0,   # 上下翻转概率
    fliplr=0.5,   # 左右翻转概率
    mosaic=1.0,   # Mosaic增强的概率
    mixup=0.0     # MixUp增强的概率
)
model.val(imgsz=[1280,1280])

2、测试代码:视频

from ultralytics import YOLO
import cv2
import os

os.environ["CUDA_VISIBLE_DEVICES"] = "2"  # 同样是选择第3块GPU

def process_video():
    # 初始化模型
    model = YOLO("runs/detect/train2/weights/best.pt")
    
    # 输入输出路径
    input_path = "/mnt/disk3/sunjiahui/CV-code/v8_all/XIONG_AN/shipin.mp4"
    output_path = "/mnt/disk3/sunjiahui/CV-code/v8_all/XIONG_AN/output_video15.mp4"
    
    # 尝试不同编解码器组合
    codec_options = ['mp4v', 'avc1', 'X264', 'MJPG']
    success = False
    
    for codec in codec_options:
        try:
            cap = cv2.VideoCapture(input_path)
            fps = int(cap.get(cv2.CAP_PROP_FPS)) or 30  # 处理fps为0的情况
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            
            fourcc = cv2.VideoWriter_fourcc(*codec)
            out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
            print(f"尝试使用编解码器 {codec}...")
            
            while cap.isOpened():
                ret, frame = cap.read()
                if not ret:
                    break
                
                results = model.predict(frame, conf=0.15)
                annotated_frame = results[0].plot()
                
                # 确保帧格式正确
                if annotated_frame.shape[:2] != (height, width):
                    annotated_frame = cv2.resize(annotated_frame, (width, height))
                
                out.write(annotated_frame)
            
            success = True
            break
            
        except Exception as e:
            print(f"编解码器 {codec} 失败: {str(e)}")
            if os.path.exists(output_path):
                os.remove(output_path)
            continue
            
        finally:
            cap.release()
            out.release()
    
    if success:
        print(f"视频生成成功!保存路径:{os.path.abspath(output_path)}")
        print("如果仍无法播放,请尝试以下方案:")
        print("1. 使用 VLC 播放器(兼容性最佳)")
        print("2. 执行命令:ffmpeg -i output_video.mp4 -c:v libx264 final.mp4")
    else:
        print("所有编解码器尝试失败,改用图像序列方案...")
        save_as_image_sequence(model, input_path)

def save_as_image_sequence(model, input_path):
    """备用方案:保存为图片序列"""
    output_dir = "video_frames"
    os.makedirs(output_dir, exist_ok=True)
    
    cap = cv2.VideoCapture(input_path)
    frame_count = 0
    
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        
        results = model.predict(frame)
        annotated_frame = results[0].plot()
        
        cv2.imwrite(f"{output_dir}/frame_{frame_count:04d}.jpg", annotated_frame)
        frame_count += 1
    
    cap.release()
    print(f"图像序列已保存至 {output_dir},可用以下命令合成视频:")
    print(f"ffmpeg -framerate 30 -i {output_dir}/frame_%04d.jpg -c:v libx264 output.mp4")

if __name__ == "__main__":
    process_video()

相关文章:

  • 贴源数据层建设
  • NameError: name ‘libpaddle‘ is not defined
  • MAX232数据手册:搭建电平转换桥梁,助力串口稳定通信
  • 学到什么记什么(25.3.3)
  • 深入学习Linux内存管理-缺页异常
  • MySQL数据库的数据类型
  • 刷题日记——部分二分算法题目分享
  • C++学习之C++初识、C++对C语言增强、对C语言扩展
  • 批量设置 Word 样式,如字体信息、段落距离、行距、页边距等信息
  • MOE(Mixture of Experts)门控网络的实现与优化
  • pywin32连接到WMI接口获取指定名称程序路径
  • 【Java数据结构】哈希表
  • 【DOM 型 XSS举例】
  • 开放鸿蒙认证,OpenHarmony兼容性认证介绍
  • 2025统计建模大赛选题参考?
  • 算法系列之数据结构-二叉树
  • Blueprint —— Flow Control
  • C#中泛型的协变和逆变
  • 机器学习之集成学习思维导图
  • 【人工智能】Python中的迁移学习:使用预训练模型进行分类任务
  • 福州开发企业网站/百度最新版下载
  • 昆山哪里有人做网站/国产长尾关键词拘挖掘
  • 购物网站设计理念/西安企业网站seo
  • 灰色网站欣赏/360优化大师历史版本
  • 网站开发需要英语/网络营销推广的方法
  • 做物流行业网站/百度关键词查询工具免费