证件照DIY开发实战
1 开发准备
1.1 在项目级gradle里添加华为maven仓
打开AndroidStudio项目级build.gradle文件。
增量添加如下maven地址:
buildscript {
repositories {
maven {url 'http://developer.huawei.com/repo/'}
} }allprojects {
repositories {
maven { url 'http://developer.huawei.com/repo/'}
}}
1.2 在应用级的build.gradle里面加上SDK依赖
把人脸识别的SDK和基础SDK引入
dependencies{
// 引入基础SDK
implementation 'com.huawei.hms:ml-computer-vision:1.0.2.300'
// 引入人脸检测能力包
implementation 'com.huawei.hms:ml-computer-vision-image-segmentation-body-model:1.0.2.301'
}
1.3 在AndroidManifest.xml文件里面增量添加模型自动下载
要使应用程序能够在用户从华为应用市场安装您的应用程序后,自动将最新的机器学习模型更新到用户设备,请将以下语句添加到该应用程序的AndroidManifest.xml文件中:
<manifest
<application
<meta-data
android:name="com.huawei.hms.ml.DEPENDENCY"
android:value= "imgseg "/>
</application>
</manifest>
1.4 在AndroidManifest.xml文件里面申请相机和存储权限
2 代码开发关键步骤
2.1 动态权限申请
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!allPermissionsGranted()) {
getRuntimePermissions();
}}@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode != PERMISSION_REQUESTS) {
return;
}
boolean isNeedShowDiag = false;
for (int i = 0; i < permissions.length; i++) {
if (permissions[i].equals(Manifest.permission.READ_EXTERNAL_STORAGE) && grantResults[i] != PackageManager.PERMISSION_GRANTED) {
// 如果相机或者存储权限没有授权,则需要弹出授权提示框
isNeedShowDiag = true;
}
}
if (isNeedShowDiag && !ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
AlertDialog dialog = new AlertDialog.Builder(this)
.setMessage(getString(R.string.camera_permission_rationale))
.setPositiveButton(getString(R.string.settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName())); // 根据包名打开对应的设置界面
startActivityForResult(intent, 200);
startActivity(intent);
}
})
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).create();
dialog.show();
}}
2.2 创建图像分割检测器
可以通过图像分割检测配置器“MLImageSegmentationSetting”创建图像分割检测器。
MLImageSegmentationSetting setting = new MLImageSegmentationSetting.Factory()
.setAnalyzerType(MLImageSegmentationSetting.BODY_SEG)
.setExact(true)
.create();
this.analyzer = MLAnalyzerFactory.getInstance().getImageSegmentationAnalyzer(setting);
2.3 通过android.graphics.Bitmap创建“MLFrame”对象用于分析器检测图片
可以通过图像分割检测配置器“MLImageSegmentationSetting”创建图像分割检测器。
MLFrame mlFrame = new MLFrame.Creator().setBitmap(this.originBitmap).create();
2.4 调用“asyncAnalyseFrame ”方法进行图像分割。
// 创建一个task,处理图像分割检测器返回的结果。 Task<MLImageSegmentation> task = analyzer.asyncAnalyseFrame(frame); // 异步处理图像分割检测器返回结果 Task<MLImageSegmentation> task = this.analyzer.asyncAnalyseFrame(mlFrame);
task.addOnSuccessListener(new OnSuccessListener<MLImageSegmentation>() {
@Override public void onSuccess(MLImageSegmentation mlImageSegmentationResults) {
// Transacting logic for segment success.
if (mlImageSegmentationResults != null) {
StillCutPhotoActivity.this.foreground = mlImageSegmentationResults.getForeground();
StillCutPhotoActivity.this.preview.setImageBitmap(StillCutPhotoActivity.this.foreground);
StillCutPhotoActivity.this.processedImage = ((BitmapDrawable) ((ImageView) StillCutPhotoActivity.this.preview).getDrawable()).getBitmap();
StillCutPhotoActivity.this.changeBackground();
} else {
StillCutPhotoActivity.this.displayFailure();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override public void onFailure(Exception e) {
// Transacting logic for segment failure.
StillCutPhotoActivity.this.displayFailure();
return;
}
});
2.5 更换图片背景。
this.backgroundBitmap = BitmapUtils.loadFromPath(StillCutPhotoActivity.this, id, targetedSize.first, targetedSize.second);BitmapDrawable drawable = new BitmapDrawable(backgroundBitmap);this.preview.setDrawingCacheEnabled(true);this.preview.setBackground(drawable);this.preview.setImageBitmap(this.foreground);this.processedImage = Bitmap.createBitmap(this.preview.getDrawingCache());this.preview.setDrawingCacheEnabled(false);