【机器视觉 视频截帧算法】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()
相关推荐
木井巳5 小时前
【递归算法】二叉搜索树中第K小的元素
java·算法·leetcode·深度优先·剪枝
铉铉这波能秀5 小时前
LeetCode Hot100 中 enumerate 函数的妙用(2026.2月版)
数据结构·python·算法·leetcode·职场和发展·开发
墨有6665 小时前
哈希表从入门到实现,一篇吃透!
数据结构·算法·哈希算法
南极星10055 小时前
我的创作纪念日--128天
java·python·opencv·职场和发展
三十_A5 小时前
零基础通过 Vue 3 实现前端视频录制 —— 从原理到实战
前端·vue.js·音视频
We་ct5 小时前
LeetCode 228. 汇总区间:解题思路+代码详解
前端·算法·leetcode·typescript
AIpanda8885 小时前
如何借助AI销冠系统提升数字员工在销售中的成效?
算法
啊阿狸不会拉杆5 小时前
《机器学习导论》第 7 章-聚类
数据结构·人工智能·python·算法·机器学习·数据挖掘·聚类
木非哲6 小时前
机器学习--从“三个臭皮匠”到 XGBoost:揭秘 Boosting 算法的“填坑”艺术
算法·机器学习·boosting
小辉同志6 小时前
437. 路径总和 III
算法·深度优先·广度优先