本文是個人開發Camera APP中總結的問題之一,主要介紹FaceDetection的基本使用方法和注意問題。文中如有錯誤和不足,歡迎批評指正。
一、關於FaceDetection
1、版本支持
FaceDetection是Android
ICE_CREAM_SANDWICH (Android Version 4.0,ADT 14)版開始增加的功能,實際是否支持還得依賴於設備自身的限制(
Camera.Parameters.getMaxNumDetectedFaces()
> 0)。
2、FaceDetectionListener
下面是FaceDetectionListener接口的源碼:
/**
* Callback interface for face detected in the preview frame.
*
*/
public interface FaceDetectionListener
{
/**
* Notify the listener of the detected faces in the preview frame.
*
* @param faces The detected faces in a list
* @param camera The {@link Camera} service object
*/
void onFaceDetection(Face[] faces, Camera camera);
}
FaceDetectionListener只有一個方法,FaceDetection(Face[] faces, Camera camera)。其中faces是檢測到的人臉數組(注意可能檢測不到),camera是當前Camera對象。
使用時,需要創建一個FaceDetectionListener並重寫onFaceDetection方法,在方法中遍歷faces進行處理。
Example:
mCamera.setFaceDetectionListener(new NodinFaceDetectionListener());
class NodinFaceDetectionListener implements FaceDetectionListener {
private static final String TAG = "NodinFaceDetectionListener";
@Override
public void onFaceDetection(Face[] faces, Camera camera) {
// TODO Auto-generated method stub
if (null == faces || faces.length == 0) {
//TODO Hide face frame.
Log.d(TAG, "onFaceDetection : There is no face found.");
} else {
//Face face = faces[0];
//Rect faceRect = face.rect;
//TODO Calculate the size of face frame and show.
Log.d(TAG, "onFaceDetection : At least one face has been found.");
}
}
}
3、啟動FaceDetection
啟動FaceDetection很簡單,mCamera.startFaceDetection().
但是需要注意一個問題:startFaceDetection()方法必須在Camera的startPreview之后調用
4、停止FaceDetection
mCamera.stopFaceDetection().
同樣需要注意順序問題:stopFaceDetection()方法必須在Camera的stopPreview之前調用
5、關於takePicture
Google API描述,在執行Camera的takePicture方法時,系統會自動調用stopPreview同時停止FaceDetection。如果此后又調用了stopFaceDetection()方法,會拋出
IllegalStateException:stop facedetection failed.由於該異常是從底層拋出的,無法確定異常拋出行,解決起來比較棘手。在此例中,由於FaceDetection在takePicture時已經stop,如果再調用stopFaceDetection()方法,會出現該問題。在使用FaceDetection時,使用狀態標識來記錄Face Detector的狀態,在takePicture時將標識設為stop並在start和stop方法中判斷標識狀態,可以避免該問題。
——2013.5.14 寫於北京