我遇到过这种情况,我使用 OpenCV 来检测相机前面的人脸,并对这些人脸进行一些机器学习。我遇到的问题是,一旦我完成所有处理,并去抓取下一帧,我得到的是过去,而不是现在。意思是,我将读取缓冲区内的内容,而不是实际在相机前面的内容。由于我不关心处理时哪些面孔出现在相机前面,所以我关心现在出现在相机前面的内容。
我确实尝试将缓冲区大小设置为1
,这确实有很大帮助,但我仍然会得到至少 3 个缓冲区读取。将 FPS 设置为 1,也并不能帮助 100% 消除这种情况。以下是我的流程。
let cv = require('opencv4nodejs');
let camera = new cv.VideoCapture(camera_port);
camera.set(cv.CAP_PROP_BUFFERSIZE, 1);
camera.set(cv.CAP_PROP_FPS, 2);
camera.set(cv.CAP_PROP_POS_FRAMES , 1);
function loop()
{
//
// <>> Grab one frame from the Camera buffer.
//
let rgb_mat = camera.read();
// Do to gray scale
// Do face detection
// Crop the image
// Do some ML stuff
// Do whats needs to be done after the results are in.
//
// <>> Release data from memory
//
rgb_mat.release();
//
// <>> Restart the loop
//
loop();
}
我的问题是:
是否可以将缓冲区全部删除?如果是这样,又是怎样的。如果没有,则why
将不胜感激。
Whether CAP_PROP_BUFFERSIZE
支持看起来相当特定于操作系统和后端。例如,2.4 docs https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-get声明它“目前仅受 DC1394 [Firewire] v 2.x 后端支持”,并且对于后端 V4L,根据code https://github.com/opencv/opencv/blob/3.4.5/modules/videoio/src/cap_v4l.cpp#L164,仅于 2018 年 3 月 9 日添加支持。
禁用缓冲区的最简单的非脆弱方法是使用单独的线程;有关详细信息,请参阅 Piotr Kurowski 的回答下我的评论。这里的Python代码使用单独的线程来实现无缓冲的VideoCapture:(我没有opencv4nodejs环境。)
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:
frame = cap.read()
time.sleep(.5) # simulate long processing
cv2.imshow("frame", frame)
if chr(cv2.waitKey(1)&255) == 'q':
break
帧读取器线程封装在自定义内部VideoCapture
类,与主线程的通信是通过队列进行的。
This answer https://stackoverflow.com/a/30032945/1628638建议使用cap.grab()
在读者线程中,但文档不保证grab()
清除缓冲区,因此这可能在某些情况下有效,但在其他情况下无效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)