OpenCV在release模式下WaitKey函数失效如何解决?

问题

VS 2017+OpenCV
涉及OpenCV,想打开摄像头,对人脸进行一些数据收集。但是在进入while循环内部想要使用键入来退出循环时总会失败。每次只能使用迫使程序中断的方法退出循环。

相关代码

int main() {
    ofstream ofs;
    ofs.open("Open.txt",ios::out|ios::trunc);//测试睁眼
    if (!ofs.is_open()) {
        cout << "cannot openn the file." << endl;
        return 1;
    }
    VideoCapture cap(0);//打开摄像头
    if (!cap.isOpened()) {
        cout << "cannot open the cap." << endl;
        return 1;
    }

    frontal_face_detector detector = get_frontal_face_detector();
    shape_predictor pos_model;
    deserialize("E:/CV/shape_predictor_68_face_landmarks.dat") >> pos_model;

    while(true){
        Mat frame;
        cap >> frame;
        cv_image<bgr_pixel> cimg(frame);//将图像转化为dlib中的BGR格式

        std::vector<dlib::rectangle> faces = detector(cimg);
        std::vector<full_object_detection> shapes;
        for (unsigned int i = 0; i < faces.size(); i++)shapes.push_back(pos_model(cimg, faces[i]));
        
        if (!shapes.empty()) {
            for (int j = 0; j < shapes.size(); j++) {
                for (int i = 0; i < 68; i++) {//用来画特征值的点
                    cv::circle(frame, cvPoint(shapes[j].part(i).x(), shapes[j].part(i).y()), 2, cv::Scalar(219, 22, 0), -1);
                }
            }
            double EAR=GetEAR(shapes);
            ofs << EAR << endl;
        }
        imshow("demo", frame);
        int opt = waitKey(30);
        //if (getWindowProperty("demo", WND_PROP_AUTOSIZE) < 1)break;
        if (opt!=-1)break;
    }
    ofs.close();
    return 0;
}
发现的错误

我把部分调用摄像头的程序拿出来单独测试,发现是由于使用的模式是Release导致不能退出循环;在Debug模式下可以正常退出。但是毕竟这个程序会附加很多的文件以及做计算什么的,所以还是得在Relea模式下运行才行,使用Debug真的太慢了!
求问有什么好的解决方案吗?


if (opt!=-1)break;
改为
if (opt==27)break;//按Esc键退出