我正在创建人脸转换应用程序。我能够检测到一张脸并在其中画一个椭圆形。现在我遇到了一个问题:裁剪出脸。我正在为此使用Vision API。
这是我的代码。它能够检测到人脸并在其上画一个圆:
private class SaveImageAsync extends AsyncTask<Bitmap, Void, Void> {
File file;
Bitmap bitmap;
@Override
protected Void doInBackground(Bitmap... bitmaps) {
bitmap = bitmaps[0];
Bitmap faceBitmap;
//Bitmap test = BitmapFactory.decodeResource(getResources(), R.drawable.traditional_f_filter_x);
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Bitmap tempBitmap = Bitmap.createBitmap(mutableBitmap.getWidth(), mutableBitmap.getHeight(), Bitmap.Config.RGB_565);
Paint paint = new Paint();
paint.setStrokeWidth(5);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
Canvas canvas = new Canvas(tempBitmap);
canvas.drawBitmap(mutableBitmap, 0, 0 , null);
FaceDetector detector = new FaceDetector.Builder(getApplicationContext()).setTrackingEnabled(false).build();
if (!detector.isOperational()) {
Toast.makeText(getApplicationContext(), "ERROR", Toast.LENGTH_LONG).show();
}
Frame frame = new Frame.Builder().setBitmap(mutableBitmap).build();
try {
SparseArray<Face> faces = detector.detect(frame);
Face face = faces.valueAt(0);
int left = (int) (face.getPosition().x);
int top = (int) (face.getPosition().y);
int right = (int) (face.getPosition().x + face.getWidth());
int bottom = (int) (face.getPosition().y + face.getHeight());
canvas.drawOval(new RectF(left, top, right, bottom), paint);
faceBitmap = Bitmap.createBitmap(tempBitmap, left, top, right - left, bottom - top);
file = getOutputMediaFile(getApplicationContext());
FilterSystem.selectedImage = faceBitmap;
} catch (Exception e) {
faceBitmap = null;
Log.e("ERROR", "CANNOT DETECT FACE " +e.getMessage());
}
try {
FileOutputStream fos = new FileOutputStream(file);
faceBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "DONE PROCESSING", Toast.LENGTH_LONG).show();
}
}
现在,我可以轻松地从整个图像中裁剪出包含面部的圆圈,然后换出图像,但这不是我想要的。我只想要脸部特征(眼睛,鼻子,嘴巴),并能够过滤它们,因此颜色也能匹配。我该如何实现?我已经看过OpenCV,但不知道如何从这里继续。还有其他选择吗?