Face API JavaScript 퀵 스타트

등록일시: 2017-12-28 08:00,  수정일시: 2018-02-05 01:58
조회수: 3,977
이 문서는 Cognitive Services 기술을 널리 알리고자 하는 개인적인 취지로 제공되는 번역문서입니다. 이 문서에 대한 모든 저작권은 마이크로소프트에 있으며 요청이 있을 경우 언제라도 게시가 중단될 수 있습니다. 번역 내용에 오역이 존재할 수 있고 주석은 번역자 개인의 의견일 뿐이며 마이크로소프트는 이에 관한 어떠한 보장도 하지 않습니다. 번역이 완료된 이후에도 대상 제품 및 기술이 개선되거나 변경됨에 따라 원문의 내용도 변경되거나 보완되었을 수 있으므로 주의하시기 바랍니다.
본문에서는 JavaScript를 사용해서 Face API를 사용하는 방법을 살펴봅니다.

본문에서는 JavaScript와 Face API를 사용해서 다음과 같은 작업을 신속하게 수행하기 위해 필요한 유용한 정보와 예제 코드를 제공합니다:

무료 구독 키를 발급받는 방법은 구독 키 발급받기 문서를 참고하시기 바랍니다.

JavaScript를 이용해서 Face API로 이미지의 얼굴 감지하기

Face - Detect 메서드를 이용해서 이미지의 얼굴을 감지하고 다음과 같은 얼굴 특징을 반환받습니다:

  • 얼굴 ID: 다양한 Face API 시나리오에서 사용되는 얼굴의 고유 ID
  • 얼굴 사각형: 이미지 내의 얼굴 위치를 나타내는 Left, Top, Width, Height
  • 랜드마크: 얼굴 구성 요소의 중요한 위치를 나타내는 27 곳의 얼굴 랜드마크 배열
  • 나이, 성별, 미소짓는 정도, 머리 자세 및 얼굴의 털을 비롯한 얼굴 특징

얼굴 감지 JavaScript 요청 예제

예제를 실행하려면 다음의 과정을 따라하십시오:

  1. detectFaces.html 등의 이름으로 파일을 생성하고, 다음 예제 코드를 복사하여 붙여 넣은 다음 저장합니다.
  2. subscriptionKey의 값을 여러분이 발급받은 유효한 구독 키로 변경합니다.
  3. uriBase의 값을 구독 키를 발급받은 지역의 URL 주소로 변경합니다.
  4. 파일을 브라우저에 드래그 & 드랍합니다.
  5. Analyze faces 버튼을 클릭합니다.
<!DOCTYPE html>
<html>
<head>
    <title>Detect Faces Sample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    function processImage() {
        // **********************************************
        // *** Update or verify the following values. ***
        // **********************************************

        // Replace the subscriptionKey string value with your valid subscription key.
        var subscriptionKey = "13hc77781f7e4b19b5fcdd72a8df7156";

        // Replace or verify the region.
        //
        // You must use the same region in your REST API call as you used to obtain your subscription keys.
        // For example, if you obtained your subscription keys from the westus region, replace
        // "westcentralus" in the URI below with "westus".
        //
        // NOTE: Free trial subscription keys are generated in the westcentralus region, so if you are using
        // a free trial subscription key, you should not need to change this region.
        var uriBase = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";

        // Request parameters.
        var params = {
            "returnFaceId": "true",
            "returnFaceLandmarks": "false",
            "returnFaceAttributes": "age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise",
        };

        // Display the image.
        var sourceImageUrl = document.getElementById("inputImage").value;
        document.querySelector("#sourceImage").src = sourceImageUrl;

        // Perform the REST API call.
        $.ajax({
            url: uriBase + "?" + $.param(params),

            // Request headers.
            beforeSend: function(xhrObj){
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
            },

            type: "POST",

            // Request body.
            data: '{"url": ' + '"' + sourceImageUrl + '"}',
        })

        .done(function(data) {
            // Show formatted JSON on webpage.
            $("#responseTextArea").val(JSON.stringify(data, null, 2));
        })

        .fail(function(jqXHR, textStatus, errorThrown) {
            // Display error message.
            var errorString = (errorThrown === "") ? "Error. " : errorThrown + " (" + jqXHR.status + "): ";
            errorString += (jqXHR.responseText === "") ? "" : (jQuery.parseJSON(jqXHR.responseText).message) ? 
                jQuery.parseJSON(jqXHR.responseText).message : jQuery.parseJSON(jqXHR.responseText).error.message;
            alert(errorString);
        });
    };
</script>

<h1>Detect Faces:</h1>
Enter the URL to an image that includes a face or faces, then click the <strong>Analyze face</strong> button.
<br><br>
Image to analyze: <input type="text" name="inputImage" id="inputImage" value="https://upload.wikimedia.org/wikipedia/commons/c/c3/RH_Louise_Lillian_Gish.jpg" />
<button onclick="processImage()">Analyze face</button>
<br><br>
<div id="wrapper" style="width:1020px; display:table;">
    <div id="jsonOutput" style="width:600px; display:table-cell;">
        Response:
        <br><br>
        <textarea id="responseTextArea" class="UIInput" style="width:580px; height:400px;"></textarea>
    </div>
    <div id="imageDiv" style="width:420px; display:table-cell;">
        Source image:
        <br><br>
        <img id="sourceImage" width="400" />
    </div>
</div>
</body>
</html>

얼굴 감지 결과 응답 살펴보기

정상적으로 처리된 응답은 JSON 형식으로 반환됩니다. 다음은 성공한 응답의 사례입니다:

[
  {
    "faceId": "49d55c17-e018-4a42-ba7b-8cbbdfae7c6f",
    "faceRectangle": {
      "top": 131,
      "left": 177,
      "width": 162,
      "height": 162
    },
    "faceAttributes": {
      "smile": 0,
      "headPose": {
        "pitch": 0,
        "roll": 0.1,
        "yaw": -32.9
      },
      "gender": "female",
      "age": 22.9,
      "facialHair": {
        "moustache": 0,
        "beard": 0,
        "sideburns": 0
      },
      "glasses": "NoGlasses",
      "emotion": {
        "anger": 0,
        "contempt": 0,
        "disgust": 0,
        "fear": 0,
        "happiness": 0,
        "neutral": 0.986,
        "sadness": 0.009,
        "surprise": 0.005
      },
      "blur": {
        "blurLevel": "low",
        "value": 0.06
      },
      "exposure": {
        "exposureLevel": "goodExposure",
        "value": 0.67
      },
      "noise": {
        "noiseLevel": "low",
        "value": 0
      },
      "makeup": {
        "eyeMakeup": true,
        "lipMakeup": true
      },
      "accessories": [],
      "occlusion": {
        "foreheadOccluded": false,
        "eyeOccluded": false,
        "mouthOccluded": false
      },
      "hair": {
        "bald": 0,
        "invisible": false,
        "hairColor": [
          {
            "color": "brown",
            "confidence": 1
          },
          {
            "color": "black",
            "confidence": 0.87
          },
          {
            "color": "other",
            "confidence": 0.51
          },
          {
            "color": "blond",
            "confidence": 0.08
          },
          {
            "color": "red",
            "confidence": 0.08
          },
          {
            "color": "gray",
            "confidence": 0.02
          }
        ]
      }
    }
  }
]

JavaScript를 이용해서 Face API로 이미지의 얼굴 식별하기

다음 예제 코드를 복사해서 test.html 등의 이름의 파일로 저장합니다. url의 값을 구독 키를 발급받은 지역을 사용하도록 변경하고, "Ocp-Apim-Subscription-Key" 값을 유효한 구독 키로 대체한 다음, 요청 본문을 추가합니다. 마지막으로 파일을 브라우저에 드래그 & 드랍하여 예제를 실행합니다.

Face - Identify 메서드를 이용해서, 미리 생성해야하고 이후 편집이 가능한 인물 데이터베이스 (인물 그룹으로 정의된) 및 감지된 얼굴에 기반해서 인물을 식별합니다.

얼굴 식별 JavaScript 요청 예제

<!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>

<script type="text/javascript">
    $(function() {
        var params = {
            // Request parameters
        };

        $.ajax({
            // NOTE: You must use the same location in your REST call as you used to obtain your subscription keys.
            //   For example, if you obtained your subscription keys from westus, replace "westcentralus" in the 
            //   URL below with "westus".
            url: "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/identify?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");

                // NOTE: Replace the "Ocp-Apim-Subscription-Key" value with a valid subscription key.
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","13hc77781f7e4b19b5fcdd72a8df7156");
            },
            type: "POST",
            // Request body
            data: "{body}",
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("error");
        });
    });
</script>
</body>
</html>
역주

얼굴 식별의 경우, 요청 본문으로 전달되는 "{body}" 부분에 지정해야 하는 정보가 조금 복잡합니다. 다음은 API 참조 문서에서 발췌한 예제입니다.

{    
  "personGroupId": "sample_group",
  "faceIds": [
    "c5c24a82-6845-4031-9d5d-978df9175426",
    "65d083d4-9447-47d1-af30-b626144bf0fb"
  ],
  "maxNumOfCandidatesReturned": 1,
  "confidenceThreshold": 0.5
}

얼굴 식별 결과 응답 살펴보기

정상적으로 처리된 응답은 JSON 형식으로 반환됩니다. 다음은 성공한 응답의 사례입니다:

[
    {
        "faceId":"c5c24a82-6845-4031-9d5d-978df9175426",
        "candidates":[
            {
                "personId":"25985303-c537-4467-b41d-bdb45cd95ca1",
                "confidence":0.92
            }
        ]
    },
    {
        "faceId":"65d083d4-9447-47d1-af30-b626144bf0fb",
        "candidates":[
            {
                "personId":"2ae4935b-9659-44c3-977f-61fac20d0538",
                "confidence":0.89
            }
        ]
    }
]