opencv-python读取相机视频最新帧

本文介绍了一种使用Opencv-Python进行实时视频处理的方法,通过创建一个自定义的VideoCapture类,确保每次都能读取到最新的帧,避免了由于处理速率跟不上相机读取速率而导致的帧积压问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

opencv-python的默认读取相机视频方式是一帧一帧读入采集的图像,如果处理速率跟不上相机读取速率,就会发现opencv-python处理的不是当前帧,而是之前积压的帧
所以需要每次读取最新帧。

参考大神的解决方案

import cv2, Queue, threading, time

# bufferless VideoCapture
class VideoCapture:

  def __init__(self, name):
    self.cap = cv2.VideoCapture(name)
    self.q = Queue.Queue()
    t = threading.Thread(target=self._reader)
    t.daemon = True
    t.start()

  # read frames as soon as they are available, keeping only most recent one
  def _reader(self):
    while True:
      ret, frame = self.cap.read()
      if not ret:
        break
      if not self.q.empty():
        try:
          self.q.get_nowait()   # discard previous (unprocessed) frame
        except Queue.Empty:
          pass
      self.q.put(frame)

  def read(self):
    return self.q.get()

cap = VideoCapture(0)
while True:
  time.sleep(.5)   # simulate time between events
  frame = cap.read()
  cv2.imshow("frame", frame)
  if chr(cv2.waitKey(1)&255) == 'q':
    break
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值