【Android】Android自帶人臉檢測FaceDetector
阿新 • • 發佈:2019-01-24
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; 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.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); setContentView(new myView(this)); //使用自建的view來顯示 Log.i("APP","MainActivity run here"); } private class myView extends View{ private int imageWidth, imageHeight; private int numberOfFace = 5; //最大檢測的人臉數 private FaceDetector myFaceDetect; //人臉識別類的例項 private FaceDetector.Face[] myFace; //儲存多張人臉的陣列變數 float myEyesDistance; //兩眼之間的距離 int numberOfFaceDetected; //實際檢測到的人臉數 Bitmap myBitmap; public myView(Context context){ //view類的建構函式,必須有 super(context); BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options(); BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565; //構造點陣圖生成的引數,必須為565。類名+enum myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ddd, BitmapFactoryOptionsbfo); imageWidth = myBitmap.getWidth(); imageHeight = myBitmap.getHeight(); myFace = new FaceDetector.Face[numberOfFace]; //分配人臉陣列空間 myFaceDetect = new FaceDetector(imageWidth, imageHeight, numberOfFace); numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace); //FaceDetector 構造例項並解析人臉 Log.i("APP","numberOfFaceDetected is " + numberOfFaceDetected); } protected void onDraw(Canvas canvas){ //override函式,必有 canvas.drawBitmap(myBitmap, 0, 0, null); //畫出點陣圖 Paint myPaint = new Paint(); myPaint.setColor(Color.GREEN); myPaint.setStyle(Paint.Style.STROKE); myPaint.setStrokeWidth(3); //設定點陣圖上paint操作的引數 for(int i=0; i < numberOfFaceDetected; i++){ Face face = myFace[i]; PointF myMidPoint = new PointF(); face.getMidPoint(myMidPoint); myEyesDistance = face.eyesDistance(); //得到人臉中心點和眼間距離引數,並對每個人臉進行畫框 canvas.drawRect( //矩形框的位置引數 (int)(myMidPoint.x - myEyesDistance), (int)(myMidPoint.y - myEyesDistance), (int)(myMidPoint.x + myEyesDistance), (int)(myMidPoint.y + myEyesDistance), myPaint); } } } }