使用Google Mobile Vision FaceDetector检测onPreviewFrame回调中的面部?

时间:2017-10-12 07:10:15

标签: android face-detection google-vision

我使用com.google.android.gms.vision.face.FaceDetector检测如下所示的相机预览回调中的面孔:

faceDetector = new FaceDetector.Builder(this)
                .setTrackingEnabled(false)
                .setMode(FaceDetector.FAST_MODE)
                .setLandmarkType(FaceDetector.ALL_LANDMARKS)
                .build();

mCamera.setPreviewCallbackWithBuffer(new Camera.PreviewCallback() {
    @Override
    public void onPreviewFrame(final byte[] data, Camera camera) {
        if (faceDetector.isOperational()) {
            int format = camera.getParameters().getPreviewFormat();
            int width = camera.getParameters().getPreviewSize().width;
            int height = camera.getParameters().getPreviewSize().height;

            Frame frame = new Frame.Builder().setImageData(ByteBuffer.wrap(data), width, height, format).build();
            SparseArray<Face> faces = faceDetector.detect(frame);
            Log.d("TEST", "Num faces = " + faces.size());
        }

        mSurfaceView.requestRender();

        camera.addCallbackBuffer(mImageBuffer);
    }
});

但是,输出始终为Num faces = 0。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您犯了一个错误。您的代码必须如下所示:

faceDetector = new FaceDetector.Builder(this)
                .setTrackingEnabled(false)
                .setMode(FaceDetector.FAST_MODE)
                .setLandmarkType(FaceDetector.ALL_LANDMARKS)
                .build();

mCamera.setPreviewCallbackWithBuffer(new Camera.PreviewCallback() {
    @Override
    public void onPreviewFrame(final byte[] data, Camera camera) {
        if(!faceDetector.isOperational()){
            Log.e("TEST", "Could not set up the face detector!");
        } else {
            int format = camera.getParameters().getPreviewFormat();
            int width = camera.getParameters().getPreviewSize().width;
            int height = camera.getParameters().getPreviewSize().height;

            Frame frame = new Frame.Builder().setImageData(ByteBuffer.wrap(data), width, height, format).build();
            SparseArray<Face> faces = faceDetector.detect(frame);
            Log.d("TEST", "Num faces = " + faces.size());
        }

        mSurfaceView.requestRender();

        camera.addCallbackBuffer(mImageBuffer);
    }
});