我使用的是IP摄像机,需要知道捕获何时失败。根据OpenCV文档,VideoCapture::read(OutputArray图像)应在未捕获任何帧(相机已断开连接,或视频文件中没有更多帧)时返回false,但这种情况并未发生。当我的相机断开连接时,我的代码卡在了读取功能中。我需要知道捕获失败的时间。如何做到这一点?我的代码如下:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
String ptzCam = "rtsp://user:password@ip:port/videoMain";
VideoCapture cap(ptzCam); // open the default camera
if (!cap.isOpened()) {
return -1;
}
namedWindow("capture", 1);
for (;;) {
Mat frame;
if (cap.read(frame)) {
cout << "Capturing... " << endl;
imshow("capture", frame);
}
else {
cout << "Capture is not opened." << endl;
}
if (waitKey(30) >= 0)
break;
}
cap.release();
destroyAllWindows();
}
您应该尝试以下代码:
cv::VideoCapture cap;
cv::Mat frm;
cap.open(0);
if (!cap.isOpened())
// error handling
while (true) {
if (!cap.grab() || !cap.retrieve(frm) || frm.empty()) {
// error handling
}
// cv::imshow and cv::waitKey or any other frm manipulations
}
您可以在此处了解cv::VideoCapture成员函数:cv::Video Capture::grab(),cv::VideoCapture::retrieve()
我自己目前正在玩OpenCV,我正试图弄清楚如何处理断开USB摄像头的连接,然后再重新连接。当我拔下USB后使用cap.isOpened()
函数时,我注意到返回值没有任何变化。拔下相机插头后,我还注意到试图读取帧会导致崩溃。这让我无法将相机插回电源并再次播放。但是下面的代码使我可以在不让程序崩溃的情况下断开/重新连接相机。
while (true) { //loop for showing camera footage
if (cap.read(frame)) { //check if there is an frame to read
imshow("something", frame); //show the frame
if (waitKey(1000 / 60) >= 0)
break;
}else{ //if you can't read the frame (because camera is disconnected) enter an loop
while (true) {
VideoCapture newCapture(0); //create an new capture
if (!newCapture.isOpened()) //check if the new capture is open or not
cout << "camera is unavailable" << endl;
else {
cout << "camera seems available" << endl;
cap = newCapture; //if the new capture is open set it as the origional capture
break; //break from the loop
}
}
}
}