【机器视觉 视频截帧算法】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()
相关推荐
我家大宝最可爱4 小时前
强化学习基础-拒绝采样
人工智能·算法·机器学习
YuTaoShao5 小时前
【LeetCode 每日一题】面试题 17.12. BiNode
算法·leetcode·深度优先
刘大猫.5 小时前
XNMS项目-拓扑图展示
java·人工智能·算法·拓扑·拓扑图·节点树·xnms
夏鹏今天学习了吗7 小时前
【LeetCode热题100(95/100)】寻找重复数
算法·leetcode·职场和发展
TTGGGFF10 小时前
控制系统建模仿真(四):线性控制系统的数学模型
人工智能·算法
晚风吹长发10 小时前
初步了解Linux中的命名管道及简单应用和简单日志
linux·运维·服务器·开发语言·数据结构·c++·算法
Σίσυφος190011 小时前
Halcon中霍夫直线案例
算法
Anastasiozzzz11 小时前
leetcode力扣hot100困难题--4.俩个正序数列的中位数
java·算法·leetcode·面试·职场和发展
BHXDML12 小时前
第六章:推荐算法
算法·机器学习·推荐算法