您的位置:首页 > 移动开发 > Android开发

opencv在android预览上实现人脸识别(4)

2015-01-25 11:08 330 查看


简介

  现在,继续进行opencv的学习ing。本章中,学习使用opencv提供的库来实现人脸识别的功能。


实现步骤


函数介绍

  这里是使用的opencv库实现,主要用到两个方面:
1、opencv函数:detectMultiScale
2、haarcascade_frontalface_alt.xml
  函数detectMultiScale在opencv官网上有详细资料讲解。
  haarcascade_frontalface_alt.xml在从opencv里面下载的压缩包里可以找到,路径为:opencv-2.4.9\opencv-2.4.9\data\haarcascades


代码实现

  代码的实现,也是在之前讲到的opencv在android上预览的那版最小代码上,用jni来实现的。这里只贴出jni中的代码,java的代码,都一样的。

#include <PreviceGray.h>
#include <opencv2/core/core.hpp>
#include <opencv2/core/mat.hpp>
#include <opencv/cv.h>
#include <string>
#include <vector>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <android/log.h>

using namespace cv;
using namespace std;

void detectAndDisplay(Mat *frame);

String face_cascade_name = "/sdcard/haarcascade_frontalface_alt.xml";
CascadeClassifier face_cascade;
#define LOG_TAG "show infomation"

void detectAndDisplay(Mat *frame)
{
std::vector<Rect> faces;
Mat frame_gray;

cvtColor( *frame, frame_gray, COLOR_BGR2GRAY );
equalizeHist( frame_gray, frame_gray );

face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CASCADE_SCALE_IMAGE, Size(30, 30) );
for ( size_t i = 0; i < faces.size(); i++ )
{
Point center( faces[i].x + faces[i].width/2, faces[i].y + faces[i].height/2 );
ellipse(*frame, center, Size( faces[i].width/2, faces[i].height/2 ), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );
}
}

JNIEXPORT void Java_com_example_camera_1opencv_1android_PreviceGray_grayProc(JNIEnv* env, jclass obj, jlong imageGray)
{
int i;

Mat mat = Mat(*((Mat*)imageGray));

if(!face_cascade.load(face_cascade_name)){
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG,"--(!)Error loading face cascade");
}
detectAndDisplay(&mat);
}


  注意,在代码实现中,一定要先将haarcascade_frontalface_alt.xml复制到设备对应的/sdcard/haarcascade_frontalface_alt.xml,同时加入SD的读写操作权限。
  在代码中,首先是face_cascade.load来加载haarcascade_frontalface_alt.xml,接着使用cvtColor将图像变成灰阶图像。
再然后equalizeHist来做直方图均衡化,直方图均衡化,可以将比较淡的图像变换为比较深的图像(即增强图像的亮度及对比度),
之后,使用face_cascade.detectMultiScale来判断获取图像中人脸信息的坐标。
最后在人脸中间坐标处画,根据脸部大小画一个圆作为标记。最后在预览图像中,就会有一个圆圈中识别到的人脸信息。

参考代码:http://download.csdn.net/detail/u011630458/8403763
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐