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

OpenCV-循环读取视频帧,对每一帧进行处理

原型代码

  • 内存模型:
    • 核心变量:frame,Numpy ndarray,每次会被覆盖,大小保持恒定
import cv2video_path = 'your_video.mp4'cap = cv2.VideoCapture(video_path)if not cap.isOpened():print("Can't open Video")exit()while True:ret, frame = cap.read()if not ret:break# # 在这里对每一帧进行处理# cv2.imshow('Frame', frame)if cv2.waitKey(25) & OxFF == ord('q'): # 25ms内,有按钮按下,且按下的按钮为qbreakcap.release()
cv2.destroyAllWindows()

函数封装

对其进行一个函数封装,传入一个process函数,其对每个frame进行统一的处理,然后输出一个处理后的视频。

import cv2 
import numpy as np # 用于帧的类型提示 
from typing import Callable, Optional # 用于类型提示def process_video_frames( video_file_path: str, frame_processor: Callable[[np.ndarray], np.ndarray], output_path=Optional[str] = None ) -> None:cap = cv2.VideoCaputer(video_path)if not cap.isOpened():print("Can't open Video")exit()# [[OpenCV-获取视频属性]]frame_width, frame_height, fps = get_video_properties(video_capture: cv2.VideoCapture)video_writer = Noneif output_path:fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 定义视频编码器video_writer = cv2.VideoWriter(output_path, fourcc, fps, (frame_width, frame_height))if not video_writer.isOpened():print("Init Video Writer Failed.Processed Video will not be saved")video_writer = Nonewhile True:ret, frame = cap.read()if not ret:break# # 在这里对使用process函数对每一帧进行进行处理processed_frame = frame_processor(current_frame)# 如果输出视频写入器已成功初始化,则写入处理后的帧if video_writer:# 确保处理后的帧尺寸与原始视频一致,否则可能无法写入if processed_frame.shape[:2] != (frame_height, frame_width):print(f"警告: 处理后的帧尺寸 {processed_frame.shape[:2]} 与原始视频尺寸 "f"{(frame_height, frame_width)} 不匹配。可能导致写入问题。")video_writer.write(processed_frame)	cap.release()if video_writer:video_writer.release()cv2.destroyAllWindows()
http://www.dtcms.com/a/332116.html

相关文章:

  • GoLand深度解析:智能开发利器与cpolar内网穿透方案的协同实践
  • 0814 TCP通信协议
  • 一款开源的远程桌面软件,旨在为用户提供流畅的游戏体验,支持 2K 分辨率、60 FPS,延迟仅为 40ms。
  • 数据库访问模式详解
  • [TryHackMe](知识学习)---基于堆栈得到缓冲区溢出
  • opencv基础学习与实战(2)
  • Linux中的日志管理
  • 学习嵌入式第二十八天
  • 中山清华:基于大模型的具身智能系统综述
  • app-4 日志上传
  • 从0到1:C++ 语法之引用
  • qt项目中解决关闭弹窗后执行主界面的信号槽时闪退问题
  • 基于wireshark的USB 全速硬件抓包工具USB Sniffer Lite的使用
  • 多线程安全和性能测试
  • 珠海社保缴费记录如何打印
  • MyBatis Interceptor 深度解析与应用实践
  • CTFShow PWN入门---Kernel PWN 356-360 [持续更新]
  • 【嵌入式汇编基础】-ARM架构基础(五)
  • c/c++实现 TCP Socket网络通信
  • Docker存储卷备份策略于VPS服务器环境的实施标准与恢复测试
  • Linux 进程与内存布局详解
  • RecyclerView 拖拽与滑动操作
  • HQA-Attack: Toward High Quality Black-Box Hard-Label Adversarial Attack on Text
  • 多列集合---Map
  • 【无标题】设计文档
  • Cache的基本原理和缓存一致性
  • 基于大语言模型的爬虫数据清洗与结构化
  • 可信搜索中的多重签名
  • 系统日常巡检脚本
  • 将mysql数据库表结构导出成DBML格式