【机器视觉 视频截帧算法】OpenCV 视频截帧算法教程

引言

在视频处理、分析和计算机视觉任务中,常常需要从视频文件中提取特定的图像帧。这个过程被称为"视频截帧"或"视频抽帧"。OpenCV (Open Source Computer Vision Library) 是一个功能强大且广泛应用的开源计算机视觉库,提供了简洁高效的方法来实现视频截帧。本教程将详细介绍如何使用 Python 结合 OpenCV 库来完成这一任务。
核心原理

视频本质上是由一系列连续的图像帧组成的。每个帧代表视频在某一时刻的画面。OpenCV 通过 cv2.VideoCapture 类来读取视频文件。该类提供了一系列方法,允许我们逐帧读取视频内容。一旦读取到某一帧,我们就可以将其作为一个图像矩阵(NumPy array)进行处理,或者直接使用 cv2.imwrite 将其保存为独立的图像文件(如 JPEG, PNG 等)。

下面给出一个视频截帧例子:

capture_frame_s16.py

python 复制代码
import cv2
import time
import datetime
import os

# RTSP 视频流地址
rtsp_url = "rtsp://admin:password@ip:554/h264/ch1/main/av_stream"

# 指定截取帧的大小
frame_width = 2560
frame_height = 1440

# 重试次数和重试间隔(秒)
retry_count = 60
retry_interval = 5

# 创建一个 VideoCapture 对象
cap = cv2.VideoCapture(rtsp_url)

# 检查视频流是否打开
if not cap.isOpened():
    print("Error: Could not open video stream.")
    exit()

try:
    while True:
        # 读取视频流的一帧
        ret, frame = cap.read()

        # 检查帧是否正确读取
        if not ret:
            print("Error: Could not read frame from video stream. Trying to reconnect...")
            for i in range(retry_count):
                time.sleep(retry_interval)
                cap.release()
                cap = cv2.VideoCapture(rtsp_url)
                ret, frame = cap.read()
                if ret:
                    print("Reconnected to the video stream.")
                    break
            if not ret:
                print("Failed to reconnect to the video stream. Exiting...")
                break

        # 调整帧大小
        frame_resized = cv2.resize(frame, (frame_width, frame_height))

        # 获取当前时间
        current_time = datetime.datetime.now()
        # 判断当前时间,限制在0点-24点截取图片
        if current_time.hour>=0 and current_time.hour<=23:
            # 获取当前日期和小时
            current_date = datetime.datetime.now().strftime("%Y-%m-%d")
            current_hour = datetime.datetime.now().strftime("%H")

            # 创建以日期和小时命名的文件夹
            folder_path ="/root/sinoma_line1/halt_detection_yolov5/images/cam1/"+ f"{current_date}/{current_hour}"
            os.makedirs(folder_path, exist_ok=True)

            # 获取当前时间戳
            current_time = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")

            # 保存帧为图片
            filename = f"{folder_path}/frame_{current_time}.jpg"
            cv2.imwrite(filename, frame_resized)
            print(f"Frame saved: {filename}")
        else:
            print("Current time is outside the 0:00-23:00 range. Skipping frame save.")
        # 等待 60 秒(1 分钟截取 1 张,所以每张之间间隔 60 秒)
        time.sleep(5)
except KeyboardInterrupt:
    # 当按下 Ctrl+C 时退出循环
    pass
except Exception as e:
    # 打印任何其他异常
    print(f"An error occurred: {e}")
finally:
    # 释放 VideoCapture 对象
    cap.release()
相关推荐
wabs6669 分钟前
关于哈希表【力扣15.三数之和的思考】
数据结构·算法·leetcode·散列表·哈希表·三数之和
欧特克_Glodon14 分钟前
OpenCV计算机视觉开发入门与实践<二>:图像噪声与图像处理
c++·图像处理·opencv·计算机视觉
退休倒计时15 分钟前
【每日一题】LeetCode 88. 合并两个有序数组 TypeScript
算法·leetcode·职场和发展·typescript
键盘会跳舞21 分钟前
C++:函数对象与 std::function 源码级深度拆解——泛型算法的策略内核与可调用对象统一封装
c++·算法·仿函数
手写码匠26 分钟前
华为云Flexus+DeepSeek征文|Agent 评测体系实战:用 DeepSeek-R1 当裁判,打造 Dify Agent 的自动化回归测试流水线
人工智能·深度学习·算法·aigc
LONGZETECH37 分钟前
无人机实训高成本痛点解法:虚拟仿真实现 70% 耗材损耗下降
大数据·算法·unity·架构·无人机
不会就选b41 分钟前
算法日常・每日刷题--<队列,宽搜>4
算法
码字的特恩1 小时前
微软确认暂不为 Windows 11 加入透明效果自定义功能,建议用户使用第三方工具
人工智能·windows·算法·microsoft·计算机·大模型·编程
星轨初途1 小时前
LeetCode 热题 100——day10 和为 K 的子数组
开发语言·c++·算法·leetcode
数模竞赛Paid answer1 小时前
2021年深圳杯数学建模C题配电网可靠性和故障软自愈研究解题全过程论文及程序
算法·数学建模·数据分析·深圳杯