如何在 Python 中始终从 OpenCV VideoCapture 获取最新帧

使用 OpenCV 视频捕获时,但当你只是偶尔使用图像时,你将从捕获缓冲区获取较旧的图像。

此代码示例通过运行单独的捕获线程不断将图像保存到临时缓冲区来解决此问题。

因此,你始终可以从缓冲区获取最新图像。代码基于我们的基本示例如何在 Python 中使用 OpenCV 拍摄网络摄像头照片

opencv_latest_frame.py
video_capture = cv2.VideoCapture(0)

video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
video_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)

if not video_capture.isOpened():
    raise Exception("Could not open video device")

class TakeCameraLatestPictureThread(threading.Thread):
    def __init__(self, camera):
        self.camera = camera
        self.frame = None
        super().__init__()
        # 启动线程
        self.start()

    def run(self):
        while True:
            ret, self.frame = self.camera.read()

latest_picture = TakeCameraLatestPictureThread(video_capture)

使用示例:

opencv_latest_frame_usage.py
# 将最新图像转换为正确的色彩空间
rgb_img = cv2.cvtColor(latest_picture.frame, cv2.COLOR_BGR2RGB)
# 显示
plt.imshow(rgb_img)

Check out similar posts by category: Audio/Video, OpenCV, Python