1:1 face comparison determines if two images contain the same person by comparing the largest face in each. This topic provides sample code in several popular programming languages.
-
For real-time assistance, start an online consultation.
-
If you have questions about API access or usage for the Alibaba Cloud Vision AI Platform, join our DingTalk group (ID: 23109592) to contact us.
Overview
For a functional overview and detailed parameter descriptions, see 1:1 face comparison.
SDK installation
For SDK package dependencies, 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.
Sample code
OSS files in Shanghai
/*
Import the required dependency package.
The minimum required SDK version for facebody20191230 is 3.0.7.
You can find the latest SDK version in this repository: https://mvnrepository.com/artifact/com.aliyun/facebody20191230
<!-- https://mvnrepository.com/artifact/com.aliyun/facebody20191230 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>facebody20191230</artifactId>
<version>${aliyun.facebody.version}</version>
</dependency>
*/
import com.aliyun.facebody20191230.models.CompareFaceResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
public class CompareFace {
public static com.aliyun.facebody20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
Initialize the configuration object com.aliyun.teaopenapi.models.Config.
The Config object stores configuration parameters such as AccessKeyId, AccessKeySecret, 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 = "facebody.cn-shanghai.aliyuncs.com";
return new com.aliyun.facebody20191230.Client(config);
}
public static void main(String[] args_) throws Exception {
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using the 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.facebody20191230.Client client = CompareFace.createClient(accessKeyId, accessKeySecret);
com.aliyun.facebody20191230.models.CompareFaceRequest compareFaceRequest = new com.aliyun.facebody20191230.models.CompareFaceRequest()
.setImageURLA("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-right1.png")
.setImageURLB("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left1.png");
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Print the API response.
CompareFaceResponse compareFaceResponse = client.compareFaceWithOptions(compareFaceRequest, runtime);
// Obtain the full response.
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(compareFaceResponse)));
} catch (TeaException teaException) {
// Obtain the full error message.
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
// Obtain a specific field.
System.out.println(teaException.getCode());
}
}
}# -*- coding: utf-8 -*-
# Import the required dependency package.
# The minimum required SDK version for facebody20191230 is 4.0.8.
# You can find the latest SDK version in this repository: https://pypi.org/project/alibabacloud-facebody20191230/
# pip install alibabacloud_facebody20191230
import os
from alibabacloud_facebody20191230.client import Client
from alibabacloud_facebody20191230.models import CompareFaceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
config = Config(
# For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
# If you are using the 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='facebody.cn-shanghai.aliyuncs.com',
# The ID of the region where the endpoint is located.
region_id='cn-shanghai'
)
compare_face_request = CompareFaceRequest(
image_urla='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-right1.png',
image_urlb='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left1.png'
)
runtime_option = RuntimeOptions()
try:
# Initialize the client.
client = Client(config)
response = client.compare_face_with_options(compare_face_request, runtime_option)
# Obtain the full response.
print(response.body)
except Exception as error:
# Obtain the full error message.
print(error)
# Obtain a specific field.
print(error.code)
# Tip: You can view attribute names by using error.__dict__.<?php
// Install the dependency package.
// composer require alibabacloud/facebody-20191230
// The minimum required SDK version for facebody-20191230 is 3.0.8.
// You can find the latest SDK version in this repository: https://packagist.org/packages/alibabacloud/facebody-20191230
use AlibabaCloud\SDK\Facebody\V20191230\Facebody;
use AlibabaCloud\Tea\Utils\Utils;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Facebody\V20191230\Models\CompareFaceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
class CompareFace {
/**
* Initialize the client with an AccessKey pair.
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Facebody Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
// Initialize the configuration object Darabonba\OpenApi\Models\Config.
// The Config object stores configuration parameters such as accessKeyId, accessKeySecret, and endpoint.
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret
]);
// The endpoint of the service.
$config->endpoint = "facebody.cn-shanghai.aliyuncs.com";
return new Facebody($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using the 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);
$compareFaceRequest = new CompareFaceRequest([
"imageURLA" => "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-right1.png",
"imageURLB" => "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left1.png"
]);
$runtime = new RuntimeOptions([]);
try {
$resp = $client->compareFaceWithOptions($compareFaceRequest, $runtime);
# Obtain the full response.
echo Utils::toJSONString($resp->body);
} catch (Exception $exception) {
# Obtain the full error message.
echo Utils::toJSONString($exception);
# Obtain a specific field.
echo $exception->getCode();
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
// The $argv parameter is reserved and does not require modification.
CompareFace::main(array_slice($argv, 1));// Install the dependency package.
// npm install @alicloud/facebody20191230
// The minimum required SDK version for facebody20191230 is 4.0.7.
// You can find the latest SDK version in this repository: https://npmjs.com/package/@alicloud/facebody20191230
const FacebodyClient = require('@alicloud/facebody20191230');
const OpenapiClient = require('@alicloud/openapi-client');
const TeaUtil = require('@alicloud/tea-util');
let config = new OpenapiClient.Config({
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using the 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 = `facebody.cn-shanghai.aliyuncs.com`;
const client = new FacebodyClient.default(config);
let compareFaceRequest = new FacebodyClient.CompareFaceRequest({
imageURLA: "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-right1.png",
imageURLB: "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left1.png",
});
let runtime = new TeaUtil.RuntimeOptions({ });
client.compareFaceWithOptions(compareFaceRequest, runtime)
.then(function(compareFaceResponse) {
// Obtain the full response.
console.log(compareFaceResponse);
// Obtain a specific field.
console.log(compareFaceResponse.body.data);
}, function(error) {
// Obtain the full error message.
console.log(error);
// Obtain a specific field.
console.log(error.data.Code);
})/**
The minimum required SDK version for facebody-20191230 is 4.0.7.
You can find the latest SDK version in this repository: https://pkg.go.dev/github.com/alibabacloud-go/facebody-20191230/v4
Dependency: github.com/alibabacloud-go/facebody-20191230
We recommend using 'go mod tidy' to install dependencies.
*/
package main
import (
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
facebody20191230 "github.com/alibabacloud-go/facebody-20191230/v4/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
func main() {
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using the 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")
// Initialize the configuration object &openapi.Config. The Config object stores configuration parameters such as AccessKeyId, AccessKeySecret, and endpoint.
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret)
}
// The endpoint of the service.
config.Endpoint = tea.String("facebody.cn-shanghai.aliyuncs.com")
client, err := facebody20191230.NewClient(config)
if err != nil {
panic(err)
}
compareFaceRequest := &facebody20191230.CompareFaceRequest{
ImageURLA: tea.String("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-right1.png"),
ImageURLB: tea.String("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left1.png"),
}
runtime := &util.RuntimeOptions{}
compareFaceResponse, err := client.CompareFaceWithOptions(compareFaceRequest, runtime)
if err != nil {
// Obtain the full error message.
fmt.Println(err.Error())
} else {
// Obtain the full response.
fmt.Println(compareFaceResponse)
}
}// Install the dependency.
// dotnet add package AlibabaCloud.SDK.Facebody20191230
// The minimum required SDK version for facebody20191230 is 3.0.7.
// You can find the latest SDK version in this repository: https://nuget.org/packages/AlibabaCloud.SDK.Facebody20191230
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Facebody20191230.Models;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Initialize the client with an AccessKey pair.
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Facebody20191230.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 = "facebody.cn-shanghai.aliyuncs.com";
return new AlibabaCloud.SDK.Facebody20191230.Client(config);
}
public static void Main(string[] args)
{
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using the 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.Facebody20191230.Client client = CreateClient(System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
AlibabaCloud.SDK.Facebody20191230.Models.CompareFaceRequest compareFaceRequest = new AlibabaCloud.SDK.Facebody20191230.Models.CompareFaceRequest
{
ImageURLA = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-right1.png",
ImageURLB = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left1.png",
};
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
AlibabaCloud.SDK.Facebody20191230.Models.CompareFaceResponse compareFaceResponse = client.CompareFaceWithOptions(compareFaceRequest, runtime);
// Obtain the full response.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(compareFaceResponse.Body));
// Obtain a specific field.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(compareFaceResponse.Body.Data));
}
catch (TeaException error)
{
// Obtain the full error message.
Console.WriteLine(error.Message);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Obtain the full error message.
Console.WriteLine(error.Message);
}
}
}
}Local files or URLs
/*
Import the required dependency package.
The minimum required SDK version for facebody20191230 is 3.0.7.
You can find the latest SDK version in this repository: https://mvnrepository.com/artifact/com.aliyun/facebody20191230
<!-- https://mvnrepository.com/artifact/com.aliyun/facebody20191230 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>facebody20191230</artifactId>
<version>${aliyun.facebody.version}</version>
</dependency>
*/
import com.aliyun.facebody20191230.models.CompareFaceResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
public class CompareFace {
public static com.aliyun.facebody20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
/*
Initialize the configuration object com.aliyun.teaopenapi.models.Config.
The Config object stores configuration parameters such as AccessKeyId, AccessKeySecret, 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 = "facebody.cn-shanghai.aliyuncs.com";
return new com.aliyun.facebody20191230.Client(config);
}
public static void main(String[] args_) throws Exception {
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using the 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.facebody20191230.Client client = CompareFace.createClient(accessKeyId, accessKeySecret);
// Scenario 1: Use a local file.
InputStream inputStreamA = new FileInputStream(new File("/tmp/CompareFace-right.png"));
// Scenario 2: Use a publicly accessible URL.
URL url = new URL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left1.png");
InputStream inputStreamB = url.openConnection().getInputStream();
com.aliyun.facebody20191230.models.CompareFaceAdvanceRequest compareFaceAdvanceRequest = new com.aliyun.facebody20191230.models.CompareFaceAdvanceRequest()
.setImageURLAObject(inputStreamA)
.setImageURLBObject(inputStreamB);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
try {
// Print the API response.
CompareFaceResponse compareFaceResponse = client.compareFaceAdvance(compareFaceAdvanceRequest, runtime);
// Obtain the full response.
System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(compareFaceResponse)));
} catch (TeaException teaException) {
// Obtain the full error message.
System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
// Obtain a specific field.
System.out.println(teaException.getCode());
}
}
}# -*- coding: utf-8 -*-
# Import the required dependency package.
# The minimum required SDK version for facebody20191230 is 4.0.8.
# You can find the latest SDK version in this repository: https://pypi.org/project/alibabacloud-facebody20191230/
# pip install alibabacloud_facebody20191230
import os
import io
from urllib.request import urlopen
from alibabacloud_facebody20191230.client import Client
from alibabacloud_facebody20191230.models import CompareFaceAdvanceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
config = Config(
# For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
# If you are using the 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='facebody.cn-shanghai.aliyuncs.com',
# The ID of the region where the endpoint is located.
region_id='cn-shanghai'
)
runtime_option = RuntimeOptions()
compare_face_request = CompareFaceAdvanceRequest()
# Scenario 1: The file is stored locally.
streamA = open(r'/tmp/CompareFace-right.png', 'rb')
compare_face_request.image_urlaobject = streamA
# Scenario 2: Use a publicly accessible URL.
urlB = 'http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left1.png'
imgB = urlopen(urlB).read()
compare_face_request.image_urlbobject = io.BytesIO(imgB)
try:
# Initialize the client.
client = Client(config)
response = client.compare_face_advance(compare_face_request, runtime_option)
# Obtain the full response.
print(response.body)
except Exception as error:
# Obtain the full error message.
print(error)
# Obtain a specific field.
print(error.code)
# Tip: You can view attribute names by using error.__dict__.
# Close the stream.
streamA.close()<?php
// Install the dependency package.
// composer require alibabacloud/facebody-20191230
// The minimum required SDK version for facebody-20191230 is 3.0.8.
// You can find the latest SDK version in this repository: https://packagist.org/packages/alibabacloud/facebody-20191230
use AlibabaCloud\SDK\Facebody\V20191230\Facebody;
use AlibabaCloud\Tea\Utils\Utils;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Facebody\V20191230\Models\CompareFaceAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;
class CompareFaceAdvance {
/**
* Initialize the client with an AccessKey pair.
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Facebody Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
// Initialize the configuration object Darabonba\OpenApi\Models\Config.
// The Config object stores configuration parameters such as accessKeyId, accessKeySecret, and endpoint.
$config = new Config([
"accessKeyId" => $accessKeyId,
"accessKeySecret" => $accessKeySecret
]);
// The endpoint of the service.
$config->endpoint = "facebody.cn-shanghai.aliyuncs.com";
return new Facebody($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($args){
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using the 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.
$fileA = fopen('/tmp/CompareFace-right.png', 'rb');
$streamA = new Stream($fileA);
// Scenario 2: Use a publicly accessible URL.
$fileB = fopen('http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left1.png', 'rb');
$streamB = new Stream($fileB);
$compareFaceAdvanceRequest = new CompareFaceAdvanceRequest([
"imageURLAObject" => $streamA,
"imageURLBObject" => $streamB
]);
$runtime = new RuntimeOptions([]);
try {
$resp = $client->compareFaceAdvance($compareFaceAdvanceRequest, $runtime);
# Obtain the full response.
echo Utils::toJSONString($resp->body);
} catch (Exception $exception) {
# Obtain the full error message.
echo Utils::toJSONString($exception);
# Obtain a specific field.
echo $exception->getCode();
}
}
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
require_once $path;
}
// The $argv parameter is reserved and does not require modification.
CompareFaceAdvance::main(array_slice($argv, 1));// Install the dependency package.
// npm install @alicloud/facebody20191230
// The minimum required SDK version for facebody20191230 is 4.0.7.
// You can find the latest SDK version in this repository: https://npmjs.com/package/@alicloud/facebody20191230
const FacebodyClient = require('@alicloud/facebody20191230');
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 information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using the 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 = `facebody.cn-shanghai.aliyuncs.com`;
const client = new FacebodyClient.default(config);
const getResponse = function (httpClient, url) {
return new Promise((resolve, reject) => {
httpClient.get(url, function (response) {
resolve(response);
})
})
}
const request = async function () {
try {
const compareFaceAdvanceRequest = new FacebodyClient.CompareFaceAdvanceRequest();
// Scenario 1: Use a local file.
const fileStreamA = fs.createReadStream('/tmp/CompareFace-left1.png');
// Scenario 2: Use a publicly accessible URL.
const urlB = new URL('http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-right1.png');
const httpClient = (urlB.protocol == "https:") ? https : http;
compareFaceAdvanceRequest.imageURLAObject = fileStreamA;
compareFaceAdvanceRequest.imageURLBObject = await getResponse(httpClient, urlB);
let runtime = new TeaUtil.RuntimeOptions({});
client.compareFaceAdvance(compareFaceAdvanceRequest, runtime)
.then(function (compareFaceResponse) {
// Obtain the full response.
console.log(compareFaceResponse);
// Obtain a specific field.
console.log(compareFaceResponse.body.data);
}, function (error) {
// Obtain the full error message.
console.log(error);
// Obtain a specific field.
console.log(error.data.Code);
})
} catch (error) {
console.log(error);
}
}();/**
The minimum required SDK version for facebody-20191230 is 4.0.7.
You can find the latest SDK version in this repository: https://pkg.go.dev/github.com/alibabacloud-go/facebody-20191230/v4
Dependency: github.com/alibabacloud-go/facebody-20191230
We recommend using 'go mod tidy' to install dependencies.
*/
package main
import (
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
facebody20191230 "github.com/alibabacloud-go/facebody-20191230/v4/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"net/http"
"os"
)
func main() {
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using the 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")
// Initialize the configuration object &openapi.Config. The Config object stores configuration parameters such as AccessKeyId, AccessKeySecret, and endpoint.
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret)
}
// The endpoint of the service.
config.Endpoint = tea.String("facebody.cn-shanghai.aliyuncs.com")
client, err := facebody20191230.NewClient(config)
if err != nil {
panic(err)
}
// Scenario 1: Use a local file.
file1, err := os.Open("/tmp/CompareFace-right.png")
if err != nil {
fmt.Println("can not open file", err)
panic(err)
}
// Scenario 2: Use a publicly accessible URL.
httpClient := http.Client{}
file2, _ := httpClient.Get("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-left1.png")
compareFaceAdvanceRequest := &facebody20191230.CompareFaceAdvanceRequest{
ImageURLAObject: file1,
ImageURLBObject: file2.Body,
}
runtime := &util.RuntimeOptions{}
compareFaceAdvanceResponse, err := client.CompareFaceAdvance(compareFaceAdvanceRequest, runtime)
if err != nil {
// Obtain the full error message.
fmt.Println(err.Error())
} else {
// Obtain the full response.
fmt.Println(compareFaceAdvanceResponse)
}
}// Install the dependency.
// dotnet add package AlibabaCloud.SDK.Facebody20191230
// The minimum required SDK version for facebody20191230 is 3.0.7.
// You can find the latest SDK version in this repository: https://nuget.org/packages/AlibabaCloud.SDK.Facebody20191230
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Facebody20191230.Models;
using Tea;
using Tea.Utils;
namespace AlibabaCloud.SDK.Sample
{
public class Sample
{
/**
* Initialize the client with an AccessKey pair.
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Facebody20191230.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 = "facebody.cn-shanghai.aliyuncs.com";
return new AlibabaCloud.SDK.Facebody20191230.Client(config);
}
public static void Main(string[] args)
{
// For information about how to create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
// If you are using the 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.Facebody20191230.Client client = CreateClient(System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
AlibabaCloud.SDK.Facebody20191230.Models.CompareFaceAdvanceRequest compareFaceAdvanceRequest = new AlibabaCloud.SDK.Facebody20191230.Models.CompareFaceAdvanceRequest();
// Scenario 1: Use a local file.
System.IO.StreamReader fileA = new System.IO.StreamReader(@"tmp/CompareFace-left1.png");
compareFaceAdvanceRequest.ImageURLAObject = fileA.BaseStream;
// Scenario 2: Use a publicly accessible URL.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/CompareFace/CompareFace-right1.png");
WebResponse response = request.GetResponse();
Stream streamB = response.GetResponseStream();
compareFaceAdvanceRequest.ImageURLBObject = streamB;
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
AlibabaCloud.SDK.Facebody20191230.Models.CompareFaceResponse compareFaceResponse = client.CompareFaceAdvance(compareFaceAdvanceRequest, runtime);
// Obtain the full response.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(compareFaceResponse.Body));
// Obtain a specific field.
Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(compareFaceResponse.Body.Data));
}
catch (TeaException error)
{
// Obtain the full error message.
Console.WriteLine(error.Message);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// Obtain the full error message.
Console.WriteLine(error.Message);
}
}
}
}FAQ
Does 1:1 face comparison support photo capture, liveness detection, or face enrollment?
This API compares two static images (provided as URLs or local file streams) to determine whether they show the same person. It does not support camera scanning, photo capture, or liveness detection gestures such as opening your mouth or turning your head. Image capture and pre-processing must be implemented by the caller.
If your business requires face enrollment, face library management, or 1:N face search, use the other capabilities in Visual Intelligence API, such as the face search feature.
Why do multiple calls with the same photo return different Confidence scores?
The Confidence score can vary across calls because the face-to-image ratio in each submission may differ slightly between requests. To minimize variance, use recent photos and avoid heavily filtered or retouched images that can widen the confidence gap. The underlying feature details and face-to-image ratios are model internals and cannot be retrieved.
Can I modify the Thresholds values returned by the API?
No. The Thresholds values are automatically calculated by the system based on false acceptance rates (for example, 1/1,000 or 1/10,000) and are returned as reference values only. You cannot modify these values directly. Instead, use the Confidence value returned by the API and define your own business threshold based on your accuracy requirements.