每隔n秒使用Open CV处理图像

时间:2018-05-21 20:09:40

标签: python-3.x opencv image-processing raspberry-pi

我正在使用OpenCV 3.4和Python 3编写程序。我还使用了Raspberry pi 3和PiCamera。 我的问题是我必须每隔2或3秒从picamera实时录制的视频处理最后一帧。

import cv2
from time import sleep
cam=cv2.VideoCapture(0)
while True:
    suc, img=cam.read()
    #operation on image, it's not important
    cv2.imshow(...)

我有类似的代码。 这段代码效果很好,但是Rasberry继续多次处理视频的最后一帧。 我想每2或3秒只处理一次。 我已经在while循环中尝试了time.sleep(2)但是它没有工作,因为那时视频不是实时的。我在互联网上搜索了很多,我认为picamera继续记录,当2秒钟过去时,我的程序处理后的帧而不是相机记录的最后一帧。 在互联网上,我发现了一个名为VideoCapture.Grab的功能,但我不明白它是如何工作的,如果我必须使用它。 我发现了另一个与我非常相似的问题 How to capture a picture after every 5 seconds of camera using opencv python and Raspbery Pi 3? 但代码的第二部分是剪切或类似的,我无法理解。 谢谢大家。

2 个答案:

答案 0 :(得分:0)

这是一个快速简便的解决方案:

在python中,time.time()从1970年1月1日开始以秒为单位获取当前时间。在你的while循环中,如果你只是抓住当前时间并将它与你上次抓取一帧的时间进行比较,那么你可以检查是否已经过了2秒,然后决定像你提到的那样“保持”你的框架。您可以尝试以下代码:

import cv2
import time
cam=cv2.VideoCapture(0)
last_recorded_time = time.time() # this keeps track of the last time a frame was processed
while True:
    curr_time = time.time() # grab the current time

    # keep these three statements outside of the if statement, so we 
    #     can still display the camera/video feed in real time
    suc, img=cam.read()
    #operation on image, it's not important
    cv2.imshow(...)

    if curr_time - last_recorded_time >= 2.0: # it has been at least 2 seconds
        # NOTE: ADD SOME STATEMENTS HERE TO PROCESS YOUR IMAGE VARIABLE, img

        # IMPORTANT CODE BELOW
        last_recorded_time = curr_time

请注意,我添加了4行代码,并将1(from time import sleep更改为import time)。我希望这有帮助!它不会暂停你的程序或完全放慢它。

答案 1 :(得分:0)

您可以使用time.time()手动计算时间。

from time import time
import cv2

# Create a new VideoCapture object
cam = cv2.VideoCapture(0)

# Initialise variables to store current time difference as well as previous time call value
previous = time()
delta = 0

# Keep looping
while True:
    # Get the current time, increase delta and update the previous variable
    current = time()
    delta += current - previous
    previous = current

    # Check if 3 (or some other value) seconds passed
    if delta > 3:
        # Operations on image
        # Reset the time counter
        delta = 0

    # Show the image and keep streaming
    _, img = cam.read()
    cv2.imshow("Frame", img)
    cv2.waitKey(1)