Python,OpenCV:在网络摄像头上检测到对象的持续时间



我能够跟踪网络摄像头返回的每一帧中的对象。 我想记下第一次检测到该对象的时间以及此后连续检测到该对象的持续时间。 网络摄像头无限期打开,即直到用户输入关闭。

由于用于检测对象的代码集位于从 CV2 读取下一帧所需的 while 循环中。VideoCapture() 我无法想出一种有效的、pythonic 的方式来做我想做的事情。

现在,我正在附加一个列表,其中包含每个帧的元组(timestamp,flag)timestamp是 python time.time()的值,flag是一个布尔值,用于指示是否检测到对象。然后,我总结了标志为"是"的时间戳的所有值。但这并没有完全满足我的需求。你能建议一个更合适的方法吗?

*我希望OpenCV中有一个通用函数,如cv2.detectionDuration() :P

--编辑--

这是跟踪正面面部的代码:

import cv2
import time
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
capture = cv2.VideoCapture(0)
keyPressed = -1
faceFound = []
print 'press esc to quit'
while(keyPressed != 27):
    ret, camImage = capture.read()
    cv2.imshow('camImage', camImage)
    try:
        faceRegion = faceCascade.detectMultiScale(camImage)
        timestamp = time.time()
        flag = 1
        faceFound.append((timestamp,flag)) 
    except TypeError:
        timestamp = time.time()
        flag = 0
        faceFound.append((timestamp,flag))
        print 'check if front face is visible to camera'
        pass
    keyPressed = cv2.waitKey(1)
cv2.destroyAllWindows()
timeDelta = 0
for tup in faceFound:
    if tup[1] == 1:
        timeDelta += tup[0]
print timeDelta

另外,您能否帮助我获得更好的 timeDelta 格式,以便它可以显示为day:hour:min:sec:microsec . 对于我当前的需求,有没有更好的替代 time.time() 的方法?

[time_first, time_last, got_first] 

如果got_first为假且检测到人脸,则将time_first分配给now()got_first分配给真。

如果未检测到人脸,则将time_last分配给now()got_first分配给 false。

import cv2
import time
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
capture = cv2.VideoCapture(0)
keyPressed = -1
faceFound = []
ts = [0,0,False]
print 'press esc to quit'
while(keyPressed != 27):
    ret, camImage = capture.read()
    cv2.imshow('camImage', camImage)
    try:
        faceRegion = faceCascade.detectMultiScale(camImage)
        if ts[2] == False:
            ts[0] = time.time()
            ts[2] = True
    except TypeError:
        if ts[2] == True:
            ts[1] = time.time()
            ts[2] = False
            faceFound.append([ts[0], ts[1]])
        print 'check if front face is visible to camera'
        pass
    keyPressed = cv2.waitKey(1)
cv2.destroyAllWindows()
for list in faceFound:
    print list[1] - list[0]

虽然我认为你的代码有问题,但因为没有检测到人脸。你可以打印faceRegion,看到它是一个空元组。

您尝试执行的操作称为停留时间,在该时间中,我们计算帧内检测到的物体的时间。为了实现这一点,你需要在推理内部进行某种跟踪。基本上,跟踪器会为您检测到的对象分配一个对象 ID,然后该对象 ID 保持不变,直到检测到该对象。根据该对象 ID,您可以启动计时器并继续计数,直到检测到对象。在opencv中,你可以使用质心跟踪算法

看看这个视频,这可能会给你一个基本的想法:https://www.youtube.com/watch?v=JbNeFMKXybw&list=PLWw98q-Xe7iH8UHARl8RGk8MRj1raY4Eh&index=7

最新更新