本文档为您介绍人体分割常用语言和常见情况的示例代码。
您可以进入在线咨询获取在线人工帮助。
阿里云视觉智能开放平台视觉AI能力API接入、接口使用或问题咨询等,请通过钉钉群(23109592)加入阿里云视觉智能开放平台咨询群联系我们。
能力介绍
关于人体分割的功能介绍以及具体调用参数说明,请参见人体分割。
SDK包安装
常见语言的SDK依赖包信息,请参见SDK总览。
配置环境变量
配置环境变量ALIBABA_CLOUD_ACCESS_KEY_ID和ALIBABA_CLOUD_ACCESS_KEY_SECRET。
阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维,具体操作,请参见创建RAM用户。
请不要将AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。
Linux和macOS系统配置方法
在IntelliJ IDEA中打开终端Terminal。
执行以下命令,配置环境变量。
<access_key_id>
需替换为您RAM用户的AccessKey ID,<access_key_secret>
替换为您RAM用户的AccessKey Secret。如果后续需要进行更多权限相关的配置,具体操作请参见使用RAM Policy控制访问权限。export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
Windows系统配置方法
新建环境变量文件,添加环境变量
ALIBABA_CLOUD_ACCESS_KEY_ID
和ALIBABA_CLOUD_ACCESS_KEY_SECRET
,并写入已准备好的AccessKey ID和AccessKey Secret。然后重启Windows系统。本操作以Windows 10为例进行说明。打开文件资源管理器,在此电脑上右键单击属性。
在右侧导航栏,单击高级系统配置。
在系统属性对话框的高级页签下,单击环境变量。
在环境变量对话框中,单击新建(W)。
在弹出的新建系统变量对话框中,添加环境变量
ALIBABA_CLOUD_ACCESS_KEY_ID
和ALIBABA_CLOUD_ACCESS_KEY_SECRET
,并写入已准备好的AccessKey ID和AccessKey Secret。重启Windows系统,使配置生效。
示例代码
文件在上海地域OSS
/*
引入依赖包
<!-- https://mvnrepository.com/artifact/com.aliyun/imageseg20191230 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>imageseg20191230</artifactId>
<version>${aliyun.imageseg.version}</version>
</dependency>
*/
import com.aliyun.imageseg20191230.models.SegmentBodyResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
public class SegmentBody {
public static com.aliyun.imageseg20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
初始化配置对象com.aliyun.teaopenapi.models.Config
Config对象存放 AccessKeyId、AccessKeySecret、endpoint等配置
*/
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// 访问的域名
config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new com.aliyun.imageseg20191230.Client(config);
}
public static void main(String[] args_) throws Exception {
// 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html
// 如果您使用的是RAM用户的AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
com.aliyun.imageseg20191230.Client client = SegmentBody.createClient(accessKeyId, accessKeySecret);
com.aliyun.imageseg20191230.models.SegmentBodyRequest segmentBodyRequest = new com.aliyun.imageseg20191230.models.SegmentBodyRequest()
.setImageURL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.png");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
SegmentBodyResponse segmentBodyResponse = client.segmentBodyWithOptions(segmentBodyRequest, runtime);
// 获取整体结果
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(segmentBodyResponse)));
// 获取单个字段
System.out.println(segmentBodyResponse.getBody().getData().getImageURL());
} catch (TeaException teaException) {
// 获取整体报错信息
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
// 获取单个字段
System.out.println(teaException.getCode());
}
}
}
# -*- coding: utf-8 -*-
# 引入依赖包
# pip install alibabacloud_imageseg20191230
import os
from alibabacloud_imageseg20191230.client import Client
from alibabacloud_imageseg20191230.models import SegmentBodyRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
# 初始化Config
config = Config(
# 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
# 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
# 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
# 访问的域名。
endpoint='imageseg.cn-shanghai.aliyuncs.com',
# 访问的域名对应的region
region_id='cn-shanghai'
)
request = SegmentBodyRequest(
image_url='https://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody_IDCard.jpeg',
#ReturnForm参数设置:
#指定返回的图像形式。
#如果设置为mask,则返回单通道黑白图。
#如果设置为crop,则返回裁剪之后的四通道PNG图(裁掉边缘空白区域)。
#如果设置为whiteBK,则返回白底图。
#如果不设置或者设置为其他值,则返回四通道PNG图。
return_form='mask'
)
# 初始化RuntimeObject
runtime_option = RuntimeOptions()
try:
# 初始化Client
client = Client(config)
response = client.segment_body_with_options(request, runtime_option)
# 获取整体结果
print(response.body)
except Exception as error:
# 获取整体报错信息
print(error)
# 获取单个字段
print(error.code)
# tips: 可通过error.__dict__查看属性名称
<?php
//安装依赖包
//composer require alibabacloud/imageseg-20191230
use AlibabaCloud\SDK\Imageseg\V20191230\Imageseg;
use AlibabaCloud\Tea\Utils\Utils;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Imageseg\V20191230\Models\SegmentBodyRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
class SegmentBody {
/**
* 使用AK&SK初始化账号Client
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Imageseg Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
//初始化配置对象Darabonba\OpenApi\Models\Config。
//Config对象存放accessKeyId、accessKeySecret、endpoint等配置
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret
]);
// 访问的域名
$config->endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new Imageseg($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
// 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
// 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
$client = self::createClient($accessKeyId, $accessKeySecret)
$segmentBodyRequest = new SegmentBodyRequest([
"imageURL" => "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody9.png",
"returnForm" => "mask"
]);
$runtime = new RuntimeOptions([]);
try {
$resp = $client->segmentBodyWithOptions($segmentBodyRequest, $runtime);
# 获取整体结果
echo Utils::toJSONString($resp->body);
} catch (Exception $exception) {
# 获取整体报错信息
echo Utils::toJSONString($exception);
# 获取单个字段
echo $exception->getCode();
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
//$argv是预留的数组入参参数,无实际意义,无需进行修改
SegmentBody::main(array_slice($argv, 1));
// 安装依赖包
// npm install @alicloud/imageseg20191230
const ImagesegClient = require('@alicloud/imageseg20191230');
const OpenapiClient = require('@alicloud/openapi-client');
const TeaUtil = require('@alicloud/tea-util');
let config = new OpenapiClient.Config({
// 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
// 如果您用的是RAM用户AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// 访问的域名
config.endpoint = `imageseg.cn-shanghai.aliyuncs.com`;
const client = new ImagesegClient.default(config);
let segmentBodyRequest = new ImagesegClient.SegmentBodyRequest({
imageURL: "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.png",
});
let runtime = new TeaUtil.RuntimeOptions({ });
client.segmentBodyWithOptions(segmentBodyRequest, runtime)
.then(function(segmentBodyRequestResponse) {
// 获取整体结果
console.log(segmentBodyRequestResponse);
// 获取单个字段
console.log(segmentBodyRequestResponse.body.data);
}, function(error) {
// 获取整体报错信息
console.log(error);
// 获取单个字段
console.log(error.data.Code);
})
/**
依赖github.com/alibabacloud-go/imageseg-20191230/v2
建议使用go mod tidy安装依赖
*/
import (
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
imageseg20191230 "github.com/alibabacloud-go/imageseg-20191230/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
func main() {
// 从环境变量读取配置的AccessKey ID
// 运行示例前必须先配置环境变量
// 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
// 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。
accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
// 初始化配置对象 &openapi.Config。Config对象存放AccessKeyId、AccessKeySecret、Endpoint等配置。
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret)
}
// 访问的域名
config.Endpoint = tea.String("imageseg.cn-shanghai.aliyuncs.com")
client, err := imageseg20191230.NewClient(config)
if err != nil {
panic(err)
}
segmentBodyRequest := &imageseg20191230.SegmentBodyRequest{
ImageURL: tea.String("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.png"),
}
runtime := &util.RuntimeOptions{}
segmentBodyResponse, err := client.SegmentBodyWithOptions(segmentBodyRequest, runtime)
if err != nil {
// 获取整体报错信息
fmt.Println(err.Error())
} else {
// 获取整体结果
fmt.Println(segmentBodyResponse)
}
}
// 安装依赖包
// dotnet add package AlibabaCloud.SDK.Imageseg20191230
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Imageseg20191230.Models;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* 使用AK&SK初始化账号Client
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Imageseg20191230.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
// 访问的域名
config.Endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new AlibabaCloud.SDK.Imageseg20191230.Client(config);
}
public static void Main(string[] args)
{
// 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html
// 如果您使用的是RAM用户的AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
AlibabaCloud.SDK.Imageseg20191230.Client client = CreateClient(System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
AlibabaCloud.SDK.Imageseg20191230.Models.SegmentBodyRequest segmentBodyRequest = new AlibabaCloud.SDK.Imageseg20191230.Models.SegmentBodyRequest
{
ImageURL = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.png",
};
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
AlibabaCloud.SDK.Imageseg20191230.Models.SegmentBodyResponse segmentBodyResponse = client.SegmentBodyWithOptions(segmentBodyRequest, runtime);
// 获取整体结果
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentBodyResponse.Body));
// 获取单个字段
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentBodyResponse.Body.Data));
}
catch (TeaException error)
{
// 如有需要,请打印 error
Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// 如有需要,请打印 error
Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
}
}
}
}
文件在本地或可访问的URL
/*
引入依赖包
<!-- https://mvnrepository.com/artifact/com.aliyun/imageseg20191230 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>imageseg20191230</artifactId>
<version>${aliyun.imageseg.version}</version>
</dependency>
*/
import com.aliyun.imageseg20191230.models.SegmentBodyResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import java.io.InputStream;
import java.net.URL;
public class SegmentBody {
public static com.aliyun.imageseg20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
初始化配置对象com.aliyun.teaopenapi.models.Config
Config对象存放 AccessKeyId、AccessKeySecret、endpoint等配置
*/
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// 访问的域名
config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new com.aliyun.imageseg20191230.Client(config);
}
public static void main(String[] args_) throws Exception {
// 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html
// 如果您使用的是RAM用户的AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
com.aliyun.imageseg20191230.Client client = SegmentBody.createClient(accessKeyId, accessKeySecret);
// 场景一,使用本地文件
// InputStream inputStream = new FileInputStream(new File("/tmp/detectVideoShot.mp4"));
// 场景二,使用任意可访问的url
URL url = new URL("https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody9.png");
InputStream inputStream = url.openConnection().getInputStream();
com.aliyun.imageseg20191230.models.SegmentBodyAdvanceRequest segmentBodyAdvanceRequest = new com.aliyun.imageseg20191230.models.SegmentBodyAdvanceRequest()
.setImageURLObject(inputStream);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
SegmentBodyResponse segmentBodyResponse = client.segmentBodyAdvance(segmentBodyAdvanceRequest, runtime);
// 获取整体结果
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(segmentBodyResponse)));
// 获取单个字段
System.out.println(segmentBodyResponse.getBody().getData().getImageURL());
} catch (TeaException teaException) {
// 获取整体报错信息
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
// 获取单个字段
System.out.println(teaException.getCode());
}
}
}
# -*- coding: utf-8 -*-
# 引入依赖包
# pip install alibabacloud_imageseg20191230
import os
import io
from urllib.request import urlopen
from alibabacloud_imageseg20191230.client import Client
from alibabacloud_imageseg20191230.models import SegmentBodyAdvanceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
# 初始化Config
config = Config(
# 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
# 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
# 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
# 访问的域名。
endpoint='imageseg.cn-shanghai.aliyuncs.com',
# 访问的域名对应的region
region_id='cn-shanghai'
)
request = SegmentBodyAdvanceRequest()
#场景一:文件在本地
#stream = open(r'/tmp/SegmentBody9.png', 'rb')
#request.image_urlobject = stream
#场景二:使用任意可访问的url
url = 'https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody9.png'
img = urlopen(url).read()
request.image_urlobject = io.BytesIO(img)
request.return_form = 'mask'
runtime_option = RuntimeOptions()
try:
# 初始化Client
client = Client(config)
response = client.segment_body_advance(request, runtime_option)
# 获取整体结果
print(response.body)
except Exception as error:
# 获取整体报错信息
print(error)
# 获取单个字段
print(error.code)
# tips: 可通过error.__dict__查看属性名称
#关闭流
#stream.close()
<?php
//安装依赖包
//composer require alibabacloud/imageseg-20191230
use AlibabaCloud\SDK\Imageseg\V20191230\Imageseg;
use AlibabaCloud\Tea\Utils\Utils;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Imageseg\V20191230\Models\SegmentBodyAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;
class SegmentBodyAdvance {
/**
* 使用AK&SK初始化账号Client
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Imageseg Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
//初始化配置对象Darabonba\OpenApi\Models\Config。
//Config对象存放accessKeyId、accessKeySecret、endpoint等配置
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret
]);
// 访问的域名
$config->endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new Imageseg($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
//创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html
//如果您是用的子账号AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
$client = self::createClient($accessKeyId, $accessKeySecret);
// 场景一,使用本地文件
//$file = fopen('/tmp/SegmentBody9.png', 'rb');
//$stream = new Stream($file);
// 场景二,使用任意可访问的url
$file = fopen('https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody9.png', 'rb');
$stream = new Stream($file);
$segmentBodyAdvanceRequest = new SegmentBodyAdvanceRequest([
"imageURLObject" => $stream,
"returnForm" => "mask"
]);
$runtime = new RuntimeOptions([]);
try {
$resp = $client->segmentBodyAdvance($segmentBodyAdvanceRequest, $runtime);
# 获取整体结果
echo Utils::toJSONString($resp->body);
} catch (Exception $exception) {
# 获取整体报错信息
echo Utils::toJSONString($exception);
# 获取单个字段
echo $exception->getCode();
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
//$argv是预留的数组入参参数,无实际意义,无需进行修改
SegmentBodyAdvance::main(array_slice($argv, 1));
// 安装依赖包
// npm install @alicloud/imageseg20191230
const ImagesegClient = require('@alicloud/imageseg20191230');
const OpenapiClient = require('@alicloud/openapi-client');
const TeaUtil = require('@alicloud/tea-util');
const fs = require('fs');
const http = require('http');
const https = require('https');
let config = new OpenapiClient.Config({
// 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
// 如果您用的是RAM用户AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// 访问的域名
config.endpoint = `imageseg.cn-shanghai.aliyuncs.com`;
const client = new ImagesegClient.default(config);
const getResponse = function (httpClient, url) {
return new Promise((resolve, reject) => {
httpClient.get(url, function (response) {
resolve(response);
})
})
}
const request = async function () {
try {
let segmentBodyAdvanceRequest = new ImagesegClient.SegmentBodyAdvanceRequest();
// 场景一,使用本地文件
// const fileStream = fs.createReadStream('/tmp/SegmentBody1.png');
// segmentBodyAdvanceRequest.imageURLObject = fileStream;
// 场景二,使用任意可访问的url
const url = new URL("https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody9.png");
const httpClient = (url.protocol == "https:") ? https : http;
const request = httpClient.get(url, function(response) {
segmentBodyAdvanceRequest.imageURLObject = await getResponse(httpClient, url);
let runtime = new TeaUtil.RuntimeOptions({ });
client.segmentBodyAdvance(segmentBodyAdvanceRequest, runtime)
.then(function(segmentBodyResponse) {
// 获取整体结果
console.log(segmentBodyResponse);
// 获取单个字段
console.log(segmentBodyResponse.body.data);
}, function(error) {
// 获取整体报错信息
console.log(error);
// 获取单个字段
console.log(error.data.Code);
})
} catch (error) {
console.log(error);
}
}();
/**
依赖github.com/alibabacloud-go/imageseg-20191230/v2
建议使用go mod tidy安装依赖
*/
import (
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
imageseg20191230 "github.com/alibabacloud-go/imageseg-20191230/v2/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
// 从环境变量读取配置的AccessKey ID
// 运行示例前必须先配置环境变量
// 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html。
// 如果您用的是RAM用户的AccessKey,还需要为RAM用户授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html。
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行示例前必须先配置环境变量。
accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
// 初始化配置对象 &openapi.Config。Config对象存放AccessKeyId、AccessKeySecret、Endpoint等配置。
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret)
}
// 访问的域名
config.Endpoint = tea.String("imageseg.cn-shanghai.aliyuncs.com")
client, err := imageseg20191230.NewClient(config)
if err != nil {
panic(err)
}
// 场景一,使用本地文件
//file, err := os.Open("/tmp/SegmentBody.png")
//if err != nil {
// fmt.Println("can not open file", err)
// panic(err)
//}
//segmentBodyAdvanceRequest := &imageseg20191230.SegmentBodyAdvanceRequest{
// ImageURLObject: file,
//}
// 场景二,使用任意可访问的url
httpClient := http.Client{}
file, _ := httpClient.Get("https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody9.png")
segmentBodyAdvanceRequest := &imageseg20191230.SegmentBodyAdvanceRequest{
ImageURLObject: file.Body,
}
runtime := &util.RuntimeOptions{}
segmentBodyAdvanceResponse, err := client.SegmentBodyAdvance(segmentBodyAdvanceRequest, runtime)
if err != nil {
// 获取整体报错信息
fmt.Println(err.Error())
} else {
// 获取整体结果
fmt.Println(segmentBodyAdvanceResponse)
}
}
// 安装依赖包
// dotnet add package AlibabaCloud.SDK.Imageseg20191230
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Imageseg20191230.Models;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* 使用AK&SK初始化账号Client
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Imageseg20191230.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = accessKeyId,
AccessKeySecret = accessKeySecret,
};
// 访问的域名
config.Endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new AlibabaCloud.SDK.Imageseg20191230.Client(config);
}
public static void Main(string[] args)
{
// 创建AccessKey ID和AccessKey Secret,请参考https://help.aliyun.com/document_detail/175144.html
// 如果您使用的是RAM用户的AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html
// 从环境变量读取配置的AccessKey ID和AccessKey Secret。运行代码示例前必须先配置环境变量。
AlibabaCloud.SDK.Imageseg20191230.Client client = CreateClient(System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
AlibabaCloud.SDK.Imageseg20191230.Models.SegmentBodyAdvanceRequest segmentBodyAdvanceRequest = new AlibabaCloud.SDK.Imageseg20191230.Models.SegmentBodyAdvanceRequest
();
// 场景一,使用本地文件
System.IO.StreamReader file = new System.IO.StreamReader(@"/tmp/SegmentBody1.png");
segmentBodyAdvanceRequest.ImageURLObject = file.BaseStream;
// 场景二,使用任意可访问的url
//HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://viapi-test-bj.oss-cn-beijing.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody9.png");
//WebResponse response = request.GetResponse();
//Stream stream = response.GetResponseStream();
//segmentBodyAdvanceRequest.ImageURLObject = stream;
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
AlibabaCloud.SDK.Imageseg20191230.Models.SegmentBodyResponse SegmentBodyResponse = client.SegmentBodyAdvance(segmentBodyAdvanceRequest, runtime);
// 获取整体结果
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(SegmentBodyResponse.Body));
// 获取单个字段
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(SegmentBodyResponse.Body.Data));
}
catch (TeaException error)
{
// 如有需要,请打印 error
Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// 如有需要,请打印 error
Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
}
}
}
}
常见的处理后结果
证件照制作
调用人体分割之后可以拿到人体与背景分割后的前景人体图(4通道),可以结合人脸检测与五官定位与红、白、蓝背景融合制作证件照。具体操作步骤如下:
调用人脸检测与五官定位SDK获取人脸105关键点信息。
通过分割SDK获取分割png图。
根据人脸关键点进行人脸对齐,返回旋转后图像、面部中心点、旋转角度、旋转后新的landmarks值。
输入旋转后图片、预期的证件照分辨率、landmarks、背景色,返回半身像结果。
证件照背景色替换。
此处以python为例进行说明。
安装相关依赖
pip install alibabacloud_facebody20191230 pip install opencv-python pip install oss2 pip install aliyun-python-sdk-viapiutils pip install viapi-utils
完整代码如下
import argparse import math import cv2 from typing import List import numpy as np from alibabacloud_imageseg20191230.client import Client as imageseg20191230Client from alibabacloud_facebody20191230.client import Client as facebody20191230Client from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_facebody20191230 import models as facebody_20191230_models from alibabacloud_imageseg20191230 import models as imageseg_20191230_models from alibabacloud_tea_util import models as util_models from alibabacloud_tea_util.client import Client as UtilClient from viapi.fileutils import FileUtils import urllib.request class Sample: def __init__(self): pass @staticmethod def create_client( access_key_id: str, access_key_secret: str, ) -> (imageseg20191230Client, facebody20191230Client): """ 使用AK&SK初始化账号Client @param access_key_id: @param access_key_secret: @return: Client @throws Exception """ seg_config = open_api_models.Config( # 您的 AccessKey ID, access_key_id=access_key_id, # 您的 AccessKey Secret, access_key_secret=access_key_secret ) face_config = open_api_models.Config( # 您的 AccessKey ID, access_key_id=access_key_id, # 您的 AccessKey Secret, access_key_secret=access_key_secret ) # 访问的域名 seg_config.endpoint = f'imageseg.cn-shanghai.aliyuncs.com' face_config.endpoint = f'facebody.cn-shanghai.aliyuncs.com' return (imageseg20191230Client(seg_config), facebody20191230Client(face_config)) def id_pohto_demo( args: List[str], ) -> None: assert (args is not None and len(args.param) > 2), "parameters wrong, use -h for details!" [sc_file, color, of_file] = [i for i in args.param] # set id photo size size = [295, 413] # client init seg_client, face_client = Sample.create_client(args.access_key_id, args.access_key_secret) # generation source image url input_url = generate_url(sc_file, args.access_key_id, args.access_key_secret) # init segment_body_request segment_body_request = imageseg_20191230_models.SegmentBodyRequest( image_url=input_url ) # init detect_face_request detect_face_request = facebody_20191230_models.DetectFaceRequest( image_url=input_url ) runtime = util_models.RuntimeOptions() try: # 通过人脸SDK获取人脸105关键点信息 face_result = face_client.detect_face_with_options(detect_face_request, runtime) landmarks = face_result.body.data.landmarks landmarks = np.array(landmarks) # 通过分割SDK获取分割png图 seg_result = seg_client.segment_body_with_options(segment_body_request, runtime) print(seg_result.body.data.image_url) rqt = urllib.request.urlopen(seg_result.body.data.image_url) seg_img = np.asarray(bytearray(rqt.read()), dtype="uint8") seg_img = cv2.imdecode(seg_img, cv2.IMREAD_UNCHANGED) # 根据人脸关键点进行人脸对齐,返回旋转后图像、面部中心点、旋转角度、旋转后新的landmarks值 rotated_img, eye_center, angle, landmarks = align_face(seg_img, landmarks) # 输入旋转后图片、预期的证件照分辨率、landmarks、背景色,返回半身像结果 png_img = corp_halfbody(rotated_img, landmarks, size) # 证件照背景色替换 colors = {'red': (0, 0, 255, 255), 'blue': (255, 0, 0, 255), 'white': (255, 255, 255, 255)} if type(color) is str: color = colors[color] rst_img = np.zeros((size[1], size[0], 3)) + color[0:3] rst_img = image_merge_background(png_img[:, :, 0:3], png_img, rst_img) # 保存结果到本地 cv2.imwrite(of_file, rst_img) except Exception as error: print(error.message) # 如有需要,请打印 error UtilClient.assert_as_string(error.message) def align_face(image_array, landmarks): """ align faces according to eyes position :param image_array: numpy array of a single image :param landmarks: dict of landmarks for facial parts as keys and tuple of coordinates as values :return: rotated_img: numpy array of aligned image eye_center: tuple of coordinates for eye center angle: degrees of rotation """ landmarks = np.resize(landmarks, (105, 2)) # get list landmarks of left and right eye left_eye = landmarks[24:39] right_eye = landmarks[40:55] left_eye_center = np.mean(left_eye, axis=0).astype("int32") right_eye_center = np.mean(right_eye, axis=0).astype("int32") dy = right_eye_center[1] - left_eye_center[1] dx = right_eye_center[0] - left_eye_center[0] angle = math.atan2(dy, dx) * 180. / math.pi # calculate the center of 2 eyes eye_center = (int(left_eye_center[0] + right_eye_center[0]) // 2, int(left_eye_center[1] + right_eye_center[1]) // 2) # at the eye_center, rotate the image by the angle rotate_matrix = cv2.getRotationMatrix2D(eye_center, angle, scale=1) rotated_img = cv2.warpAffine(image_array, rotate_matrix, (image_array.shape[1], image_array.shape[0])) rotated_landmarks = [] for landmark in landmarks: rotated_landmark = rotate(origin=eye_center, point=landmark, angle=angle, row=image_array.shape[0]) rotated_landmarks.append(rotated_landmark) return rotated_img, eye_center, angle, rotated_landmarks def rotate(origin, point, angle, row): """ rotate coordinates in image coordinate system :param origin: tuple of coordinates,the rotation center :param point: tuple of coordinates, points to rotate :param angle: degrees of rotation :param row: row size of the image :return: rotated coordinates of point """ x1, y1 = point x2, y2 = origin y1 = row - y1 y2 = row - y2 angle = math.radians(angle) x = x2 + math.cos(angle) * (x1 - x2) - math.sin(angle) * (y1 - y2) y = y2 + math.sin(angle) * (x1 - x2) + math.cos(angle) * (y1 - y2) y = row - y return int(x), int(y) def corp_halfbody(image_array, landmarks, size): """ crop face according to eye,mouth and chin position :param image_array: numpy array of a single image :param size: single int value, size for w and h after crop :param landmarks: dict of landmarks for facial parts as keys and tuple of coordinates as values :return: cropped_img: numpy array of cropped image left, top: left and top coordinates of cropping """ crop_size = [0, 0, size[1], size[0]] scal = size[1] / 4 / abs(landmarks[98][1] - landmarks[56][1]) image = cv2.resize(image_array, np.multiply((image_array.shape[0:2])[::-1], scal).astype(int)) landmarks = np.multiply(np.array(landmarks), scal) x_center = landmarks[98][0] crop_size[0:2] = [x_center - size[0] / 2, x_center + size[0] / 2] y_center = (landmarks[98][1] + landmarks[56][1]) / 2 crop_size[2:4] = [y_center - size[1] / 2, y_center + size[1] / 2] left, right, top, bottom = [round(i) for i in crop_size] left = max(0, left) top = max(0, top) right = min(image.shape[1], right) bottom = min(image.shape[0], bottom) cropped_img = image[top:bottom, left:right] left, right, top, bottom = [round(i) for i in crop_size] bottom = size[1] top = size[1] - cropped_img.shape[0] left = -min(0, left) right = min(cropped_img.shape[1] + left, size[0]) png_img = np.zeros((size[1], size[0], 4)) png_img[top:bottom, left:right] = cropped_img[:, :] return png_img def image_merge_background(sc_image, png_image, bg_image): """ merge foreground to background image :param sc_image: numpy array of the source image :param png_image: numpy array of the segmented result with same size of sc_image :param bg_image: numpy array of the background image with same size of sc_image :return: rst_image: numpy array of merged image """ assert (sc_image is not None and png_image is not None and bg_image is not None), "read image input error!" h, w, c = sc_image.shape # keep sc_image, png_image and bg_image same size viapi_image = cv2.resize(png_image, (w, h)) bg_image = cv2.resize(bg_image, (w, h)) if len(viapi_image.shape) == 2: mask = viapi_image[:, :, np.newaxis] elif viapi_image.shape[2] == 4: mask = viapi_image[:, :, 3:4] elif viapi_image.shape[2] == 3: mask = viapi_image[:, :, 0:1] else: raise Exception("invalid image mask!") mask = mask / 255.0 # merge background sc_image = sc_image.astype(float) bg_image = bg_image.astype(float) rst_image = (sc_image - bg_image) * mask + bg_image rst_image = np.clip(rst_image, 0, 255) return rst_image # see https://help.aliyun.com/document_detail/155645.html for more detail def generate_url(image_path, access_key_id, access_key_secret): file_utils = FileUtils(access_key_id, access_key_secret) oss_url = file_utils.get_oss_url(image_path, "jpeg", True) return oss_url def define_options(): parser = argparse.ArgumentParser(description='Human segmentation examples.') parser.add_argument('-i', '--access_key_id', default="", help="oss access key id") parser.add_argument('-s', '--access_key_secret', default="", help="access key secret") parser.add_argument('-p', '--param', nargs=3 , default=['./data/source.jpeg', 'red', 'result.jpg'] , type=str , help=('source_image_path background_color[red blue white] result_path')) args = parser.parse_args() return args if __name__ == '__main__': args = define_options() id_pohto_demo(args)
原图:
与红背景融合后的证件照图:
证件照的相关代码,请参见idcard。
说明代码解压后运行python idcard.py -i YOUR_ACCESS_KEY_ID -s YOUR_ACCESS_KEY_SECRET即可,其中
YOUR_ACCESS_KEY_ID
、YOUR_ACCESS_KEY_SECRET
生成操作,请参见创建AccessKey。如果您使用的是子账号AccessKey,您需要给子账号赋予AliyunVIAPIFullAccess权限,具体操作,请参见使用RAM授权。您的账号还需要开通分割抠图服务和人脸人体服务,若未开通服务请立即开通分割抠图服务和立即开通人脸人体服务。