task = this.analyzer.asyncAnalyseFrame(mlFrame);
task.addOnSuccessListener(new OnSuccessListener() {
@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 更换图片背景。
```java
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);
```
---
## 结后语
就这样,一款证件DIY的小程序就制作好了,给大家看下Demo的演示效果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200403144201569.gif#pic_center)
如果你动手能力强的话,还可以添加更换西服等操作,源码已经上传github,大家也可以在github上一起完善该功能。
github源码地址请戳(工程目录为:ID-Photo-DIY)
基于图像分割能力不仅仅可以用来做证件照DIY程序,还可以实现如下相关功能:
1. 生活照的人像抠图,更换背景制作一些趣味的照片,或者对背景做虚化得到更美、更有艺术效果的照片。
2. 识别图像中的天空、植物、美食、猫狗、花朵、水面等、沙面、建筑、山峰等元素,针对这些元素做特殊的美化,比如让天空更蓝,水更清澈。
3. 识别视频流中的对象,对视频流进行特效编辑、更换背景。
其它功能请大家一起开脑洞吧!
**更详细的开发指南参考华为开发者联盟官网**
[华为开发者联盟机器学习服务开发指南](https://developer.huawei.com/consumer/cn/doc/development/HMS-Guides/ml-introduction-4)
---
往期链接:[Android | 教你如何用三十分钟在安卓上开发一个微笑抓拍神器](http://blog.itpub.net/69970551/viewspace-2689151/)
内容来源:[https://developer.huawei.com/consumer/cn/forum/topicview?tid=0201203408959360433&fid=18](https://developer.huawei.com/consumer/cn/forum/topicview?tid=0201203408959360433&fid=18)
原作者:AI_talking