【问题标题】:C++ OpenCV do face recognition until camera is removedC++ OpenCV 进行人脸识别,直到相机被移除
【发布时间】:2018-11-16 12:19:19
【问题描述】:

我正在使用 OpenCV 进行一些带有网络摄像头的人脸识别。问题是,只要没有安装摄像头,我就会遇到异常。我一开始就用这段代码处理了这个问题:

if (!realTime.isOpened())
{
    cout << "No webcam installed!" << endl;

    system("pause");
    return 0;
}

realTime 是 VideoCapture 的一个对象。因此,当我想在没有插入网络摄像头的情况下启动程序时,我会在控制台中看到“未安装网络摄像头”。 但是现在我希望程序在网络摄像头被关闭时立即停止。这似乎真的很难,因为我的人脸识别是在一个while循环中:

namedWindow("Face Detection", WINDOW_KEEPRATIO);

string trained_classifier_location = "C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml";

CascadeClassifier faceDetector;

faceDetector.load(trained_classifier_location);

vector<Rect> faces;

while (true)
{
    realTime.read(videoStream);


    faceDetector.detectMultiScale(videoStream, faces, 1.1, 4, CASCADE_SCALE_IMAGE, Size(20, 20));



    for (int i = 0; i < faces.size(); i++)
    {

        Mat faceROI = videoStream(faces[i]);

        int x = faces[i].x;
        int y = faces[i].y;
        int h = y + faces[i].height;
        int w = x + faces[i].width;
        rectangle(videoStream, Point(x, y), Point(w, h), Scalar(255, 0, 255), 2, 8, 0);
    }

    imshow("Face Detection", videoStream);

    if (waitKey(10) == 27)
    {
        break;
    }
}

我也用try-catch-statement尝试过,但是在

处抛出异常

【问题讨论】:

  • "但是现在我希望程序在网络摄像头关闭时立即停止。" 如果 OpenCV 抛出异常,未处理的异常将立即停止您的程序。
  • 但是程序崩溃了,当我构建并执行它时,它告诉我 FaceRecog.exe 不再工作了。我想防止这种情况发生
  • 为什么不捕捉异常?

标签: c++ opencv


【解决方案1】:

检查read 的返回值(无论如何你都应该这样做)。来自doc

该方法/函数在一次调用中结合了 VideoCapture::grab() 和 VideoCapture::retrieve()。这是读取视频文件或从解码中捕获数据并返回刚刚抓取的帧的最方便的方法。 如果没有抓到帧(相机已经断开,或者视频文件中没有更多帧),该方法返回false,函数返回空图像(使用cv::Mat,用Mat::empty())。

所以:

bool valid_frame = false;
while (true)
{
    valid_frame = realTime.read(videoStream);
    if(!valid_frame) 
    { 
        std::cout << "camera disconnected, or no more frames in video file";
        break;
    }
    ...
}

【讨论】:

    猜你喜欢
    • 2014-01-20
    • 2011-08-01
    • 2021-03-01
    • 2012-06-15
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 2015-07-05
    相关资源
    最近更新 更多