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

2025-06-14【视觉】视频转化为图集

很简单的,很容易的代码,
1.以时间命名图片
2.多线程处理
3.tqdm进度条可视化
在这里插入图片描述

import cv2
import os
from pathlib import Path
import concurrent.futures
from tqdm import tqdmdef video_to_images(video_path, output_dir='frames', frame_interval=1, workers=4, use_time_name=True):"""使用多线程和tqdm进度条将视频转换为图片序列参数:video_path (str): 输入视频的路径output_dir (str): 输出图片的目录frame_interval (int): 每隔多少帧提取一帧workers (int): 线程池大小use_time_name (bool): 是否使用时间作为文件名"""# 确保输出目录存在Path(output_dir).mkdir(parents=True, exist_ok=True)# 打开视频获取基本信息cap = cv2.VideoCapture(video_path)if not cap.isOpened():print(f"错误:无法打开视频文件 {video_path}")returnfps = cap.get(cv2.CAP_PROP_FPS)total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))duration = total_frames / fps  # 视频总时长(秒)cap.release()# 计算需要处理的帧索引frame_indices = list(range(0, total_frames, frame_interval))print(f"视频信息: {fps:.2f} FPS, 共 {total_frames} 帧, 时长 {duration:.2f} 秒, 将提取 {len(frame_indices)} 帧")def frame_to_timecode(frame_idx, fps):"""将帧索引转换为时分秒格式"""total_seconds = frame_idx / fpshours = int(total_seconds // 3600)minutes = int((total_seconds % 3600) // 60)seconds = total_seconds % 60return hours, minutes, secondsdef process_frame(index):cap = cv2.VideoCapture(video_path)cap.set(cv2.CAP_PROP_POS_FRAMES, index)ret, frame = cap.read()cap.release()if ret:if use_time_name:# 生成时间格式文件名: time_时_分_秒_毫秒.jpgh, m, s = frame_to_timecode(index, fps)ms = int((s - int(s)) * 1000)  # 毫秒部分output_path = os.path.join(output_dir, f"time_{h:02d}_{m:02d}_{int(s):02d}_{ms:03d}.jpg")else:# 原始的帧索引命名output_path = os.path.join(output_dir, f"frame_{index:06d}.jpg")cv2.imwrite(output_path, frame)return Truereturn False# 使用线程池并行处理帧,并添加tqdm进度条with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:results = list(tqdm(executor.map(process_frame, frame_indices),total=len(frame_indices),desc="处理进度",unit="帧"))success_count = sum(results)print(f"视频转图片完成!成功生成 {success_count} 张图片,保存在 {output_dir} 目录下")if __name__ == "__main__":# 使用示例 - 按时间命名video_file = "2.mp4"  # 替换为你的视频文件路径video_to_images(video_file,output_dir="output_frames",frame_interval=25,  # 每秒提取一帧(假设视频为25fps)workers=4,  # 根据CPU核心数调整use_time_name=True  # 使用时间命名)#时间格式:time_时_分_秒_毫秒.jpg(例如:time_00_01_53_000.jpg表示 1 分 53 秒整)
http://www.xdnf.cn/news/1031131.html

相关文章:

  • linux-部署go开发环境
  • 【Flutter】程序报错导致的灰屏总结
  • 华为云Flexus+DeepSeek征文 | 模型即服务(MaaS)安全攻防:企业级数据隔离方案
  • Elasticsearch高效文章搜索实践
  • git-build-package 工具代码详细解读
  • Spark DAG、Stage 划分与 Task 调度底层原理深度剖析
  • MySQL EXPLAIN 详解
  • 【LUT技术专题】4DLUT代码讲解
  • 【系统分析师】2009年真题:综合知识-答案及详解
  • 【卫星通信】卫星与5G深度融合的架构研究——释放非地面网络潜能,构建全球无缝连接【3GPP TR 23.700-19 V0.1.0 (2025-04)】
  • 本地 MySQL 环境连接问题排查与解决笔记
  • 文件同步·使用同步软件来管理文件(外接大脑)
  • 项目拓展-简易SQL监控,P6SPY拦截所有jdbc连接并打印执行SQL
  • 三维重建 —— 4. 三维重建基础与极几何
  • LeetCode 第73题:矩阵置零
  • 区块链与人工智能的融合:从信任到智能的IT新引擎
  • JUC核心解析系列(五)——执行框架(Executor Framework)深度解析
  • ELK 日志分析系统深度解析与实战指南
  • 使用预训练卷积神经模型进行分类(MATLAB例)
  • MaxCompute的Logview分析详解
  • 仿飞书部门选择器
  • 二维码识别深度解析
  • 大模型笔记1:大致了解大模型
  • Burgers方程初值问题解的有效区域
  • JVM 参数调优核心原则与常用参数
  • 【无标题】在 4K 高分辨率(如 3840×2160)笔记本上运行 VMware 虚拟机时平面太小字体太小(ubuntu)
  • 如何在 ArcGIS 中使用 Microsoft Excel 文件_20250614
  • 【软测】node.js辅助生成测试报告
  • 写作词汇积累(A):颇有微词、微妙(“微”字的学习理解)
  • Veeam Backup Replication系统的安装与使用