This document provides sample code in several programming languages to demonstrate common use cases for Human Body Segmentation.
For live support, visit Contact Us.
For inquiries about API integration, usage, or other topics related to the Vision AI Open Platform, join our DingTalk group (ID: 23109592).
Overview
For details about the Human Body Segmentation feature and its parameters, see Human Body Segmentation.
Install the SDK package
For SDK dependencies for common programming languages, see SDK Overview.
Configure environment variables
Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
An Alibaba Cloud account has full access to all API operations. We recommend that you use a RAM user for API calls or routine O&M. For more information, see Create a RAM user.
Do not save your AccessKey ID or AccessKey Secret in project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
Configure environment variables on Linux and macOS
Open a terminal in IntelliJ IDEA.
Run the following commands to configure the environment variables.
Replace
<access_key_id>with the AccessKey ID of your RAM user and<access_key_secret>with the AccessKey Secret of your RAM user. If you need to configure more permissions, see Control access permissions using a RAM policy.export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
Configure environment variables on Windows
Create a new environment variable file, add the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared. Then, restart the Windows operating system. The following example uses Windows 10.Open File Explorer, right-click This PC, and then select Properties.
In the left-side navigation pane, click Advanced system settings.
On the Advanced tab of the System Properties dialog box, click Environment Variables.
In the Environment Variables dialog box, click New.
In the New System Variable dialog box, add the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.Restart the Windows operating system for the configurations to take effect.
Code examples
Image from an OSS bucket (Shanghai)
/*
Add the dependency
<!-- 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 {
/*
Initializes the configuration object com.aliyun.teaopenapi.models.Config,
which stores configurations such as your AccessKey ID, AccessKey Secret, and endpoint.
*/
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// The endpoint of the service.
config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new com.aliyun.imageseg20191230.Client(config);
}
public static void main(String[] args_) throws Exception {
// For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
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);
// Get the complete result.
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(segmentBodyResponse)));
// Get a specific field.
System.out.println(segmentBodyResponse.getBody().getData().getImageURL());
} catch (TeaException teaException) {
// Get the complete error message.
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
// Get a specific field.
System.out.println(teaException.getCode());
}
}
}# -*- coding: utf-8 -*-
# Add the dependency.
# 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
# Initialize Config.
config = Config(
# For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
# If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
# Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
# The endpoint of the service.
endpoint='imageseg.cn-shanghai.aliyuncs.com',
# The region that corresponds to the endpoint.
region_id='cn-shanghai'
)
request = SegmentBodyRequest(
image_url='https://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody_IDCard.jpeg',
# Settings for the ReturnForm parameter:
# Specifies the format of the returned image.
# If set to 'mask', a single-channel black-and-white image is returned.
# If set to 'crop', a four-channel PNG image is returned after the blank edges are cropped.
# If set to 'whiteBK', an image with a white background is returned.
# If this parameter is not specified, a four-channel PNG image is returned by default.
return_form='mask'
)
# Initialize RuntimeOptions.
runtime_option = RuntimeOptions()
try:
# Initialize the client.
client = Client(config)
response = client.segment_body_with_options(request, runtime_option)
# Get the complete result.
print(response.body)
except Exception as error:
# Get the complete error message.
print(error)
# Get a specific field.
print(error.code)
# Tip: You can view attribute names by using error.__dict__.<?php
// Install the dependency.
// 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 {
/**
* Use an AccessKey pair to initialize the client.
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Imageseg Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
// Initializes the configuration object Darabonba\OpenApi\Models\Config,
// which stores configurations such as your accessKeyId, accessKeySecret, and endpoint.
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret
]);
// The endpoint of the service.
$config->endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new Imageseg($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
// For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
$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);
# Get the complete result.
echo Utils::toJSONString($resp->body);
} catch (Exception $exception) {
# Get the complete error message.
echo Utils::toJSONString($exception);
# Get a specific field.
echo $exception->getCode();
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
// $argv is a reserved array for input parameters and does not need to be modified.
SegmentBody::main(array_slice($argv, 1));// Install the dependency.
// 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({
// For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// The endpoint of the service.
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) {
// Get the complete result.
console.log(segmentBodyRequestResponse);
// Get a specific field.
console.log(segmentBodyRequestResponse.body.data);
}, function(error) {
// Get the complete error message.
console.log(error);
// Get a specific field.
console.log(error.data.Code);
})/**
Depends on github.com/alibabacloud-go/imageseg-20191230/v2.
We recommend using 'go mod tidy' to install dependencies.
*/
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"
"os"
)
func main() {
// For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
// Initializes the configuration object &openapi.Config, which stores configurations such as AccessKey ID, AccessKey Secret, and endpoint.
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret)
}
// The endpoint of the service.
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 {
// Get the complete error message.
fmt.Println(err.Error())
} else {
// Get the complete result.
fmt.Println(segmentBodyResponse)
}
}// Install the dependency.
// 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
{
/**
* Use an AccessKey pair to initialize the 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,
};
// The endpoint of the service.
config.Endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new AlibabaCloud.SDK.Imageseg20191230.Client(config);
}
public static void Main(string[] args)
{
// For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
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);
// Get the complete result.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentBodyResponse.Body));
// Get a specific field.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentBodyResponse.Body.Data));
}
catch (TeaException error)
{
// Print the error message.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Print the error message.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
}
}
}
}Image from a local file or URL
/*
Add the dependency
<!-- 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 {
/*
Initializes the configuration object com.aliyun.teaopenapi.models.Config,
which stores configurations such as your AccessKey ID, AccessKey Secret, and endpoint.
*/
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// The endpoint of the service.
config.endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new com.aliyun.imageseg20191230.Client(config);
}
public static void main(String[] args_) throws Exception {
// For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
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);
// Scenario 1: Use a local file.
// InputStream inputStream = new FileInputStream(new File("/tmp/detectVideoShot.mp4"));
// Scenario 2: Use a publicly accessible URL.
URL url = new URL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.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);
// Get the complete result.
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(segmentBodyResponse)));
// Get a specific field.
System.out.println(segmentBodyResponse.getBody().getData().getImageURL());
} catch (TeaException teaException) {
// Get the complete error message.
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
// Get a specific field.
System.out.println(teaException.getCode());
}
}
}# -*- coding: utf-8 -*-
# Add the dependency.
# 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
# Initialize Config.
config = Config(
# For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
# If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
# Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
# The endpoint of the service.
endpoint='imageseg.cn-shanghai.aliyuncs.com',
# The region that corresponds to the endpoint.
region_id='cn-shanghai'
)
request = SegmentBodyAdvanceRequest()
# Scenario 1: Use a local file.
#stream = open(r'/tmp/SegmentBody9.png', 'rb')
#request.image_urlobject = stream
# Scenario 2: Use a publicly accessible URL.
url = 'http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.png'
img = urlopen(url).read()
request.image_urlobject = io.BytesIO(img)
request.return_form = 'mask'
runtime_option = RuntimeOptions()
try:
# Initialize the client.
client = Client(config)
response = client.segment_body_advance(request, runtime_option)
# Get the complete result.
print(response.body)
except Exception as error:
# Get the complete error message.
print(error)
# Get a specific field.
print(error.code)
# Tip: You can view attribute names by using error.__dict__.
# Close the stream.
#stream.close()<?php
// Install the dependency.
//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 {
/**
* Use an AccessKey pair to initialize the client.
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Imageseg Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
// Initializes the configuration object Darabonba\OpenApi\Models\Config,
// which stores configurations such as your accessKeyId, accessKeySecret, and endpoint.
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret
]);
// The endpoint of the service.
$config->endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new Imageseg($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
// For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
$client = self::createClient($accessKeyId, $accessKeySecret);
// Scenario 1: Use a local file.
//$file = fopen('/tmp/SegmentBody9.png', 'rb');
//$stream = new Stream($file);
// Scenario 2: Use a publicly accessible URL.
$file = fopen('http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.png', 'rb');
$stream = new Stream($file);
$segmentBodyAdvanceRequest = new SegmentBodyAdvanceRequest([
"imageURLObject" => $stream,
"returnForm" => "mask"
]);
$runtime = new RuntimeOptions([]);
try {
$resp = $client->segmentBodyAdvance($segmentBodyAdvanceRequest, $runtime);
# Get the complete result.
echo Utils::toJSONString($resp->body);
} catch (Exception $exception) {
# Get the complete error message.
echo Utils::toJSONString($exception);
# Get a specific field.
echo $exception->getCode();
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
// $argv is a reserved array for input parameters and does not need to be modified.
SegmentBodyAdvance::main(array_slice($argv, 1));// Install the dependency.
// 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({
// For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// The endpoint of the service.
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();
// Scenario 1: Use a local file.
// const fileStream = fs.createReadStream('/tmp/SegmentBody1.png');
// segmentBodyAdvanceRequest.imageURLObject = fileStream;
// Scenario 2: Use a publicly accessible URL.
const url = new URL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.png");
const httpClient = (url.protocol == "https:") ? https : http;
const response = await getResponse(httpClient, url);
segmentBodyAdvanceRequest.imageURLObject = response;
let runtime = new TeaUtil.RuntimeOptions({ });
client.segmentBodyAdvance(segmentBodyAdvanceRequest, runtime)
.then(function(segmentBodyResponse) {
// Get the complete result.
console.log(segmentBodyResponse);
// Get a specific field.
console.log(segmentBodyResponse.body.data);
}, function(error) {
// Get the complete error message.
console.log(error);
// Get a specific field.
console.log(error.data.Code);
})
} catch (error) {
console.log(error);
}
}();/**
Depends on github.com/alibabacloud-go/imageseg-20191230/v2.
We recommend using 'go mod tidy' to install dependencies.
*/
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"
"os"
)
func main() {
// For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
// Initializes the configuration object &openapi.Config, which stores configurations such as AccessKey ID, AccessKey Secret, and endpoint.
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret)
}
// The endpoint of the service.
config.Endpoint = tea.String("imageseg.cn-shanghai.aliyuncs.com")
client, err := imageseg20191230.NewClient(config)
if err != nil {
panic(err)
}
// Scenario 1: Use a local file.
//file, err := os.Open("/tmp/SegmentBody.png")
//if err != nil {
// fmt.Println("can not open file", err)
// panic(err)
//}
//segmentBodyAdvanceRequest := &imageseg20191230.SegmentBodyAdvanceRequest{
// ImageURLObject: file,
//}
// Scenario 2: Use a publicly accessible URL.
httpClient := http.Client{}
file, _ := httpClient.Get("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.png")
segmentBodyAdvanceRequest := &imageseg20191230.SegmentBodyAdvanceRequest{
ImageURLObject: file.Body,
}
runtime := &util.RuntimeOptions{}
segmentBodyAdvanceResponse, err := client.SegmentBodyAdvance(segmentBodyAdvanceRequest, runtime)
if err != nil {
// Get the complete error message.
fmt.Println(err.Error())
} else {
// Get the complete result.
fmt.Println(segmentBodyAdvanceResponse)
}
}// Install the dependency.
// dotnet add package AlibabaCloud.SDK.Imageseg20191230
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Imageseg20191230.Models;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Use an AccessKey pair to initialize the 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,
};
// The endpoint of the service.
config.Endpoint = "imageseg.cn-shanghai.aliyuncs.com";
return new AlibabaCloud.SDK.Imageseg20191230.Client(config);
}
public static void Main(string[] args)
{
// For more information about how to create an AccessKey ID and an AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you use an AccessKey of a RAM user, you must grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
// Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
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
();
// Scenario 1: Use a local file.
Stream fileStream = File.OpenRead(@"/tmp/SegmentBody1.png");
segmentBodyAdvanceRequest.ImageURLObject = fileStream;
// Scenario 2: Use a publicly accessible URL.
//HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imageseg/SegmentBody/SegmentBody1.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);
// Get the complete result.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentBodyResponse.Body));
// Get a specific field.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(segmentBodyResponse.Body.Data));
}
catch (TeaException error)
{
// Print the error message.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Print the error message.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
}
}
}
}Common post-processing scenarios
Create ID photos
After calling the Human Body Segmentation API, you receive a four-channel foreground image of the segmented human body. You can then use the Face Detection and Landmark feature to combine this image with a red, white, or blue background to create ID photos. Follow these steps:
-
Call the Face Detection and Landmark SDK to get the 105 facial landmark coordinates.
-
Call the segmentation SDK to get the segmented PNG image.
-
Align the face based on the facial landmarks. This returns the rotated image, the center of the face, the rotation angle, and the new landmark coordinates after rotation.
-
Provide the rotated image, the desired ID photo resolution, the landmarks, and the background color to generate a half-body portrait.
-
Replace the background of the ID photo.
The following example uses Python.
-
Install the required dependencies.
pip install alibabacloud_facebody20191230 pip install opencv-python pip install oss2 pip install aliyun-python-sdk-viapiutils pip install viapi-utils -
The following example shows the complete code:
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): """ Use an AccessKey pair to initialize the client. @param access_key_id: @param access_key_secret: @return: Client @throws Exception """ seg_config = open_api_models.Config( # Your AccessKey ID access_key_id=access_key_id, # Your AccessKey Secret access_key_secret=access_key_secret ) face_config = open_api_models.Config( # Your AccessKey ID access_key_id=access_key_id, # Your AccessKey Secret access_key_secret=access_key_secret ) # The endpoint of the service. 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_photo_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 the ID photo size. size = [295, 413] # Initialize the clients. seg_client, face_client = Sample.create_client(args.access_key_id, args.access_key_secret) # Generate the source image URL. input_url = generate_url(sc_file, args.access_key_id, args.access_key_secret) # Initialize the segment_body_request. segment_body_request = imageseg_20191230_models.SegmentBodyRequest( image_url=input_url ) # Initialize the detect_face_request. detect_face_request = facebody_20191230_models.DetectFaceRequest( image_url=input_url ) runtime = util_models.RuntimeOptions() try: # Use the Face SDK to get the 105 facial landmark coordinates. face_result = face_client.detect_face_with_options(detect_face_request, runtime) landmarks = face_result.body.data.landmarks landmarks = np.array(landmarks) # Use the segmentation SDK to get the segmented PNG image. 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) # Align the face based on the facial landmarks. This returns the rotated image, the center of the face, the rotation angle, and the new landmark values after rotation. rotated_img, eye_center, angle, landmarks = align_face(seg_img, landmarks) # Provide the rotated image, the desired ID photo resolution, the landmarks, and the background color to generate a half-body portrait. png_img = crop_halfbody(rotated_img, landmarks, size) # Replace the background color of the ID photo. 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) # Save the result to a local file. cv2.imwrite(of_file, rst_img) except Exception as error: print(error.message) # If necessary, print the error. UtilClient.assert_as_string(error.message) def align_face(image_array, landmarks): """ Align the face based on the position of the eyes. :param image_array: NumPy array of a single image. :param landmarks: A dictionary where keys are facial parts and values are coordinate tuples. :return: rotated_img: NumPy array of the aligned image. eye_center: Tuple of coordinates for the eye center. angle: Degrees of rotation. """ landmarks = np.resize(landmarks, (105, 2)) # Get a list of landmarks for the left and right eyes. 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 the two 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 calculated 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 an image coordinate system. :param origin: A tuple of coordinates for the rotation center. :param point: A tuple of coordinates for the point to rotate. :param angle: Degrees of rotation. :param row: Row size of the image. :return: Rotated coordinates of the 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 crop_halfbody(image_array, landmarks, size): """ Crop the face based on the position of the eyes, mouth, and chin. :param image_array: NumPy array of a single image. :param size: An integer for the width and height after cropping. :param landmarks: A dictionary where keys are facial parts and values are coordinate tuples. :return: cropped_img: NumPy array of the cropped image. left, top: The left and top coordinates of the crop. """ 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 a foreground image onto a background image. :param sc_image: NumPy array of the source image. :param png_image: NumPy array of the segmented result with the same size as sc_image. :param bg_image: NumPy array of the background image with the same size as sc_image. :return: rst_image: NumPy array of the 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 # Ensure sc_image, png_image, and bg_image are the 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 the 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 # For more information, see https://help.aliyun.com/document_detail/155645.html. 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_photo_demo(args)Original image:

ID photo with a red background:

For the complete code for creating ID photos, see idcard.
Note-
After you decompress the code package, run python idcard.py -i YOUR_ACCESS_KEY_ID -s YOUR_ACCESS_KEY_SECRET. Replace
YOUR_ACCESS_KEY_IDandYOUR_ACCESS_KEY_SECRETwith your credentials. To create credentials, see Create an AccessKey. If you use the AccessKey of a RAM user, you must grant theAliyunVIAPIFullAccesspermission to the RAM user. For authorization instructions, see Authorize a RAM user. -
Ensure that the Image Segmentation service and the Face and Body service are activated for your account. If they are not, proceed to activate the Image Segmentation service and activate the Face and Body service now.
-