在我的项目中,我使用opencv来捕获网络摄像头中的帧并通过某些功能检测其中的一些内容。问题在于,在确定函数中并不需要捕获所有帧,例如,每隔0.5秒取一帧就足够了,如果时间尚未完成,则循环继续到下一个函数。代码中的想法是:
while(true){
//read(frame)
//cvtColor(....)
// and other things
time = 0;// start time
if (time == 0.5){
determinatefunction(frame, ...)
}else {
continue;
}
//some others functions
}
我尝试使用chrono库执行类似于上面的操作:
// steady_clock example
#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>
using namespace std;
void foo(){
cout << "printing out 1000 stars...\n";
for (int i=0; i<1000; ++i) cout << "*";
cout << endl;
}
int main ()
{
using namespace std::chrono;
steady_clock::time_point t1 = steady_clock::now();
int i = 0;
while(i <= 100){
cout << "Principio del bucle" << endl;
steady_clock::time_point t2 = steady_clock::now();
duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
cout << time_span.count() << endl;
if (time_span.count() == 0.1){
foo();
steady_clock::time_point t1 = steady_clock::now();
}else {
continue;
}
cout << "fin del bucle" << endl;
i++;
}
}
但循环永远不会结束,永远不会启动foo()函数。
我不能使用posix线程(我看到函数sleep_for),因为我使用g ++(x86_64-win32-sjlj-rev4,由MinGW-W64项目构建)4.9.2并且它与opencv 2.4.9一起使用。我尝试使用opencv实现mingw posix,但它给了我错误,当'VideoCapture' was not declared in this scope VideoCapture cap(0)
正确写入包含和库时没有意义。
我正在使用Windows 7。
将==
与浮点计算结合使用大部分时间都是错误的。
当差异正好是duration_cast<duration<double>>(t2 - t1)
时,无法保证执行0.1
。
相反,它可能像0.099324
和下一次迭代0.1000121
使用>=
而在t1
中定义另一个if
没有多大意义。
if (time_span.count() >= 0.1) {
foo();
t1 = steady_clock::now();
}