我将 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,但是异常抛出在
最佳答案
检查 read
的返回值(无论如何你都应该这样做)。来自doc :
The method/function combines VideoCapture::grab() and VideoCapture::retrieve() in one call. This is the most convenient method for reading video files or capturing data from decode and returns the just grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the method returns false and the function returns empty image (with cv::Mat, test it with 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;
}
...
}
关于C++ OpenCV 做人脸识别,直到相机被移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53337787/