我正在使用HAAR分类器在openCV中进行面部检测。这是我的代码
#include "stdafx.h"
#include <opencv2\objdetect\objdetect.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv\cv.h>
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
void detectAndDisplay(Mat frame);
String face_cascade_name = "haarcascade_frontalface_alt.xml";
String eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml";
CascadeClassifier face_cascade;
CascadeClassifier eye_cascade;
string window_name = "Capture- Face detection";
int _tmain(int argc, _TCHAR* argv[])
{
Mat frame = imread("C:/Users/Public/Pictures/Sample Pictures/lena.png");
imshow("original picture", frame);
if (face_cascade.load(face_cascade_name))
{
cout << "\n Error loading " << endl;
}
if (eye_cascade.load(eyes_cascade_name))
{
cout << "\n Error Loading " << endl;
}
if (!frame.empty())
{
detectAndDisplay(frame);
}
waitKey(0);
return 0;
}
void detectAndDisplay(Mat frame)
{
vector<Rect>faces;
imshow("lena.png", frame);
Mat frame_gray;
cvtColor(frame, frame_gray, CV_BGR2GRAY);
equalizeHist(frame_gray, frame_gray);
imshow("Gray Color Image", frame_gray);
face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(20, 20));
int k = faces.size();
for (size_t i = 0; i <faces.size(); i++)
{
Point center(faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5);
ellipse(frame, center, Size(faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar(255, 0, 0));
Mat faceROI = frame_gray(faces[i]);
vector<Rect>eyes;
eye_cascade.detectMultiScale(faceROI, eyes, 1.1, 2, 0 | CV_HAAR_SCALE_IMAGE, Size(30, 30));
for (int j = 0; j < eyes.size(); j++)
{
Point center(faces[i].x + eyes[j].x + eyes[j].width*0.5, faces[i].y + eyes[j].y + eyes[j].height*0.5);
int radius = cvRound((eyes[j].width + eyes[j].height)*0.25);
circle(frame, center, radius, Scalar(0, 0,255), 4, 8, 0);
}
}
imshow(window_name, frame);
}
这里我的代码无效。面部未被检测到。 iam尝试get int k = faces.size()得到'0'值。可能是什么错误。
答案 0 :(得分:1)
这是因为加载级联的if条件不是逻辑:
你的是:
if (face_cascade.load(face_cascade_name))
{
cout << "\n Error loading " << endl;
}
if (eye_cascade.load(eyes_cascade_name))
{
cout << "\n Error Loading " << endl;
}
但它应该是:
if (!face_cascade.load(face_cascade_name))
{
cout << "\n Error loading " << endl;
}
if (!eye_cascade.load(eyes_cascade_name))
{
cout << "\n Error Loading " << endl;
}
你忘了'!'在条件。
答案 1 :(得分:0)
face_cascade.load(face_cascade_name)
显然返回FALSE。您可以在随OpenCV库facedetect.cpp
提供的示例中找到它
这就是为什么你没有看到加载过程失败并且你提供了错误的haarcascade文件路径。