在 OpenCV 中——当使用 USB 网络摄像头初始化 VideoCapture
对象时——每运行 2 或 3 次,摄像头将无法初始化。我有一段非常丑陋的代码来解决这个问题,但也许有人知道什么会导致相机初始化失败以及我该如何防止它?
// Initialize video capture
camera_ = cv::VideoCapture(1);
camera_.set(CV_CAP_PROP_CONVERT_RGB , false);
camera_ >> frame_full_;
while (frame_full_.empty()){ // Could be !cap.isOpened
cerr << "Camera failure." << endl;
camera_.release();
camera_ = cv::VideoCapture(1);
camera_.set(CV_CAP_PROP_CONVERT_RGB , false);
camera_ >> frame_full_;
}
/// Do something with the camera feed.
当我关闭我的程序时,我确实在控制台中看到 Cleaned up camera.
,所以我认为它已正确发布。
补充信息:在相机无法初始化的运行中,对 >>>
/.read()
的调用确实需要很想回来。
编辑:按照@4nonymou5 的建议,使用>>
运算符和.read()
之间没有区别。
最佳答案
如果您的意思是,您需要从相机输出视频并希望对各个帧进行一些处理,以下代码可能会对您有所帮助。
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std
int main(int argc, char *argv[])
{
VideoCapture cap(1);
if ( !cap.isOpened() ) // if not success, exit program
{
cout << "Cannot access camera" << endl;
return -1;
}
namedWindow("cam",1);
while(true)
{
Mat frame;
bool check = cap.read(frame); // read a new frame from video
if (!check) //if not success, break loop
{
cout << "Cannot read the frame from video file" << endl;
break;
}
// do what ever processing you want to do on frame
imShow("cam", frame);
waitKey(33);
}
return 0;
}
为了让您的代码响应, 添加
camera_.read(frame_full_);
就在 while 循环之前,它会起作用。
关于c++ - OpenCV 相机初始化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21676995/