I have a small app just to test out camera preview and facial recognition. The preview surface displays and I can see the onFaceDetection callback getting called. If I put a Log call in onFaceDetection I see it called repeatedly, but with an empty Faces[] array.
Note: The "Log" call below is not the one that is called, the Log call in my example below is never called. But I can add another Log call outside of the for
statement and that will be called.
Here's my code:
package com.example.glassgoggles;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Face;
import android.hardware.Camera.FaceDetectionListener;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraPreviewView extends SurfaceView implements SurfaceHolder.Callback, FaceDetectionListener {
private SurfaceHolder surfaceHolder = null;
private Camera camera = null;
@SuppressWarnings("deprecation")
public CameraPreviewView(Context context) {
super(context);
surfaceHolder = this.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
this.setCameraParameters();
try
{
camera.setPreviewDisplay(holder);
}
catch (Exception e)
{
this.releaseCamera();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (camera != null)
{
camera.setFaceDetectionListener(this);
camera.startPreview();
this.startFaceDetectionIfSupported();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
this.releaseCamera();
}
public void releaseCamera()
{
if (camera != null)
{
camera.release();
camera = null;
}
}
public void setCameraParameters()
{
if (camera != null)
{
Parameters parameters = camera.getParameters();
parameters.setPreviewFpsRange(30000, 30000);
camera.setParameters(parameters);
}
}
public void startFaceDetectionIfSupported() {
if (camera != null) {
Parameters parameters = camera.getParameters();
if (parameters.getMaxNumDetectedFaces() > 0) {
Log.d("Face Detection", "Starting...");
camera.startFaceDetection();
} else {
Log.d("Face Detection", "No faces allowed...");
}
}
}
@Override
public void onFaceDetection(Face[] faces, Camera camera) {
for(int i = 0; i < faces.length; i++) {
Log.d("Face Check", "Found a face...");
}
}
}