Android 调用camera2 人脸识别api


拍照预览时进行人脸识别,结果返回给callback函数


Preview.java


try {
            mCamera.setPreviewDisplay(mHolder);


            if(mOnFaceDetected != null){
                mCamera.setFaceDetectionListener(mOnFaceDetected);
            }


            mCamera.startPreview();




            Camera.Parameters params = mCamera.getParameters();
            // start face detection only *after* preview has started


            if(mOnFaceDetected != null){
                if (params.getMaxNumDetectedFaces() > 0){
                    // camera supports face detection, so can start it:
                    mCamera.startFaceDetection();
                    Log.d("DEBUG", "Face detection started");
                }
            }




        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }


Callback.Activity

OnCreate:

...
        mPreview.setOnFaceDetected(this);
...


callback函数:

private boolean focused = false;
    private int faceDetectCount = 0;
    @Override
    public void onFaceDetection(Camera.Face[] faces, Camera camera) {
        if (faces.length == 0) {
            Log.i("face", "No faces detected");
        } else if (faces.length > 0) {


            int centerX = faces[0].rect.centerX();
            int centerY = faces[0].rect.centerY();


            Log.i("face", "Faces Detected : " +
                    centerX +"," + centerY);


            faceDetectCount++;
            if(centerX <= -450 && centerX >= -600 && centerY >= 250 && centerY <= 350){
                if(!focused){
                    focusArea(-1000,-1000,1000,1000,750);
                    focused = true;
                }else{
                    if(faceDetectCount % 20 == 0){
                        mCamera.stopFaceDetection();
                        takepic();
                     //   icBack(mPreview);
                    }
                }
            }
            // add function to draw rects on view/surface/canvas
            //focusArea(faces[0].rect.left,faces[0].rect.top,faces[0].rect.right,faces[0].rect.bottom,100);
          //  takepic(mPreview);
        }
    }


你可能感兴趣的:(JAVA,android)