Android 人臉偵測

這篇主要來介紹 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);
//讀取目前在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);
//eyesDistance: 兩眼間的距離
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);
}
}
}

執行結果

作者

Nick Lin

發表於

2018-07-09

更新於

2023-01-18

許可協議


評論