這篇主要來介紹 Android API - FaceDetector 實做人臉偵測
設備環境
Device : Acrer Iconia Tab 10
Version : Android 6.0 (API 23, M)
FaceDetector
畫面中使用 ImageView 和 Button,ImageView用來顯示偵測的圖片
點擊Button後,標示出人臉的部份。
ImageView預設讀入Resources中的圖片
點擊按鈕後,先讀取圖片再進行偵測
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Override public void onClick(View v) { switch(v.getId()) { case R.id.button: ImageView imageView = findViewById(R.id.imageView); Bitmap source = ((BitmapDrawable)imageView.getDrawable()).getBitmap(); Bitmap detectMap = detectFace(source); imageView.setImageBitmap(detectMap); break; default: break; } }
|
由於Android的人臉辨識,需要使用 RGB565的圖片,所以我們必須先轉換格式
1
| Bitmap source = bitmap.copy(Bitmap.Config.RGB_565, true);
|
轉換格式後,再透過 FaceDetector 進行人臉偵測
1 2 3 4 5 6 7 8 9 10 11 12 13
| public Bitmap detectFace(Bitmap bitmap) { Bitmap source = bitmap.copy(Bitmap.Config.RGB_565, true); int MAX_FACES = 5; FaceDetector faceDet = new FaceDetector(source.getWidth(), source.getHeight(), MAX_FACES);
FaceDetector.Face[] faceArray = new FaceDetector.Face[MAX_FACES]; faceDet.findFaces(source, faceArray); drawDetectRect(source, faceArray);
return source; }
|
繪製偵測到的區域
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public void drawDetectRect(Bitmap source, FaceDetector.Face[] faceArray) { int findFaceCount = faceArray.length;
if (findFaceCount == 0) { return; }
Canvas canvas = new Canvas(source); Paint p = new Paint(); p.setAntiAlias(true); p.setStrokeWidth(4); p.setStyle(Paint.Style.STROKE); p.setColor(Color.RED); PointF pf = new PointF(); RectF rf = new RectF(); for(int i = 0; i < findFaceCount; i++) { FaceDetector.Face face = faceArray[i]; if (null != face) { face.getMidPoint(pf); rf.left = pf.x - face.eyesDistance(); rf.right = pf.x + face.eyesDistance(); rf.top = pf.y - face.eyesDistance(); rf.bottom = pf.y + face.eyesDistance();
canvas.drawRect(rf, p); } } }
|
執行結果