All Products
Search
Document Center

Content Moderation:Face comparison

Last Updated:Aug 19, 2024

This topic describes how to call the face comparison SDK for Java to compare specified face images and detect the similarity between different face images.

Usage notes

Face comparison supports synchronous moderation and asynchronous moderation.

  • If you use synchronous face comparison, the moderation results are returned in real time. For more information about the related parameters, see Synchronous moderation.

  • If you use asynchronous face comparison, you must poll the moderation results or configure a callback notification to receive the moderation results. For more information about the related parameters, see Asynchronous moderation.

Prerequisites

  • Java dependencies are installed. For more information, see Installation.

    Note

    You must use the Java version described in the Installation topic to install the dependencies. Otherwise, subsequent operation calls fail.

  • The Extension.Uploader utility class is downloaded and imported into your project if you submit a local image or a binary image stream for image moderation.

Sample code for submitting the URLs of face images

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.extension.uploader.ClientUploader;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.*;

public class ImageSyncScanSample {

    public static void main(String[] args) throws Exception {
       /**
         * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
         * Common ways to obtain environment variables:
         * Method 1:
         *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * Method 2:
         *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
        IAcsClient client = new DefaultAcsClient(profile);

        // Specify the API response format and request method. 
        ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
        imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
        imageSyncScanRequest.setMethod(MethodType.POST);
        imageSyncScanRequest.setEncoding("utf-8");
        imageSyncScanRequest.setProtocol(ProtocolType.HTTP);

        JSONObject httpBody = new JSONObject();
        httpBody.put("scenes", Arrays.asList("sface-1")); 

        JSONObject task = new JSONObject();
        // Specify the URL of face image 1 to be compared. 
        task.put("url","http://example.com/xxx.jpg");
        JSONObject extras = new JSONObject();

        // Specify the URL of face image 2 to be compared. 
        extras.put("faceUrl", "http://example.com/yyyy.jpg"); 
        task.put("extras", extras); 
        httpBody.put("tasks", Arrays.asList(task));

        imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
            "UTF-8", FormatType.JSON);

        /**
         * Specify the connection timeout and read timeout. The timeout period for the server to complete a file moderation request is 10s. 
         * If you set the read timeout to a period shorter than 10s, the server may generate a read timeout error during request processing. 
         */
        imageSyncScanRequest.setConnectTimeout(3000);
        imageSyncScanRequest.setReadTimeout(10000);
        HttpResponse httpResponse = null;
        try {
            httpResponse = client.doAction(imageSyncScanRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // The results that are returned after the server receives and processes your request. 
        if (httpResponse != null && httpResponse.isSuccess()) {
            JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
            System.out.println(JSON.toJSONString(scrResponse, true));
            int requestCode = scrResponse.getIntValue("code");
            // The moderation results of all images. 
            JSONArray taskResults = scrResponse.getJSONArray("data");
            if (200 == requestCode) {
                for (Object taskResult : taskResults) {
                    // The moderation result of a single image. 
                    int taskCode = ((JSONObject) taskResult).getIntValue("code");
                    // The moderation result of the image in a moderation scenario. If you specified multiple moderation scenarios in the request, the moderation result of the image in each scenario is returned. 
                    JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                    if (200 == taskCode) {
                        for (Object sceneResult : sceneResults) {
                            String scene = ((JSONObject) sceneResult).getString("scene");
                            String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                            // Take further action based on the values of the scene and suggestion parameters. 
                            System.out.println("suggestion = [" + suggestion + "]");
                        }
                    } else {
                        // A single image failed to be moderated. Analyze the failure based on the actual situation. 
                        System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                    }
                }
            } else {
                /**
                 * The request failed to be processed. Analyze the failure based on the actual situation. 
                 */
                System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
            }
        }
    }

}

Sample code for submitting a local file

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.extension.uploader.ClientUploader;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.*;

public class ImageSyncScanSample {

    public static void main(String[] args) throws Exception {
        /**
         * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
         * Common ways to obtain environment variables:
         * Method 1:
         *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * Method 2:
         *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
        DefaultProfile
            .addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
        IAcsClient client = new DefaultAcsClient(profile);

        // Specify the API response format and request method. 
        ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
        imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
        imageSyncScanRequest.setMethod(MethodType.POST);
        imageSyncScanRequest.setEncoding("utf-8");
        imageSyncScanRequest.setProtocol(ProtocolType.HTTP);

        JSONObject httpBody = new JSONObject();
        httpBody.put("scenes", Arrays.asList("sface-1")); 
        ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);

        JSONObject task = new JSONObject();
        // Upload face image 1 to be compared. 
        String url1 = null;
        try{
            url1 = clientUploader.uploadFile("d:/image1.jpg");
        }catch (Exception e){
            e.printStackTrace();
        }
        task.put("url", url1);
        JSONObject extras = new JSONObject();

        // Upload face image 2 to be compared. 
        String url2 = null;
        try{
            url2 = clientUploader.uploadFile("d:/image2.jpg");
        }catch (Exception e){
            e.printStackTrace();
        }
        extras.put("faceUrl", url2); 
        task.put("extras", extras); 
        httpBody.put("tasks", Arrays.asList(task));

        imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
            "UTF-8", FormatType.JSON);

        /**
         * Specify the connection timeout and read timeout. The timeout period for the server to complete a file moderation request is 10s. 
         * If you set the read timeout to a period shorter than 10s, the server may generate a read timeout error during request processing. 
         */
        imageSyncScanRequest.setConnectTimeout(3000);
        imageSyncScanRequest.setReadTimeout(10000);
        HttpResponse httpResponse = null;
        try {
            httpResponse = client.doAction(imageSyncScanRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // The results that are returned after the server receives and processes your request. 
        if (httpResponse != null && httpResponse.isSuccess()) {
            JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
            System.out.println(JSON.toJSONString(scrResponse, true));
            int requestCode = scrResponse.getIntValue("code");
            // The moderation results of all images. 
            JSONArray taskResults = scrResponse.getJSONArray("data");
            if (200 == requestCode) {
                for (Object taskResult : taskResults) {
                    // The moderation result of a single image. 
                    int taskCode = ((JSONObject) taskResult).getIntValue("code");
                    // The moderation result of the image in a moderation scenario. If you specified multiple moderation scenarios in the request, the moderation result of the image in each scenario is returned. 
                    JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                    if (200 == taskCode) {
                        for (Object sceneResult : sceneResults) {
                            String scene = ((JSONObject) sceneResult).getString("scene");
                            String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                            // Take further action based on the values of the scene and suggestion parameters. 
                            System.out.println("suggestion = [" + suggestion + "]");
                        }
                    } else {
                        // A single image failed to be moderated. Analyze the failure based on the actual situation. 
                        System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                    }
                }
            } else {
                /**
                 * The request failed to be processed. Analyze the failure based on the actual situation. 
                 */
                System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
            }
        }
    }

}