OpenCV Cascade Classifier load error iOS

2019-09-18 07:03发布

Currently I am trying to using an OpenCV Cascade Classifier to detect faces in my iOS app. The problem is that when I go to load the classifier, it fails because the pathname to the "haarcascade_frontalface_alt.xml" isn't correct.

Here is my code:

cv::String face_cascade_name = "haarcascade_frontalface_alt.xml";

void detectFaces(cv::Mat frame){

cv::CascadeClassifier face_cascade;
if (face_cascade.load(face_cascade_name)){
    printf("Load complete");
}else{
    printf("Load error");
}
std::vector<cv::Rect> faces;

std::vector<cv::Mat> rgbChannels(3);
cv::split(frame, rgbChannels); // Making the frame gray scale
cv::Mat frame_gray = rgbChannels[2];

face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE|CV_HAAR_FIND_BIGGEST_OBJECT, cv::Size(150,150));

if(faces.size()> 0){
    printf("TRUE");
}

}

Since this is an iOS project I don't know how to find the path of the required xml file in the framework. What is the proper way to load a Cascade Classifier into an iOS project? Or, what is the correct way to include the right filename so that it sees it properly?

Any help would be appreciated.

1条回答
唯我独甜
2楼-- · 2019-09-18 07:29

In iOS, you need to locate the file path within the app bunnle. Something like this:

// get main app bundle
NSBundle * appBundle = [NSBundle mainBundle];

// constant file name
NSString * cascadeName = @"haarcascade_frontalface_alt";
NSString * cascadeType = @"xml";

// get file path in bundle
NSString * cascadePathInBundle = [appBundle pathForResource: cascadeName ofType: cascadeType];

// convert NSString to std::string
std::string cascadePath([cascadePathInBundle UTF8String]);

// load cascade
if (face_cascade.load(cascadePath)){
    printf("Load complete");
}else{
    printf("Load error");
}
查看更多
登录 后发表回答