(opencv)Android人脸识别

来源:互联网 发布:kali linux arp欺骗 编辑:程序博客网 时间:2024/06/05 07:55

1.下载opencv

2.mainactivity

package com.example.facetest1;import static com.googlecode.javacv.cpp.opencv_contrib.createFisherFaceRecognizer;import static com.googlecode.javacv.cpp.opencv_core.CV_32SC1;import static com.googlecode.javacv.cpp.opencv_highgui.CV_LOAD_IMAGE_GRAYSCALE;import static com.googlecode.javacv.cpp.opencv_highgui.cvLoadImage;import static com.googlecode.javacv.cpp.opencv_imgproc.CV_COMP_CORREL;import static com.googlecode.javacv.cpp.opencv_imgproc.CV_HIST_ARRAY;import static com.googlecode.javacv.cpp.opencv_imgproc.cvCalcHist;import static com.googlecode.javacv.cpp.opencv_imgproc.cvCompareHist;import static com.googlecode.javacv.cpp.opencv_imgproc.cvNormalizeHist;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.lang.reflect.Array;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import org.opencv.android.BaseLoaderCallback;import org.opencv.android.LoaderCallbackInterface;import org.opencv.android.OpenCVLoader;import org.opencv.core.Core;import org.opencv.core.Mat;import org.opencv.core.MatOfRect;import org.opencv.core.Point;import org.opencv.core.Rect;import org.opencv.core.Scalar;import org.opencv.core.Size;import org.opencv.highgui.Highgui;import org.opencv.imgproc.Imgproc;import org.opencv.objdetect.CascadeClassifier;import com.googlecode.javacv.cpp.opencv_contrib.FaceRecognizer;import com.googlecode.javacv.cpp.opencv_core.CvMat;import com.googlecode.javacv.cpp.opencv_core.IplImage;import com.googlecode.javacv.cpp.opencv_core.MatVector;import com.googlecode.javacv.cpp.opencv_imgproc.CvHistogram;import com.googlecode.javacv.cpp.swresample;import com.lee.infos.FaceInfo;import com.lee.infos.Vauleinfo;import com.lee.view.CameraView;import android.R.array;import android.R.integer;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Matrix;import android.hardware.Camera;import android.hardware.Camera.PictureCallback;import android.os.Bundle;import android.os.Environment;import android.app.Activity;import android.util.Log;import android.view.LayoutInflater;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.CalendarView;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {protected CascadeClassifier cascadeClassifier;//private String FACE = "/sdcard/FaceDetect/face.jpg";//private String FACEDONE = "/sdcard/FaceDetect/faceDone.jpg";private List<FaceInfo> faceList = new ArrayList<FaceInfo>();private List<Vauleinfo>valueList = new ArrayList<Vauleinfo>();private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {public void onManagerConnected(int status) {switch (status) {case LoaderCallbackInterface.SUCCESS: {cascadeClassifier = new CascadeClassifier("/sdcard/FaceDetect/haarcascade_frontalface_alt2.xml");}break;default: {super.onManagerConnected(status);}break;}}};PictureCallback pictureCallbackDetect=new PictureCallback() {@Overridepublic void onPictureTaken(byte[] data, Camera camera) {Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);Matrix matrix = new Matrix();// 设置图像的旋转角度matrix.setRotate(cameraView.getAngle());// 旋转图像,并生成新的Bitmap对像bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), matrix, true);File file=new File("/sdcard/faceData/detect/"+System.currentTimeMillis()+".jpg");File fileParent=file.getParentFile();if(!fileParent.exists()){fileParent.mkdirs();}try {if(file.createNewFile()){//FileOutputStream fos=new FileOutputStream(file);//fos.write(data);//fos.flush();//fos.close();writePhoto(bitmap, bitmap.getWidth(), bitmap.getHeight(), file.getAbsolutePath());DetectFace(cascadeClassifier,file.getAbsolutePath(),1);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}};protected String tag="MainActivity";PictureCallback pictureCallbackIdentification=new PictureCallback() {@Overridepublic void onPictureTaken(byte[] data, Camera camera) {Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);Matrix matrix = new Matrix();// 设置图像的旋转角度matrix.setRotate(cameraView.getAngle());// 旋转图像,并生成新的Bitmap对像bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), matrix, true);File file=new File("/sdcard/faceData/identify/"+System.currentTimeMillis()+"_lmy.jpg");File fileParent=file.getParentFile();if(!fileParent.exists()){fileParent.mkdirs();}try {if(file.createNewFile()){writePhoto(bitmap, bitmap.getWidth(), bitmap.getHeight(), file.getAbsolutePath());DetectFace(cascadeClassifier,file.getAbsolutePath(),2);LoadFaceData();int mm=Identification(file);String mmsString = faceList.get(mm).getPath();int zz = (int)(100*CmpPic(mmsString, file.getAbsolutePath()));//Log.i(tag, ""+i);//if(i<faceList.size())//////{////}String srcpath ="";String despath = file.getAbsolutePath();//int [] s = new int[1000];int valuemax=0;int b=0;int value=0;int imax = 0;for (int i = 0; i < faceList.size(); i++) { srcpath = faceList.get(i).getPath(); b=(int)(100*CmpPic(srcpath, despath));if (b>valuemax){imax=i;value=b;}valuemax=b;}//int vaule = getMax(s);Toast.makeText(MainActivity.this, ""+value, Toast.LENGTH_SHORT).show();                    Toast.makeText(MainActivity.this, srcpath, Toast.LENGTH_LONG).show();                    setContentView(R.layout.face);//                    LayoutInflater factorys = LayoutInflater.from(MainActivity.this);//                     View textEntryView = factorys.inflate(R.layout.face, null);//                     setContentView(textEntryView);                    ImageView faceView = (ImageView) findViewById(R.id.imageView1);                    faceView.setImageBitmap(BitmapFactory.decodeFile(faceList.get(imax).getPath()));                    EditText photoname = (EditText) findViewById(R.id.editText1);                    photoname.setText(srcpath);                    EditText semblance = (EditText) findViewById(R.id.editText2);                    semblance.setText(value+"");                                        ImageView view2 = (ImageView) findViewById(R.id.imageView2);                    view2.setImageBitmap(BitmapFactory.decodeFile(faceList.get(mm).getPath()));                    EditText text3 = (EditText) findViewById(R.id.editText3);                    text3.setText(mmsString);                    EditText text4 = (EditText) findViewById(R.id.editText4);                    text4.setText(""+zz);                                        Button sureButton = (Button) findViewById(R.id.button1);                    sureButton.setText("确定");                    sureButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubsetContentView(R.layout.activity_main);cameraView=(CameraView) findViewById(R.id.cameraView1);btn_xl=(Button) findViewById(R.id.btn_xl);btn_xl.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubcameraView.getPhoto(pictureCallbackDetect);}});btn_sb=(Button)findViewById(R.id.btn_sb);btn_sb.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubcameraView.getPhoto(pictureCallbackIdentification);}});}});}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}; public static int getMax(int[] arr) {int max = arr[0];for (int x = 1; x < arr.length; x++) {if (arr[x] > max)max = arr[x];}return max;}private CameraView cameraView;private Button btn_xl;private Button btn_sb;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);cameraView=(CameraView) findViewById(R.id.cameraView1);btn_xl=(Button) findViewById(R.id.btn_xl);btn_xl.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubcameraView.getPhoto(pictureCallbackDetect);}});btn_sb=(Button)findViewById(R.id.btn_sb);btn_sb.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubcameraView.getPhoto(pictureCallbackIdentification);}});}@Overrideprotected void onResume() {// TODO Auto-generated method stubsuper.onResume();OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_8, this,mLoaderCallback);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}/** *  * @param srcPath * @param desPath * @return */public double CmpPic(String srcPath,String desPath) {int l_bins = 20;int hist_size[] = { l_bins };float v_ranges[] = { 0, 100 };float ranges[][] = { v_ranges };IplImage Image1 = cvLoadImage(srcPath, CV_LOAD_IMAGE_GRAYSCALE);IplImage Image2 = cvLoadImage(desPath, CV_LOAD_IMAGE_GRAYSCALE);IplImage imageArr1[] = { Image1 };IplImage imageArr2[] = { Image2 };CvHistogram Histogram1 = CvHistogram.create(1, hist_size,CV_HIST_ARRAY, ranges, 1);CvHistogram Histogram2 = CvHistogram.create(1, hist_size,CV_HIST_ARRAY, ranges, 1);cvCalcHist(imageArr1, Histogram1, 0, null);cvCalcHist(imageArr2, Histogram2, 0, null);cvNormalizeHist(Histogram1, 100.0);cvNormalizeHist(Histogram2, 100.0);return cvCompareHist(Histogram1, Histogram2, CV_COMP_CORREL);}public void DetectFace(CascadeClassifier cascadeClassifier,String path,int type) {Mat image = Highgui.imread(path);MatOfRect faceDetections = new MatOfRect();cascadeClassifier.detectMultiScale(image, faceDetections);for (Rect rect : faceDetections.toArray()) {Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x+ rect.width, rect.y + rect.height), new Scalar(0, 255, 0));// 把检测到的人脸重新定义大小后保存成文件Mat sub = image.submat(rect);Mat mat = new Mat();Size size = new Size(200, 200);Imgproc.resize(sub, mat, size);if(type==1){Highgui.imwrite("/sdcard/faceData/detect/lmy/"+System.currentTimeMillis()+"_lmy.jpg", mat);File file=new File(path);file.delete();Toast.makeText(this, "加入成功", Toast.LENGTH_SHORT).show();}else if(type==2){Highgui.imwrite(path, mat);}}}public void LoadFaceData() {File[] files = new File("/sdcard/faceData/detect/lmy/").listFiles();File f;String id;String name;faceList.clear();for (int i = 0; i < files.length; i++) {f = files[i];if (!f.canRead()) {return;}if (f.isFile()) {id = f.getName().split("_")[0];name = f.getName().substring(f.getName().indexOf("_") + 1,f.getName().length() - 4);faceList.add(new FaceInfo(id, name, "/sdcard/faceData/detect/lmy/"+ f.getName()));}}}//人脸匹配使用的是JavaCV中的匹配方法public int Identification(File file) {LoadFaceData();FaceRecognizer fr = createFisherFaceRecognizer();MatVector mv = new MatVector(faceList.size());CvMat cvMat = CvMat.create(faceList.size(), 1, CV_32SC1);for (int i = 0; i < faceList.size(); i++) {IplImage img = cvLoadImage(faceList.get(i).getPath(),CV_LOAD_IMAGE_GRAYSCALE);mv.put(i, img);cvMat.put(i, 0, i);}fr.train(mv, cvMat);IplImage testImage = cvLoadImage(file.getAbsolutePath(), CV_LOAD_IMAGE_GRAYSCALE);return fr.predict(testImage);}public void writePhoto(Bitmap bmp, int width, int height, String path) {File file = new File(path);try {Bitmap bm = Bitmap.createBitmap(bmp, 0, 0, width, height);BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));if (bm.compress(Bitmap.CompressFormat.JPEG, 100, bos)) {bos.flush();bos.close();}} catch (Exception e) {e.printStackTrace();}}}

xml布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent" >   <com.lee.view.CameraView         android:id="@+id/cameraView1"         android:layout_width="fill_parent"         android:layout_height="fill_parent" />    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:layout_alignParentLeft="true" >        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:id="@+id/btn_xl"            android:text="将自己的照片加入图像数据库" />        <Button            android:layout_width="wrap_content"            android:layout_height="wrap_content"             android:id="@+id/btn_sb"            android:text="识别" />    </LinearLayout></RelativeLayout>

3.脸部信息

package com.lee.infos;public class FaceInfo {private String id;private String name;private String path;public FaceInfo() {}public FaceInfo(String id, String name, String path) {super();this.id = id;this.name = name;this.path = path;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPath() {return path;}public void setPath(String path) {this.path = path;};}

package com.lee.infos;public class Vauleinfo {private String srcpath;private int    vauleinfo;public Vauleinfo(){}public Vauleinfo(String srcpath,int vauleinfo){super();this.srcpath=srcpath;this.vauleinfo=vauleinfo;}public String getSrcpath(){return srcpath;}public void setSrcpath(String srcpath){this.srcpath = srcpath;}public int getValueinfo(){return vauleinfo;}public void setVauleinfo(int valueinfo){this.vauleinfo = valueinfo;}}

3.相机

package com.lee.view;import java.io.IOException;import android.app.Activity;import android.content.Context;import android.graphics.Canvas;import android.hardware.Camera;import android.hardware.Camera.PictureCallback;import android.util.AttributeSet;import android.view.Surface;import android.view.SurfaceHolder;import android.view.SurfaceHolder.Callback;import android.view.SurfaceView;public class CameraView extends SurfaceView implements Callback {public static final int TAKE_PHOTO=0;private SurfaceHolder holder;private Camera camera;private Context context;private int angle=0;public int getAngle() {return angle;}public CameraView(Context context) {super(context);// TODO Auto-generated constructor stubinit(context);}public CameraView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);// TODO Auto-generated constructor stubinit(context);}public CameraView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stubinit(context);}private void init(Context context) {holder=getHolder();this.context=context;holder.addCallback(this);holder.setKeepScreenOn(true);}@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {}@Overridepublic void surfaceCreated(SurfaceHolder holder) {// TODO Auto-generated method stubtry {camera=Camera.open(1);camera.setPreviewDisplay(holder);camera.setDisplayOrientation(getPreviewDegree((Activity) context));camera.startPreview();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void surfaceDestroyed(SurfaceHolder holder) {// TODO Auto-generated method stubif(camera!=null){camera.release();camera=null;}}public void getPhoto(PictureCallback pictureCallback){//另外线程中执行拍照camera.takePicture(null, null, pictureCallback);//不能马上重新开始预览   拍照没有完成  当前线程等待1秒try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}//重新开始预览camera.startPreview();}@Overridepublic void draw(Canvas canvas) {// TODO Auto-generated method stubsuper.draw(canvas);}// 提供一个静态方法,用于根据手机方向获得相机预览画面旋转的角度  public int getPreviewDegree(Activity activity) {  // 获得手机的方向  int rotation = activity.getWindowManager().getDefaultDisplay()  .getRotation();  int degree = 0;  angle = 450 - rotation * 90-180;if (angle >= 360) {angle = angle - 360;}// 根据手机的方向计算相机预览画面应该选择的角度  switch (rotation) {  case Surface.ROTATION_0:  degree = 90;  break;  case Surface.ROTATION_90:  degree = 0;  break;  case Surface.ROTATION_180:  degree = 270;  break;  case Surface.ROTATION_270:  degree = 180;  break;  }  return degree;  } }


0 0
原创粉丝点击