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()

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


总结

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

相关推荐
لا معنى له3 小时前
目标检测的内涵、发展和经典模型--学习笔记
人工智能·笔记·深度学习·学习·目标检测·机器学习
AKAMAI5 小时前
Akamai Cloud客户案例 | CloudMinister借助Akamai实现多云转型
人工智能·云计算
Robot侠6 小时前
极简LLM入门指南4
大数据·python·llm·prompt·提示工程
小a杰.6 小时前
Flutter 与 AI 深度集成指南:从基础实现到高级应用
人工智能·flutter
colorknight7 小时前
数据编织-异构数据存储的自动化治理
数据仓库·人工智能·数据治理·数据湖·数据科学·数据编织·自动化治理
Lun3866buzha7 小时前
篮球场景目标检测与定位_YOLO11-RFPN实现详解
人工智能·目标检测·计算机视觉
janefir7 小时前
LangChain框架下DirectoryLoader使用报错zipfile.BadZipFile
人工智能·langchain
等....7 小时前
Miniconda使用
开发语言·python
Java&Develop7 小时前
Aes加密 GCM java
java·开发语言·python
齐齐大魔王7 小时前
COCO 数据集
人工智能·机器学习