Face comparison

更新时间:
复制 MD 格式

Use the Content Moderation SDK for .NET to compare two face images and determine whether they belong to the same person.

How it works

Submit a face comparison task with the URLs of two images. The SDK sends an ImageSyncScanRequest to the Content Moderation service with the sface-1 scene, which performs facial attribute detection.

Face comparison supports two detection modes:

  • Synchronous detection: Returns results immediately. Use this for real-time scenarios. For request and response parameters, see the Synchronous Detection API reference.

  • Asynchronous detection: Submits a task and returns results via polling or a callback notification. Use this for batch processing or when you do not need an immediate response. For parameters, see Asynchronous moderation.

Note

The SDK accepts only public HTTP or HTTPS image URLs with a maximum length of 2,048 characters. Local files and binary data are not supported.

Prerequisites

Before you begin, make sure you have:

  • Installed the Content Moderation SDK for .NET dependencies. For installation steps, see Installation.

  • Used the .NET version specified in the Installation guide. Using a different version causes operation calls to fail.

  • Two publicly accessible face image URLs (HTTP or HTTPS, max 2,048 characters each).

  • An AccessKey ID and AccessKey secret for a Resource Access Management (RAM) user with permission to call Content Moderation APIs. Store these as environment variables.

Submit a face comparison task

The following example submits a synchronous face comparison task. All requests use the sface-1 scene to compare face image 1 (url) against face image 2 (faceUrl).

using System;
using Newtonsoft.Json;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Green.Model.V20180509;
using System.Collections.Generic;

namespace csharp_sdk_sample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Retrieve credentials from environment variables.
            // Do not hardcode credentials in your code.
            DefaultProfile profile = DefaultProfile.GetProfile(
                    "cn-shanghai",
                    Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                    Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));

            // Reuse the client instance to improve performance and avoid repeated connections.
            DefaultAcsClient client = new DefaultAcsClient(profile);

            ImageSyncScanRequest request = new ImageSyncScanRequest();
            request.AcceptFormat = FormatType.JSON;
            request.ContentType = FormatType.JSON;
            request.Method = MethodType.POST;
            request.Encoding = "UTF-8";

            // faceUrl: the URL of face image 2 to compare against.
            Dictionary<string, object> extras = new Dictionary<string, object>();
            extras.Add("faceUrl", "<face-image-2-url>");

            // url: the URL of face image 1 (the source image).
            Dictionary<string, object> task1 = new Dictionary<string, object>();
            task1.Add("dataId", "<data-id>");
            task1.Add("url", "<face-image-1-url>");
            task1.Add("extras", extras);

            // scenes: set to "sface-1" for face comparison.
            // bizType: your business scenario identifier.
            Dictionary<string, object> httpBody = new Dictionary<string, object>();
            httpBody.Add("scenes", new List<string> { "sface-1" });
            httpBody.Add("bizType", "<business-scenario>");
            httpBody.Add("tasks", new List<Dictionary<string, object>> { task1 });

            request.SetContent(
                System.Text.Encoding.Default.GetBytes(JsonConvert.SerializeObject(httpBody)),
                "utf-8",
                FormatType.JSON);

            try
            {
                ImageSyncScanResponse response = client.GetAcsResponse(request);
                if (response.HttpResponse.Status != 200)
                {
                    Console.WriteLine("Request failed. Status: {0}", response.HttpResponse.Status);
                }
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error: {0}", ex.Message);
            }
        }
    }
}

Replace the following placeholders before running the code:

PlaceholderDescription
<face-image-1-url>Public HTTP or HTTPS URL of the first face image
<face-image-2-url>Public HTTP or HTTPS URL of the second face image
<data-id>A unique identifier for the task, used to correlate requests and responses
<business-scenario>Your business scenario identifier, corresponding to the bizType parameter

Usage notes

  • Client reuse: Instantiate DefaultAcsClient once and reuse it across requests. Creating a new client per request degrades performance and increases connection overhead.

  • Credentials: Store your AccessKey ID and AccessKey secret as environment variables (ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET). Hardcoding credentials in source code is a security risk.

  • Image requirements: Both image URLs must be publicly accessible. The SDK does not support local files, binary data, or private URLs requiring authentication.

What's next