OpenCV Python 版使用教程(三)摄像头读取延迟解决方法

文章目录


一、上篇回顾

在上一篇中,简单介绍了如何使用 OpenCV 操作摄像头,本期来讲在摄像头读取时,可能会出现画面延迟的解决方法。

二、产生原因

OpenCV 在读取的时候,会将视频流放在缓冲区中,然后每次调用的时候,会从缓冲区内读取视频帧。虽然说大多数情况难以出现写入缓冲区远大于读取缓冲区的速度,但是当设备出现性能瓶颈,尤其是在 树莓派 等嵌入式设备中,容易出现CPU 瓶颈,从而引发问题。

三、解决方法

1. cap.grab() 方法

cpp 复制代码
virtual bool cv::VideoCapture::grab()

官网对于这个函数的描述如下:

复制代码
The primary use of the function is in multi-camera environments, especially when the cameras do not have hardware synchronization. 
That is, you call VideoCapture::grab() for each camera and after that call the slower method VideoCapture::retrieve()
to decode and get frame from each camera. This way the overhead on demosaicing or motion jpeg
decompression etc. is eliminated and the retrieved frames from different cameras will be closer in time. 

从官网的描述来看,这个函数主要用在多个摄像机中,用于摄像头硬件同步,这个函数和 cap.retrieve() 配合使用。当然也可以使用 cap.read() 再次读取。

同时也可以进一步设置缓冲区的大小,代码如下:

python 复制代码
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)

在这里设置 Capture 的缓冲区大小为 1 帧。

2. 多线程法

python3 复制代码
import cv2
import threading

class VideoCaptureThread:
    def __init__(self, index=0):
        self.cap = cv2.VideoCapture(index)
        self.frame = None
        self.running = True
        self.lock = threading.Lock()
        self.thread = threading.Thread(target=self.update)
        self.thread.start()

    def update(self):
        while self.running:
            ret, frame = self.cap.read()
            if ret:
                with self.lock:  # 确保线程安全
                    self.frame = frame

    def read(self):
        with self.lock:  # 确保线程安全
            return self.frame

    def stop(self):
        self.running = False
        self.thread.join()
        self.cap.release()


# 使用示例
video_capture = VideoCaptureThread()

while True:
    frame = video_capture.read()
    if frame is not None:
        cv2.imshow('Frame', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.stop()
cv2.destroyAllWindows()

在本例中,读取视频帧放在了一个单独的线程,读取和处理分别单独运行,从而避免了两者速度不一致导致的读取延迟。


总结

本篇介绍了两种解决摄像头延迟的方法。在读取到图像后,接下来要做的就是图像处理了,下期将介绍图像的各种色彩空间。

相关推荐
秦先生在广东6 小时前
Block Buzz:用 Nostr 协议把 AI Agent 变成真正的队友,而非自动化幽灵
人工智能
观测云6 小时前
观测云基于 AI Agent Teams 能力的场景实践
人工智能
小程故事多_806 小时前
算力工厂与安全沙箱,企业AI规模化落地的两条核心生命线
人工智能·安全
吨吨ai6 小时前
2026年7月更新:ChatGPT、Codex、Pro、Plus 背后的 AI Determinism 问题(GPT-5.6 工程化技术分享)
人工智能·gpt·chatgpt
空中湖6 小时前
Spring AI 多模态实战:让 AI 看图、听声音、生成图片
人工智能·spring·语音识别
在水一缸6 小时前
苹果AI国行版过审背后的技术架构深度解析:端侧模型与私有云计算的融合实践
人工智能·架构·云计算·技术架构·苹果ai·端侧模型·私有云计算
乔氪智造6 小时前
我给 Agent 写的循环,一半是护栏
人工智能
武子康6 小时前
Shippy 全拆:3 个集合收缩(动作 / 状态 / 后果)+ 4 类边界(版本化行为 / Typed API / CLI / Sandbox)
人工智能·agent·aiops
QXWZ_IA6 小时前
桥梁数字孪生怎么落地?
人工智能·科技·算法·智能硬件·政务
ShirleyWang0126 小时前
让headlamp控制台能访问
linux·服务器·python·k8s·k3s