当捕获不起作用时,OpenCV C ++不会返回false

时间:2016-07-27 14:25:23

标签: c++ c image opencv image-processing

我正在使用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();
}

2 个答案:

答案 0 :(得分:1)

您应尝试以下代码:

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::VideoCapture::grab()cv::VideoCapture::retrieve()

答案 1 :(得分:1)

我目前正在自己​​与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
            }
        }
    }
}