Android提供android.media.FaceDetector類, 它可以從一個位圖圖形(Bitmap)對象中辨認人面. 下面是一個使用FaceDetector的例子.
首先複製一個有人面的位圖文件到SD Card上, 名為face1.jpg. (參考"如何複製檔案到 SD Card")
創建FaceView.java
package com.AndroidFaceDetection;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.util.AttributeSet;
import android.view.View;
public class FaceView extends View {
private final String faceImageUri = "/sdcard/face1.jpg";;
private Bitmap bitmapFace;
private int imageWidth, imageHeight;
private FaceDetector myFaceDetect;
private FaceDetector.Face[] faceDetected;
private final int numberOfFace = 5;
private int numberOfFaceDetected;
Paint paint;
public FaceView(Context context) {
super(context);
// TODO Auto-generated constructor stub
initFaceView();
}
public FaceView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
initFaceView();
}
public FaceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
initFaceView();
}
private void initFaceView(){
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapFace = BitmapFactory.decodeFile(faceImageUri);
imageWidth = bitmapFace.getWidth();
imageHeight = bitmapFace.getHeight();
faceDetected = new FaceDetector.Face[numberOfFace];
myFaceDetect = new FaceDetector(imageWidth, imageHeight, numberOfFace);
numberOfFaceDetected = myFaceDetect.findFaces(bitmapFace, faceDetected);
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(3);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(bitmapFace, 0, 0, null);
for(int i=0; i < numberOfFaceDetected; i++)
{
Face face = faceDetected[i];
PointF faceMidPoint = new PointF();
face.getMidPoint(faceMidPoint);
canvas.drawPoint(faceMidPoint.x, faceMidPoint.y, paint);
canvas.drawCircle(faceMidPoint.x, faceMidPoint.y, face.eyesDistance(), paint);
}
}
}
修改main.xml使用FaceView類
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<com.AndroidFaceDetection.FaceView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
主程序AndroidFaceDetection.java無需修改.
沒有留言:
發佈留言