基于安卓的视频遥控小车实现人脸跟随看起来好像高大上,其实是用的安卓自带的人脸检测API(FaceDetector),将其和红外发射代码结合起来,实现了小车人脸跟随功能。
人脸检测的接口为FaceDetectionListener,
private class MyFaceDetectionListener implements Camera.FaceDetectionListener { @Override public void onFaceDetection(Camera.Face[] faces, Camera camera) { if (faces.length > 0){ Log.d("FaceDetection", "face detected: "+ faces.length + " Face 1 Location X: " + faces[0].rect.centerX() + "Y: " + faces[0].rect.centerY() ); } } }
通过Camera的setFaceDetedtionListener方法来接受底层检测到脸的回掉。
mCamera.setFaceDetectionListener(new MyFaceDetectionListener());
在摄像机开始预览了之后调用开始检测方法
private void startFaceDetection(){ // Try starting Face Detection Camera.Parameters params = mCamera.getParameters(); // start face detection only *after* preview has started if (params.getMaxNumDetectedFaces() > 0){ // camera supports face detection, so can start it: mCamera.startFaceDetection(); } }
以上为通用步骤,我对MyFaceDetectionListener进行了改造,将其和红外发射代码transmit()方法结合起来,代码如下
private class MyFaceDetectionListener implements Camera.FaceDetectionListener{ private int faceX=0; private int faceY=0; boolean fMoveFlag = false;//设置标志位,只执行一次,不连续发送 boolean bMoveFlag = false; boolean lMoveFlag = false; boolean rMoveFlag = false; Camera.Parameters parameters; public MyFaceDetectionListener(Camera.Parameters parameters) { this.parameters=parameters; } @Override public void onFaceDetection(Camera.Face[] faces, Camera camera) { if (faces.length > 0){ Log.d("FaceDetection", "face detected: "+ faces.length + " Face 1 Location X: " + faces[0].rect.centerX() + "Y: " + faces[0].rect.centerY() ); faceX=faces[0].rect.centerX(); faceY=faces[0].rect.centerY(); if(faceY<-100&&!fMoveFlag){ mCIR.transmit(38000, pattern1); fMoveFlag=true; bMoveFlag=false; } if(faceY>100&&!bMoveFlag){ mCIR.transmit(38000, pattern2); bMoveFlag=true; fMoveFlag=false; } if(faceX<-100&&!lMoveFlag){ mCIR.transmit(38000, pattern3); lMoveFlag=true; rMoveFlag=false; } if(faceX>100&&!rMoveFlag){ mCIR.transmit(38000, pattern4); rMoveFlag=true; lMoveFlag=false; } }else{ } } }
红外发射部分详见基于安卓的视频遥控小车——红外详解
人脸追踪代码:http://www.pudn.com/Download/item/id/3913500.html
参考文献
感谢以下文章的博主的分享
Android音视频-视频采集(Camera预览) - LymanYe的博客
Android自带人脸识别
Adnroid 使用安卓自带的人脸识别API - 风飞飘扬的专栏