【机器视觉 视频截帧算法】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()
相关推荐
君义_noip22 分钟前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
摸个小yu31 分钟前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
汀、人工智能37 分钟前
[特殊字符] 第93课:太平洋大西洋水流问题
数据结构·算法·数据库架构·图论·bfs·太平洋大西洋水流问题
ZPC82101 小时前
rviz2 仿真控制器与真实机器人切换
人工智能·算法·机器人
澈2071 小时前
双指针,数组去重
c++·算法
小辉同志1 小时前
207. 课程表
c++·算法·力扣·图论
CheerWWW1 小时前
深入理解计算机系统——位运算、树状数组
笔记·学习·算法·计算机系统
锅挤2 小时前
数据结构复习(第一章):绪论
数据结构·算法
skywalker_112 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
汀、人工智能2 小时前
[特殊字符] 第95课:冗余连接
数据结构·算法·链表·数据库架构··冗余连接