首页 > 解决方案 > OpenCV haarcascades加载根本不起作用

问题描述

我正在使用带有 OpenCV 4.4.0 的 Visual Studio 2019,一切都很棒,但是当我想开始人脸检测时,级联分类器不会加载 haarcascade

您还必须知道我在 c 分区中安装了 openCV,这是一个简单的代码


#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <opencv2\opencv.hpp>
#include <opencv2/highgui/highgui.hpp>


#include <Windows.h>
#include <vector>
#include <stdio.h>

using namespace std;
using namespace cv;

int main()
{
    
    VideoCapture cam(0);
    Mat img;
    CascadeClassifier detector;
    vector<Rect> faces;
    Point p[2];
    bool cap = false;

    if (!detector.load("c:\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml"))
    {
        cout << "Image Detector Doesn't work\n";
        return EXIT_FAILURE;
    }

    if (!cam.isOpened())
    {
        cout << "Can't Open Camera\n";
        return EXIT_FAILURE;
    }

    while (!cap)
    {
        cam.read(img);
        imshow("Cam", img);
        waitKey(0);
        if (GetAsyncKeyState(VK_ESCAPE))
            cap = true;
    }

    destroyWindow("Cam");

    cout << "Detecting Face...\n";
    detector.detectMultiScale(img, faces);
    
    for (int i = 0; i < faces.size(); i++)
    {
        p[0] = Point(faces[i].x,faces[i].y);
        p[1] = Point(faces[i].x + faces[i].height,faces[i].y + faces[i].width);
        rectangle(img,p[0],p[1],Scalar(0,0,255),3);
    }

    imwrite("Result.jpg",img);

    return EXIT_SUCCESS;
}

此代码不加载 haarcascade 并在 cmd 中返回“无法加载”

所以我真的需要帮助并感谢所有人

标签: c++opencvvisual-studio-2019

解决方案


\在 C++ 字符串文字中用作转义序列。

因此,您应该使用\\将字符\放入其中。

if (!dec.load("c:\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml"))

推荐阅读