yolov8练习模子、测试视频

[复制链接]
发表于 2025-10-21 23:39:24 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
yolov8先练习天生best.pt文件,用这个天生的模子举行视频的测试
由于原来用的代码天生的测试视频打不开,格式应该是破坏了,大概部门帧没有正常生存吧。
修改了一下代码,近况可以正常打开天生的视频了。
1、练习代码train.py
  1. import os
  2. # os.environ["CUDA_VISIBLE_DEVICES"] = "3"  # 同样是选择第3块GPU
  3. from ultralytics import YOLO
  4. # Load a model
  5. # model = YOLO("yolov8n.yaml")  # build a new model from YAML
  6. # model = YOLO("yolov8n.pt")  # load a pretrained model (recommended for training)
  7. # ffs = os.listdir("cfg1116/new_cfg")
  8. # for ff in ffs:
  9. model = YOLO(f"cfg1116/yolov8n.yaml")  # build from YAML and transfer weights
  10. # Train the model
  11. # results = model.train(data=r"/mnt/disk3/sunjiahui/CV-code/v8_all/data.yaml", epochs=5, imgsz=1280, workers=0, batch=2, device=[2])
  12. results = model.train(
  13.     data=r"/mnt/disk3/sunjiahui/CV-code/v8_all/data.yaml",
  14.     epochs=500,
  15.     imgsz=1280,
  16.     workers=0,
  17.     batch=2,
  18.     device=[0],
  19.     hsv_h=0.015,  # HSV色调变化
  20.     hsv_s=0.7,    # HSV饱和度变化
  21.     hsv_v=0.4,    # HSV亮度变化
  22.     degrees=0.0,  # 旋转角度
  23.     translate=0.1,  # 平移比例
  24.     scale=0.5,    # 缩放比例
  25.     shear=0.0,    # 剪切变换
  26.     perspective=0.0,  # 透视变换
  27.     flipud=0.0,   # 上下翻转概率
  28.     fliplr=0.5,   # 左右翻转概率
  29.     mosaic=1.0,   # Mosaic增强的概率
  30.     mixup=0.0     # MixUp增强的概率
  31. )
  32. model.val(imgsz=[1280,1280])
复制代码
2、测试代码:视频
  1. from ultralytics import YOLO
  2. import cv2
  3. import os
  4. os.environ["CUDA_VISIBLE_DEVICES"] = "2"  # 同样是选择第3块GPU
  5. def process_video():
  6.     # 初始化模型
  7.     model = YOLO("runs/detect/train2/weights/best.pt")
  8.    
  9.     # 输入输出路径
  10.     input_path = "/mnt/disk3/sunjiahui/CV-code/v8_all/XIONG_AN/shipin.mp4"
  11.     output_path = "/mnt/disk3/sunjiahui/CV-code/v8_all/XIONG_AN/output_video15.mp4"
  12.    
  13.     # 尝试不同编解码器组合
  14.     codec_options = ['mp4v', 'avc1', 'X264', 'MJPG']
  15.     success = False
  16.    
  17.     for codec in codec_options:
  18.         try:
  19.             cap = cv2.VideoCapture(input_path)
  20.             fps = int(cap.get(cv2.CAP_PROP_FPS)) or 30  # 处理fps为0的情况
  21.             width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  22.             height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  23.             
  24.             fourcc = cv2.VideoWriter_fourcc(*codec)
  25.             out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
  26.             print(f"尝试使用编解码器 {codec}...")
  27.             
  28.             while cap.isOpened():
  29.                 ret, frame = cap.read()
  30.                 if not ret:
  31.                     break
  32.                
  33.                 results = model.predict(frame, conf=0.15)
  34.                 annotated_frame = results[0].plot()
  35.                
  36.                 # 确保帧格式正确
  37.                 if annotated_frame.shape[:2] != (height, width):
  38.                     annotated_frame = cv2.resize(annotated_frame, (width, height))
  39.                
  40.                 out.write(annotated_frame)
  41.             
  42.             success = True
  43.             break
  44.             
  45.         except Exception as e:
  46.             print(f"编解码器 {codec} 失败: {str(e)}")
  47.             if os.path.exists(output_path):
  48.                 os.remove(output_path)
  49.             continue
  50.             
  51.         finally:
  52.             cap.release()
  53.             out.release()
  54.    
  55.     if success:
  56.         print(f"视频生成成功!保存路径:{os.path.abspath(output_path)}")
  57.         print("如果仍无法播放,请尝试以下方案:")
  58.         print("1. 使用 VLC 播放器(兼容性最佳)")
  59.         print("2. 执行命令:ffmpeg -i output_video.mp4 -c:v libx264 final.mp4")
  60.     else:
  61.         print("所有编解码器尝试失败,改用图像序列方案...")
  62.         save_as_image_sequence(model, input_path)
  63. def save_as_image_sequence(model, input_path):
  64.     """备用方案:保存为图片序列"""
  65.     output_dir = "video_frames"
  66.     os.makedirs(output_dir, exist_ok=True)
  67.    
  68.     cap = cv2.VideoCapture(input_path)
  69.     frame_count = 0
  70.    
  71.     while cap.isOpened():
  72.         ret, frame = cap.read()
  73.         if not ret:
  74.             break
  75.         
  76.         results = model.predict(frame)
  77.         annotated_frame = results[0].plot()
  78.         
  79.         cv2.imwrite(f"{output_dir}/frame_{frame_count:04d}.jpg", annotated_frame)
  80.         frame_count += 1
  81.    
  82.     cap.release()
  83.     print(f"图像序列已保存至 {output_dir},可用以下命令合成视频:")
  84.     print(f"ffmpeg -framerate 30 -i {output_dir}/frame_%04d.jpg -c:v libx264 output.mp4")
  85. if __name__ == "__main__":
  86.     process_video()
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表