【机器视觉 视频截帧算法】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()
相关推荐
We་ct2 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·javascript·算法·leetcode·typescript
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【哈夫曼贪心】:合并果子
c++·算法·贪心·csp·信奥赛·哈夫曼贪心·合并果子
叼烟扛炮7 小时前
C++第二讲:类和对象(上)
数据结构·c++·算法·类和对象·struct·实例化
天疆说7 小时前
【哈密顿力学】深入解读航天器交会最优控制中的Hamilton函数
人工智能·算法·机器学习
wuweijianlove8 小时前
关于算法设计中的代价函数优化与约束求解的技术7
算法
leoufung8 小时前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了8 小时前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
HXDGCL9 小时前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化
谭欣辰9 小时前
C++ 排列组合完整指南
开发语言·c++·算法
代码中介商9 小时前
银行管理系统的业务血肉 —— 流程、状态机、输入校验与持久化(下篇)
c语言·算法