Face detection and facial feature localization

Updated at:

The face detection and facial feature localization capability accurately detects faces in images, providing 105 keypoints and details for each face, including face count, bounding box coordinates, and pose angles. The capability performs reliably under complex conditions such as occlusion, changing light, blur, multiple poses, and noise, making it suitable for photos with multiple faces at various angles. This topic provides sample code in several popular programming languages.

Note
  • 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.

Capability overview

For an overview of the face detection and facial feature localization capability and its request parameters, see Face detection and facial feature localization.

Install the SDK

For information about the SDK dependency packages for popular languages, see SDK overview.

Configure environment variables

Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Important
  • 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

    1. Open a terminal in IntelliJ IDEA.

    2. 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_ID and ALIBABA_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.

    1. Open File Explorer, right-click This PC, and then select Properties.

    2. In the left-side navigation pane, click Advanced system settings.

    3. On the Advanced tab of the System Properties dialog box, click Environment Variables.

    4. In the Environment Variables dialog box, click New.

    5. In the New System Variable dialog box, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.

    6. Restart the Windows operating system for the configurations to take effect.

Sample code

Image from OSS in Shanghai

/*
Import the 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.DetectFaceResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;

public class DetectFace {
    public static com.aliyun.facebody20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        /*
          Initializes the configuration object com.aliyun.teaopenapi.models.Config.
          The Config object 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 service endpoint.
        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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the code.
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); 
        com.aliyun.facebody20191230.Client client = DetectFace.createClient(accessKeyId, accessKeySecret);
        com.aliyun.facebody20191230.models.DetectFaceRequest detectFaceRequest = new com.aliyun.facebody20191230.models.DetectFaceRequest()
                .setImageURL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            DetectFaceResponse detectFaceResponse = client.detectFaceWithOptions(detectFaceRequest, runtime);
            // Get the full response.
            System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(detectFaceResponse)));
        } catch (TeaException teaException) {
            // Get the full error message.
            System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
            // Get a specific field.
            System.out.println(teaException.getCode());
        }
    }
}
# -*- coding: utf-8 -*-
# Import the 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 DetectFaceRequest
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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
  # Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the code.
  access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
  access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
  # The service endpoint.
  endpoint='facebody.cn-shanghai.aliyuncs.com',
  # The region ID that corresponds to the endpoint.
  region_id='cn-shanghai'
)
detect_face_request = DetectFaceRequest(
   image_url='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png',
   landmark=True,
   quality=True,
   max_face_number=2,
   pose=True
)
runtime = RuntimeOptions()
try:
  # Initialize the client.
  client = Client(config)
  response = client.detect_face_with_options(detect_face_request, runtime)
  # Get the full response.
  print(response.body)
except Exception as error:
  # Get the full 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 package.
// 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    
// composer require alibabacloud/facebody-20191230
  
use AlibabaCloud\SDK\Facebody\V20191230\Facebody;
use \Exception;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Facebody\V20191230\Models\DetectFaceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class DetectFace {

    /**
     * Use an AccessKey pair to initialize the client.
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Facebody Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        // Initializes the configuration object Darabonba\OpenApi\Models\Config.
        // The Config object stores configurations such as your accessKeyId, accessKeySecret, and endpoint.
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // The service endpoint.
        $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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the code.
        $accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
        $accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'); 
        $client = self::createClient($accessKeyId, $accessKeySecret);
        $detectFaceRequest = new DetectFaceRequest([
            "imageURL" => "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png",
            "landmark" => true,
            "quality" => true,
            "maxFaceNumber" => 2,
            "pose" => true
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->detectFaceWithOptions($detectFaceRequest, $runtime);
            # Get the full response.
            echo Utils::toJSONString($resp->body);
        } catch (Exception $exception) {
            # Get the full 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;
}
// The $argv array is reserved for input parameters and should not be modified.
DetectFace::main(array_slice($argv, 1));
// Install the dependency package.
// npm install @alicloud/facebody20191230
// The minimum required SDK version for @alicloud/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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
  // Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the code.
  accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,   
  accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// The service endpoint.
config.endpoint = `facebody.cn-shanghai.aliyuncs.com`;
const client = new FacebodyClient.default(config);
let detectFaceRequest = new FacebodyClient.DetectFaceRequest({
  imageURL: "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png",
});
let runtime = new TeaUtil.RuntimeOptions({ });
client.detectFaceWithOptions(detectFaceRequest, runtime)
  .then(function(detectFaceRequestResponse) {
    // Get the full response.
    console.log(detectFaceRequestResponse);
    // Get a specific field.
    console.log(detectFaceRequestResponse.body.data);
  }, function(error) {
    // Get the full error message.
    console.log(error);
    // Get a specific field.
    console.log(error.data.Code);
  })
/**
The minimum required SDK version for alibabacloud-go/facebody-20191230/v4 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
This depends on github.com/alibabacloud-go/facebody-20191230.
We recommend running the `go mod tidy` command to install dependencies.
*/

import (
	"fmt"
	"os"
	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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
  // Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the code.
  accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")  
	accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
  // Initializes the configuration object &openapi.Config. The Config object stores configurations such as your AccessKeyId, AccessKeySecret, and Endpoint.
	config := &openapi.Config{
		AccessKeyId: &accessKeyId,
		AccessKeySecret: &accessKeySecret,
	}
	// The service endpoint.
	config.Endpoint = tea.String("facebody.cn-shanghai.aliyuncs.com")
	client, err := facebody20191230.NewClient(config)
	if err != nil {
		panic(err)
	}
	detectFaceRequest := &facebody20191230.DetectFaceRequest{
		ImageURL: tea.String("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png"),
	}
	runtime := &util.RuntimeOptions{}
	detectFaceResponse, err := client.DetectFaceWithOptions(detectFaceRequest, runtime)
	if err != nil {
		// Get the full error message.
		fmt.Println(err.Error())
	} else {
		// Get the full response.
		fmt.Println(detectFaceResponse)
	}
}
// Install the dependency package.
// 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.Generic;
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.Facebody20191230.Client CreateClient(string accessKeyId, string accessKeySecret)
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
              AccessKeyId = accessKeyId,
              AccessKeySecret = accessKeySecret,
            };
            // The service endpoint.
            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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
            // Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the 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.DetectFaceRequest detectFaceRequest = new AlibabaCloud.SDK.Facebody20191230.Models.DetectFaceRequest
            {
                ImageURL = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png",
            };
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            try
            {
                AlibabaCloud.SDK.Facebody20191230.Models.DetectFaceResponse detectFaceResponse = client.DetectFaceWithOptions(detectFaceRequest, runtime);
                // Get the full response.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(detectFaceResponse.Body));
                // Get a specific field.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(detectFaceResponse.Body.Data));
            }
            catch (TeaException error)
            {
                // Prints the error message if an error occurs.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
              {
                { "message", _error.Message }
              });
                // Prints the error message if an error occurs.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
        }
    }
}

Local file or public URL

/*
Import the 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.DetectFaceResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;
import java.io.FileInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;

public class DetectFace {
    public static com.aliyun.facebody20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        /*
          Initializes the configuration object com.aliyun.teaopenapi.models.Config.
          The Config object 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 service endpoint.
        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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the code.
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); 
        com.aliyun.facebody20191230.Client client = DetectFace.createClient(accessKeyId, accessKeySecret);
        // Scenario 1: Use an image from a local path.
        // InputStream inputStream = new FileInputStream(new File("/tmp/detectFace.png"));
        // Scenario 2: Use an image from a public URL.
        URL url = new URL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png");
        InputStream inputStream = url.openConnection().getInputStream();
        com.aliyun.facebody20191230.models.DetectFaceAdvanceRequest detectFaceAdvanceRequest = new com.aliyun.facebody20191230.models.DetectFaceAdvanceRequest()
                .setImageURLObject(inputStream);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            DetectFaceResponse detectFaceResponse = client.detectFaceAdvance(detectFaceAdvanceRequest, runtime);
            // Get the full response.
            System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(detectFaceResponse)));
        } catch (TeaException teaException) {
            // Get the full error message.
            System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
            // Get a specific field.
            System.out.println(teaException.getCode());
        }
    }
}
# -*- coding: utf-8 -*-
# Import the 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 DetectFaceAdvanceRequest
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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
  # Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the code.
  access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
  access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
  # The service endpoint.
  endpoint='facebody.cn-shanghai.aliyuncs.com',
  # The region ID that corresponds to the endpoint.
  region_id='cn-shanghai'
)
detect_face_request = DetectFaceAdvanceRequest()
# Scenario 1: Use an image from a local path.
# stream = open(r'/tmp/DetectFace1.png', 'rb')
# detect_face_request.image_urlobject = stream

# Scenario 2: Use an image from a public URL.
url = 'http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png'
img = urlopen(url).read()
detect_face_request.image_urlobject = io.BytesIO(img)
detect_face_request.landmark = True
detect_face_request.quality = True
detect_face_request.pose = True
detect_face_request.max_face_number = 2

runtime = RuntimeOptions()
try:
  # Initialize the client.
  client = Client(config)
  response = client.detect_face_advance(detect_face_request, runtime)
  # Get the full response.
  print(response.body)
except Exception as error:
  # Get the full 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 package.
// 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    
// composer require alibabacloud/facebody-20191230
  
use AlibabaCloud\SDK\Facebody\V20191230\Facebody;
use \Exception;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Facebody\V20191230\Models\DetectFaceAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;

class DetectFaceAdvance {

    /**
     * Use an AccessKey pair to initialize the client.
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Facebody Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        // Initializes the configuration object Darabonba\OpenApi\Models\Config.
        // The Config object stores configurations such as your accessKeyId, accessKeySecret, and endpoint.
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // The service endpoint.
        $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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
				// Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the code.
				$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
				$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'); 
        $client = self::createClient($accessKeyId, $accessKeySecret);
        // Scenario 1: Use an image from a local path.
        //$file = fopen('/tmp/DetectFace1.png', 'rb');
        //$stream = new Stream($file);
        // Scenario 2: Use an image from a public URL.
        $file = fopen('http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png', 'rb');
        $stream = new Stream($file);
        $detectFaceAdvanceRequest = new DetectFaceAdvanceRequest([
            "imageURLObject" => $stream,
            "landmark" => true,
            "quality" => true,
            "maxFaceNumber" => 2,
            "pose" => true
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->detectFaceAdvance($detectFaceAdvanceRequest, $runtime);
            # Get the full response.
            echo Utils::toJSONString($resp->body);
        } catch (Exception $exception) {
            # Get the full 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;
}
// The $argv array is reserved for input parameters and should not be modified.
DetectFaceAdvance::main(array_slice($argv, 1));
// Install the dependency package.
// npm install @alicloud/facebody20191230
// The minimum required SDK version for @alicloud/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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
  // Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the code.
  accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,   
  accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// The service endpoint.
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 {
    let detectFaceAdvanceRequest = new FacebodyClient.DetectFaceAdvanceRequest();
    // Scenario 1: Use an image from a local path.
    // const fileStream = fs.createReadStream('/tmp/DetectFace1.png');
    // detectFaceAdvanceRequest.imageURLObject = fileStream;
    // Scenario 2: Use an image from a public URL.
    const url = new URL("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png");
    const httpClient = (url.protocol == "https:") ? https : http;
    detectFaceAdvanceRequest.imageURLObject = await getResponse(httpClient, url);
    let runtime = new TeaUtil.RuntimeOptions({});
    client.detectFaceAdvance(detectFaceAdvanceRequest, runtime)
      .then(function (detectFaceResponse) {
        // Get the full response.
        console.log(detectFaceResponse);
        // Get a specific field.
        console.log(detectFaceResponse.body.data);
      }, function (error) {
        // Get the full error message.
        console.log(error);
        // Get a specific field.
        console.log(error.data.Code);
      })
  } catch (error) {
    console.log(error);
  }
}();
/**
The minimum required SDK version for alibabacloud-go/facebody-20191230/v4 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
This depends on github.com/alibabacloud-go/facebody-20191230.
We recommend running the `go mod tidy` command to install dependencies.
*/

import (
	"fmt"
	"os"
	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"
)

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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
  // Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the code.
  accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")  
  accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
  // Initializes the configuration object &openapi.Config. The Config object stores configurations such as your AccessKeyId, AccessKeySecret, and Endpoint.
	config := &openapi.Config{
		AccessKeyId: &accessKeyId,
		AccessKeySecret: &accessKeySecret,
	}
	// The service endpoint.
	config.Endpoint = tea.String("facebody.cn-shanghai.aliyuncs.com")
	client, err := facebody20191230.NewClient(config)
	if err != nil {
		panic(err)
	}
	// Scenario 1: Use an image from a local path.
	// file, err := os.Open("/tmp/DetectFace.png")
	// if err != nil {
	// 	fmt.Println("cannot open file", err)
	// 	panic(err)
	// }
	// detectFaceAdvanceRequest := &facebody20191230.DetectFaceAdvanceRequest{
	// 	ImageURLObject: file,
	// }
	// Scenario 2: Use an image from a public URL.
	httpClient := http.Client{}
	resp, _ := httpClient.Get("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png")
	detectFaceAdvanceRequest := &facebody20191230.DetectFaceAdvanceRequest{
		ImageURLObject: resp.Body,
	}
	runtime := &util.RuntimeOptions{}
	detectFaceAdvanceResponse, err := client.DetectFaceAdvance(detectFaceAdvanceRequest, runtime)
	if err != nil {
		// Get the full error message.
		fmt.Println(err.Error())
	} else {
		// Get the full response.
		fmt.Println(detectFaceAdvanceResponse)
	}
}
// Install the dependency package.
// 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.Generic;
using System.IO;
using System.Net;
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.Facebody20191230.Client CreateClient(string accessKeyId, string accessKeySecret)
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
              AccessKeyId = accessKeyId,
              AccessKeySecret = accessKeySecret,
            };
            // The service endpoint.
            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 use a RAM user's AccessKey pair, you must grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
            // Reads the AccessKey ID and AccessKey Secret from environment variables. Ensure you have configured these variables before running the 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.DetectFaceAdvanceRequest detectFaceAdvanceRequest = new AlibabaCloud.SDK.Facebody20191230.Models.DetectFaceAdvanceRequest
            ();
            // Scenario 1: Use an image from a local path.
            // System.IO.Stream file = new System.IO.FileStream(@"/tmp/DetectFace1.png", System.IO.FileMode.Open);
            // detectFaceAdvanceRequest.ImageURLObject = file;

            // Scenario 2: Use an image from a public URL.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/facebody/DetectFace/DetectFace1.png");
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            detectFaceAdvanceRequest.ImageURLObject = stream;
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            try
            {
                AlibabaCloud.SDK.Facebody20191230.Models.DetectFaceResponse detectFaceResponse = client.DetectFaceAdvance(detectFaceAdvanceRequest, runtime);
                // Get the full response.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(detectFaceResponse.Body));
                // Get a specific field.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(detectFaceResponse.Body.Data));
            }
            catch (TeaException error)
            {
                // Prints the error message if an error occurs.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
              {
                { "message", _error.Message }
              });
                // Prints the error message if an error occurs.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
        }
    }
}

FAQ

Q: What do the 6 values in the Pupils parameter array represent? How do I get the center coordinates of both pupils?

The Pupils field returns an array of double values. The 6 values correspond to the following in order:

Index

Description

0

Left pupil center X coordinate (left_iris_cenpt.x)

1

Left pupil center Y coordinate (left_iris_cenpt.y)

2

Left pupil radius (left_iris_radius)

3

Right pupil center X coordinate (right_iris_cenpt.x)

4

Right pupil center Y coordinate (right_iris_cenpt.y)

5

Right pupil radius (right_iris_radis)

Q: What should I do if face detection misidentifies hands, emoji stickers, or anime characters as faces?

The algorithm has strong adaptability and may occasionally misdetect objects that share facial features. You can use the following strategies to reduce false detections:

  • Filter by LandmarkScore — Use the LandmarkScore parameter (facial landmark quality score) from the response. Set a threshold of 85 and retain only results where LandmarkScore > 85 to exclude low-confidence detections.

  • Switch to a specialized API — If your use case requires strict real-person verification, consider switching to the liveness detection or financial-grade face detection APIs.

Q: Which face is returned when MaxFaceNumber is set to 1?

When MaxFaceNumber=1, the API returns the face data with the highest score in FaceProbabilityList.

Q: How do I implement camera-based face detection with automatic photo capture on the frontend?

The Alibaba Cloud face detection API is a server-side interface. For frontend camera integration, you have two options:

  • Implement your own trigger logic in the frontend to determine when to capture a photo and call the API.

  • Capture an image from the camera, call the DetectFace API to confirm a face is present, then pass the image to your backend for further processing (such as liveness detection).

Q: Does face detection and facial feature localization support low-light or backlit environments?

The current capability does not support low-light or backlit environments. For accurate recognition results, use the API in well-lit conditions.