过年拍照独缺你?用机器学习服务一秒生成全家福

“妈,今年我就不回家过年啦。”

给正在老家热火朝天备年货的老妈打完电话,难掩失落。牛年春节注定与众不同,没有老妈催我起床大扫除,不能在年饭桌上吃上一口朝思慕想的“妈妈牌”饺子,贴春联的任务今年也不能认领……那些年月里微小而温情的事儿,今年都得在回忆里复习。心里尤为惦念的,还有每年过年一家子团聚时必不可少的全家福。好在,今年虽然不能相聚餐桌前,大家在全家福里依然能相聚。

如果今年你也不回家过年,教你一招,借助华为机器学习服务,让身在异地的家人们,完成一张不缺席的温暖全家福。

合成全家福功能演示:

全家福

原理解释

应用华为机器学习服务中的图像分割能力,把照片中人像元素的部分从图像整体中分割出来,再将背景替换为家人合照的背景。

全家福生成开发步骤详解

一、开发准备

1. 配置华为Maven仓地址。

buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
...
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
}
}
 
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
} 

2. 添加编译SDK依赖

dependencies {
    // 引入基础SDK
    implementation 'com.huawei.hms:ml-computer-vision-segmentation:2.1.0.301'
    // 引入人像分割模型包
    implementation 'com.huawei.hms:ml-computer-vision-image-segmentation-body-model:2.1.0.303'
}

3. 在AndroidManifest.xml中添加权限

// 使用存储权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

二、具体开发步骤

1. 动态权限申请

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (!allPermissionsGranted()) {
        getRuntimePermissions();
    }
}
private boolean allPermissionsGranted() {
    for (String permission : getRequiredPermissions()) {
        if (!isPermissionGranted(this, permission)) {
            return false;
        }
    }
    return true;
}
private void getRuntimePermissions() {
    List<String> allNeededPermissions = new ArrayList<>();
    for (String permission : getRequiredPermissions()) {
        if (!isPermissionGranted(this, permission)) {
            allNeededPermissions.add(permission);
        }
    }
    if (!allNeededPermissions.isEmpty()) {
        ActivityCompat.requestPermissions(
                this, allNeededPermissions.toArray(new String[0]), PERMISSION_REQUESTS);
    }
}
private static boolean isPermissionGranted(Context context, String permission) {
    if (ContextCompat.checkSelfPermission(context, permission)
            == PackageManager.PERMISSION_GRANTED) {
        return true;
    }
    return false;
}
private String[] getRequiredPermissions() {
    try {
        PackageInfo info =
                this.getPackageManager()
                        .getPackageInfo(this.getPackageName(), PackageManager.GET_PERMISSIONS);
        String[] ps = info.requestedPermissions;
        if (ps != null && ps.length > 0) {
            return ps;
        } else {
            return new String[0];
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        return new String[0];
    }
}

2. 创建图片分割检测器

MLImageSegmentationSetting setting = new MLImageSegmentationSetting.Factory()
// 设置为人像分割
        .setAnalyzerType(MLImageSegmentationSetting.BODY_SEG)
        .create();
this.analyzer = MLAnalyzerFactory.getInstance().getImageSegmentationAnalyzer(setting);

3. 通过android.graphics.Bitmap创建“MLFrame”对象用于分析器检测图片

MLFrame mlFrame = new MLFrame.Creator().setBitmap(this.originBitmap).create();

4. 调用“asyncAnalyseFrame ”方法进行图像分割

// 创建一个task,处理图像分割检测器返回的结果。
Task<MLImageSegmentation> task = this.analyzer.asyncAnalyseFrame(mlFrame);
// 异步处理图像分割检测器返回的结果。
task.addOnSuccessListener(new OnSuccessListener<MLImageSegmentation>() {
    @Override
    public void onSuccess(MLImageSegmentation mlImageSegmentationResults) {.
        if (mlImageSegmentationResults != null) {
//获得从图片中分割出的人像前景图
            foreground = mlImageSegmentationResults.getForeground();
            preview.setImageBitmap(MainActivity.this.foreground);
        }
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {
        return;
    }
});

5. 更换图片背景

// 从相册中获取图片
backgroundBitmap = Utils.loadFromPath(this, id, targetedSize.first, targetedSize.second);
BitmapDrawable drawable = new BitmapDrawable(backgroundBitmap);
preview.setBackground(drawable);
preview.setImageBitmap(this.foreground);

根据以上的步骤,就可以实现这个好玩的全家福生成功能了,就地过年不能团圆,全家福依然“缺一不可”。你还可以在此功能基础上做很多有意思的拓展,比如用华为图像服务给全家福添加一些小贴纸,让照片年味更足、更有趣味。

 

猜你喜欢

转载自blog.csdn.net/HUAWEI_HMSCore/article/details/113778873