人脸识别是利用openCV库和所谓的级联器haarcascade_frontalface_alt2.xml来进行识别
识别方法如下:
+ (UIImage*)faceDetectForImage:(UIImage*)image {
// cv::CascadeClassifier faceDetector;
// // 添加xml文件
// NSString* cascadePath = [[NSBundle mainBundle]
// pathForResource:@"haarcascade_frontalface_alt"
// ofType:@"xml"];
// faceDetector.load([cascadePath UTF8String]);
static cv::CascadeClassifier faceDetector;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 添加xml文件
NSString* cascadePath = [[NSBundle mainBundle]
pathForResource:@"haarcascade_frontalface_alt"
ofType:@"xml"];
faceDetector.load([cascadePath UTF8String]);
});
cv::Mat faceImage;
UIImageToMat(image, faceImage);
// 转为灰度
cv::Mat gray;
cvtColor(faceImage, gray, CV_BGR2GRAY);
NSLog(@"%d",faceImage.channels());
// 检测人脸并储存
std::vector<cv::Rect>faces;
faceDetector.detectMultiScale(gray, faces,1.1,2,0,cv::Size(30,30));
// 在每个人脸上画一个红色四方形
for(unsigned int i= 0;i < faces.size();i++)
{
const cv::Rect& face = faces[i];
cv::Point tl(face.x,face.y);
cv::Point br = tl + cv::Point(face.width,face.height);
// 四方形的画法
cv::Scalar magenta = cv::Scalar(255, 0, 0, 255);
cv::rectangle(faceImage, tl, br, magenta, 11, 8, 0);
}
return MatToUIImage(faceImage);
}
详细内容,请read the fucking source code:
https://github.com/Realank/openCV-Practice
封装好的方法在OpenCVUtil类中
网友评论