本文檔為您介紹人體分割常用語言和常見情況的示例代碼。
您可以進入在線咨詢獲取在線人工幫助。
阿里云視覺智能開放平臺視覺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,請參考http://bestwisewords.com/document_detail/175144.html
// 如果您使用的是RAM用戶的AccessKey,還需要為子賬號授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html。
# 如果您用的是RAM用戶的AccessKey,還需要為RAM用戶授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html。
// 如果您用的是RAM用戶的AccessKey,還需要為RAM用戶授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html。
// 如果您用的是RAM用戶AccessKey,還需要為RAM用戶授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html。
// 如果您用的是RAM用戶的AccessKey,還需要為RAM用戶授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html
// 如果您使用的是RAM用戶的AccessKey,還需要為子賬號授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html
// 如果您使用的是RAM用戶的AccessKey,還需要為子賬號授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html。
# 如果您用的是RAM用戶的AccessKey,還需要為RAM用戶授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html
//如果您是用的子賬號AccessKey,還需要為子賬號授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html。
// 如果您用的是RAM用戶AccessKey,還需要為RAM用戶授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html。
// 如果您用的是RAM用戶的AccessKey,還需要為RAM用戶授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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,請參考http://bestwisewords.com/document_detail/175144.html
// 如果您使用的是RAM用戶的AccessKey,還需要為子賬號授予權限AliyunVIAPIFullAccess,請參考http://bestwisewords.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 http://bestwisewords.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授權。您的賬號還需要開通分割摳圖服務和人臉人體服務,若未開通服務請立即開通分割摳圖服務和立即開通人臉人體服務。