这可能是一个愚蠢的问题,但我真的无法弄清楚。
首先:抱歉标题含糊不清,我不太确定如何用几句话来描述我的问题。
我在 MS Visual Studio、C++ 中使用 OpenCV 2.4.3。我正在使用 VideoCapture 接口(interface)从我的笔记本电脑网络摄像头捕获帧。
我的程序应该做的是:
循环用户的不同姿势,对于每个姿势:
这是代码:
int main() {
Mat img, face_img, img_start;
Rect *face;
VideoCapture cam(0);
ofstream fout("dataset/dataset.txt");
if(!fout) {
cout<<"Cannot open dataset file! Aborting"<<endl;
return 1;
}
int count = 0; // Number of the (last + 1) image in the dataset
// Orientations are: 0°, +/- 30°, +/- 60°, +/-90°
// Distances are just two, for now
// So it is 7x2 images
cam.read(img_start);
IplImage image = img_start;
face = face_detector(image);
if(!face) {
cout<<"No face detected..? Aborting."<<endl;
return 2;
}
// Double ROI dimensions
face->x = face->x-face->width / 2;
face->y = face->y-face->height / 2;
face->width *= 2;
face->height *=2;
for(unsigned i=0;i<14;++i) {
// Wait for the user to get in position
getchar();
// Get the face ROI
cam.read(img);
face_img = Mat(img, *face);
// Save it
stringstream sstm;
string fname;
sstm << "dataset/image" << (count+i) << ".jpeg";
fname = sstm.str();
imwrite(fname,face_img);
//do some other things..
我对它的期望:
它能做什么:
起初,我在每个 cam.capture() 中都使用了 img,然后我在 cam.capture(img_start) 中更改了第一个,但这并没有帮助。
我的代码的第二次迭代保存了应该在第一次保存的图像,第三次迭代保存应该在第二次保存的图像,依此类推。
我可能错过了 VideoCapture 中的一些重要内容,但我真的想不通,所以我来了。
感谢您的帮助,我真的很感激。
最佳答案
您的实现的问题是相机不能自由运行并实时捕获图像。当您启动相机时,视频捕捉缓冲区会在等待您读取帧时被填满。一旦缓冲区已满,它不会为新帧丢弃旧帧,直到您读取并释放其中的空间。
除了您的“进程”线程之外,解决方案是有一个单独的捕获线程。每当有新帧进入时,捕获线程都会从缓冲区中读取帧,并将其存储在“最近帧”图像对象中。当进程线程需要最近的帧时(即当您按 Enter 时),它会锁定一个互斥体以确保线程安全,将最近的帧复制到另一个对象并释放互斥体,以便捕获线程继续读取新帧。
关于OpenCV VideoCapture 读取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17411490/