人脸检测 libfacedetection-cnn win10-vs2017实现
1 代码下载
于仕琪老师的公开代码地址
链接: link.
2 建立新的控制台程序
3 添加现有项
将下载的代码解压缩,在src中的四个(如图)复制到工程中libfacedetect文件夹下,并添加至工程。
在工程中新建 .cpp ,然后将example中的detect-image.cpp(修改如下)复制到新建cpp文件
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include "facedetectcnn.h"
//define the buffer size. Do not change the size!
#define DETECT_BUFFER_SIZE 0x20000
using namespace cv;
int main()
{
string str = "H:/人脸识别/DataSets/AR-full-bmp/man/002/22.bmp";
Mat image = imread(str);
if(!image.empty())
{
int * pResults = NULL;
//pBuffer is used in the detection functions.
//If you call functions in multiple threads, please create one buffer for each thread!
unsigned char * pBuffer = (unsigned char *)malloc(DETECT_BUFFER_SIZE);
if(!pBuffer)
{
fprintf(stderr, "Can not alloc buffer.\n");
//return -1;
}
///
// CNN face detection
// Best detection rate
//
//!!! The input image must be a BGR one (three-channel) instead of RGB
//!!! DO NOT RELEASE pResults !!!
TickMeter cvtm;
cvtm.start();
pResults = facedetect_cnn(pBuffer, (unsigned char*)(image.ptr(0)), image.cols, image.rows, (int)image.step);
cvtm.stop();
printf("time = %gms\n", cvtm.getTimeMilli());
Mat result_image = image.clone();
//print the detection results
for(int i = 0; i < (pResults ? *pResults : 0); i++)
{
short * p = ((short*)(pResults+1))+142*i;
int confidence = p[0];
int x = p[1];
int y = p[2];
int w = p[3];
int h = p[4];
//show the score of the face. Its range is [0-100]
char sScore[256];
snprintf(sScore, 256, "%d", confidence);
cv::putText(result_image, sScore, cv::Point(x, y-3), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 255, 0), 1);
//draw face rectangle
rectangle(result_image, Rect(x, y, w, h), Scalar(0, 255, 0), 2);
//draw five face landmarks in different colors
cv::circle(result_image, cv::Point(p[5], p[5 + 1]), 1, cv::Scalar(255, 0, 0), 2);
cv::circle(result_image, cv::Point(p[5 + 2], p[5 + 3]), 1, cv::Scalar(0, 0, 255), 2);
cv::circle(result_image, cv::Point(p[5 + 4], p[5 + 5]), 1, cv::Scalar(0, 255, 0), 2);
cv::circle(result_image, cv::Point(p[5 + 6], p[5 + 7]), 1, cv::Scalar(255, 0, 255), 2);
cv::circle(result_image, cv::Point(p[5 + 8], p[5 + 9]), 1, cv::Scalar(0, 255, 255), 2);
//print the result
printf("face %d: confidence=%d, [%d, %d, %d, %d] (%d,%d) (%d,%d) (%d,%d) (%d,%d) (%d,%d)\n",
i, confidence, x, y, w, h,
p[5], p[6], p[7], p[8], p[9], p[10], p[11], p[12], p[13],p[14]);
}
imshow("result", result_image);
waitKey();
//release the buffer
free(pBuffer);
}
return 0;
}
4 opencv配置
include lib,配置好。
5 报错修改
1)注释掉 //include “facedetection_export.h”
2)注释掉 //FACEDETECTION_EXPORT
6 运行成功
检测召回率很高,对光照、遮挡人脸图像都很鲁棒,只是有误检,可根据置信度设置阈值取舍。