Android动态人脸检测的示例代码(脸数可调)
程序员文章站
2023-12-15 19:23:28
人脸检测
这里的人脸检测并非人脸识别,但是却可以识别出是否有人,当有人时候,你可以将帧图进行人脸识别(这里推荐face++的sdk),当然我写的demo中没有加入人脸识别...
人脸检测
这里的人脸检测并非人脸识别,但是却可以识别出是否有人,当有人时候,你可以将帧图进行人脸识别(这里推荐face++的sdk),当然我写的demo中没有加入人脸识别,有兴趣的朋友可以追加。
android自带的人脸检测
这里我们用到了人脸检测类为 facedetector.这个类提供了强大的人脸检测功能,可以方便我们进行人脸的侦测,因此我们使用他来进行动态的人脸检测,实现原理,其实也挺简单,主要是通过carmen的回调previewcallback 在其中对帧图进行操作,并通过facedetector来检测该帧图中是否有人脸。当然如果你想在surfaceview中绘制人脸的范围,可以将画布与其绑定,画完再解绑。
第一步
我们首先来定义一个surfaceview 盖在我们carmen使用的surfaceview上 进行对人脸范围的绘制
public class findfaceview extends surfaceview implements surfaceholder.callback { private surfaceholder holder; private int mwidth; private int mheight; private float eyesdistance; public findfaceview(context context, attributeset attrs) { super(context, attrs); holder = getholder(); holder.addcallback(this); holder.setformat(pixelformat.transparent); this.setzorderontop(true); } @override public void surfacechanged(surfaceholder holder, int format, int width, int height) { mwidth = width; mheight = height; } @override public void surfacecreated(surfaceholder holder) { } @override public void surfacedestroyed(surfaceholder holder) { } public void drawrect(facedetector.face[] faces, int numberoffacedetected) { canvas canvas = holder.lockcanvas(); if (canvas != null) { paint clippaint = new paint(); clippaint.setantialias(true); clippaint.setstyle(paint.style.stroke); clippaint .setxfermode(new porterduffxfermode(porterduff.mode.clear)); canvas.drawpaint(clippaint); canvas.drawcolor(getresources().getcolor(color.transparent)); paint paint = new paint(); paint.setantialias(true); paint.setcolor(color.green); paint.setstyle(style.stroke); paint.setstrokewidth(5.0f); for (int i = 0; i < numberoffacedetected; i++) { face face = faces[i]; pointf midpoint = new pointf(); // 获得两眼之间的中间点 face.getmidpoint(midpoint); // 获得两眼之间的距离 eyesdistance = face.eyesdistance(); // 换算出预览图片和屏幕显示区域的比例参数 float scale_x = mwidth / 500; float scale_y = mheight / 600; log.e("eyesdistance=", eyesdistance + ""); log.e("midpoint.x=", midpoint.x + ""); log.e("midpoint.y=", midpoint.y + ""); // 因为拍摄的相片跟实际显示的图像是镜像关系,所以在图片上获取的两眼中间点跟手机上显示的是相反方向 canvas.drawrect((int) (240 - midpoint.x - eyesdistance) * scale_x, (int) (midpoint.y * scale_y), (int) (240 - midpoint.x + eyesdistance) * scale_x, (int) (midpoint.y + 3 * eyesdistance) * scale_y, paint); } holder.unlockcanvasandpost(canvas); } } }
重要的地方
1. holder = getholder();获取surfaceholder与我们要绘制人脸范围的画布进行绑定canvas canvas = holder.lockcanvas();这样我们就可以愉快的进行绘制了,当然前提是我们要拿到人脸的坐标位置。
2. 还有重要的一点,就是要让我们用来盖在carema上的surfaceview可以同名,并且设置起在视图树的层级为最高。
holder.setformat(pixelformat.transparent); this.setzorderontop(true);
第二步
就是我们对人脸进行检测了,当然前提是我们要获得帧图
public class facerecognitiondemoactivity extends activity implements onclicklistener { private surfaceview preview; private camera camera; private camera.parameters parameters; private int orientionofcamera;// 前置摄像头的安装角度 private int facenumber;// 识别的人脸数 private facedetector.face[] faces; private findfaceview mfindfaceview; private imageview iv_photo; private button bt_camera; textview mtv; /** * called when the activity is first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); } @override protected void onstart() { super.onstart(); iv_photo = (imageview) findviewbyid(r.id.iv_photo); bt_camera = (button) findviewbyid(r.id.bt_camera); mtv = (textview) findviewbyid(r.id.show_count); bt_camera.setonclicklistener(this); mfindfaceview = (findfaceview) findviewbyid(r.id.my_preview); preview = (surfaceview) findviewbyid(r.id.preview); // 设置缓冲类型(必不可少) preview.getholder().settype(surfaceholder.surface_type_push_buffers); // 设置surface的分辨率 preview.getholder().setfixedsize(176, 144); // 设置屏幕常亮(必不可少) preview.getholder().setkeepscreenon(true); preview.getholder().addcallback(new surfacecallback()); } private final class mypicturecallback implements picturecallback { @override public void onpicturetaken(byte[] data, camera camera) { try { bitmap bitmap = bitmapfactory.decodebytearray(data, 0, data.length); matrix matrix = new matrix(); matrix.setrotate(-90); bitmap bmp = bitmap.createbitmap(bitmap, 0, 0, bitmap .getwidth(), bitmap.getheight(), matrix, true); bitmap.recycle(); iv_photo.setimagebitmap(bmp); camera.startpreview(); } catch (exception e) { e.printstacktrace(); } } } private final class surfacecallback implements callback { @override public void surfacechanged(surfaceholder holder, int format, int width, int height) { if (camera != null) { parameters = camera.getparameters(); parameters.setpictureformat(pixelformat.jpeg); // 设置预览区域的大小 parameters.setpreviewsize(width, height); // 设置每秒钟预览帧数 parameters.setpreviewframerate(20); // 设置预览图片的大小 parameters.setpicturesize(width, height); parameters.setjpegquality(80); } } @override public void surfacecreated(surfaceholder holder) { int cameracount = 0; camera.camerainfo camerainfo = new camera.camerainfo(); cameracount = camera.getnumberofcameras(); //设置相机的参数 for (int i = 0; i < cameracount; i++) { camera.getcamerainfo(i, camerainfo); if (camerainfo.facing == camera.camerainfo.camera_facing_front) { try { camera = camera.open(i); camera.setpreviewdisplay(holder); setcameradisplayorientation(i, camera); //最重要的设置 帧图的回调 camera.setpreviewcallback(new mypreviewcallback()); camera.startpreview(); } catch (exception e) { e.printstacktrace(); } } } } @override public void surfacedestroyed(surfaceholder holder) { //记得释放,避免oom和占用 if (camera != null) { camera.setpreviewcallback(null); camera.stoppreview(); camera.release(); camera = null; } } } private class mypreviewcallback implements previewcallback { @override public void onpreviewframe(byte[] data, camera camera) { //这里需要注意,回调出来的data不是我们直接意义上的rgb图 而是yuv图,因此我们需要 //将yuv转化为bitmap再进行相应的人脸检测,同时注意必须使用rgb_565,才能进行人脸检测,其余无效 camera.size size = camera.getparameters().getpreviewsize(); yuvimage yuvimage = new yuvimage(data, imageformat.nv21, size.width, size.height, null); bytearrayoutputstream baos = new bytearrayoutputstream(); yuvimage.compresstojpeg(new rect(0, 0, size.width, size.height), 80, baos); byte[] bytearray = baos.tobytearray(); detectionfaces(bytearray); } } /** * 检测人脸 * * @param data 预览的图像数据 */ private void detectionfaces(byte[] data) { bitmapfactory.options options = new bitmapfactory.options(); bitmap bitmap1 = bitmapfactory.decodebytearray(data, 0, data.length, options); int width = bitmap1.getwidth(); int height = bitmap1.getheight(); matrix matrix = new matrix(); bitmap bitmap2 = null; facedetector detector = null; //设置各个角度的相机,这样我们的检测效果才是最好 switch (orientionofcamera) { case 0: //初始化人脸检测(下同) detector = new facedetector(width, height, 10); matrix.postrotate(0.0f, width / 2, height / 2); // 以指定的宽度和高度创建一张可变的bitmap(图片格式必须是rgb_565,不然检测不到人脸) bitmap2 = bitmap.createbitmap(width, height, bitmap.config.rgb_565); break; case 90: detector = new facedetector(height, width, 1); matrix.postrotate(-270.0f, height / 2, width / 2); bitmap2 = bitmap.createbitmap(height, width, bitmap.config.rgb_565); break; case 180: detector = new facedetector(width, height, 1); matrix.postrotate(-180.0f, width / 2, height / 2); bitmap2 = bitmap.createbitmap(width, height, bitmap.config.rgb_565); break; case 270: detector = new facedetector(height, width, 1); matrix.postrotate(-90.0f, height / 2, width / 2); bitmap2 = bitmap.createbitmap(height, width, bitmap.config.rgb_565); break; } //设置支持的面数(最大支持检测多少人的脸 ,可以根据需要调整,不过需要与findfaces中的参数数值相同,否则会抛出异常) faces = new facedetector.face[10]; paint paint = new paint(); paint.setdither(true); canvas canvas = new canvas(); canvas.setbitmap(bitmap2); canvas.setmatrix(matrix); // 将bitmap1画到bitmap2上(这里的偏移参数根据实际情况可能要修改) canvas.drawbitmap(bitmap1, 0, 0, paint); //这里通过向findfaces中传递帧图转化后的bitmap和最大检测的人脸数face,返回检测后的人脸数 facenumber = detector.findfaces(bitmap2, faces); mtv.settext("facnumber----" + facenumber); mtv.settextcolor(color.red); //这里就是我们的人脸识别,绘制识别后的人脸区域的类 if (facenumber != 0) { mfindfaceview.setvisibility(view.visible); mfindfaceview.drawrect(faces, facenumber); } else { mfindfaceview.setvisibility(view.gone); } bitmap2.recycle(); bitmap1.recycle(); } /** * 设置相机的显示方向(这里必须这么设置,不然检测不到人脸) * * @param cameraid 相机id(0是后置摄像头,1是前置摄像头) * @param camera 相机对象 */ private void setcameradisplayorientation(int cameraid, camera camera) { camera.camerainfo info = new camera.camerainfo(); camera.getcamerainfo(cameraid, info); int rotation = getwindowmanager().getdefaultdisplay().getrotation(); int degree = 0; switch (rotation) { case surface.rotation_0: degree = 0; break; case surface.rotation_90: degree = 90; break; case surface.rotation_180: degree = 180; break; case surface.rotation_270: degree = 270; break; } orientionofcamera = info.orientation; int result; if (info.facing == camera.camerainfo.camera_facing_front) { result = (info.orientation + degree) % 360; result = (360 - result) % 360; } else { result = (info.orientation - degree + 360) % 360; } camera.setdisplayorientation(result); } @override public void onclick(view v) { switch (v.getid()) { case r.id.bt_camera: if (camera != null) { try { camera.takepicture(null, null, new mypicturecallback()); } catch (exception e) { e.printstacktrace(); } } break; } } }
到这里我们的人脸识别就已经大功告成。demo地址
如果您想了解更多关于人脸识别方面的只是,先去关注并了解opencv。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。