Face API JavaScript 퀵 스타트
- 본 번역문서의 원문은 Face API JavaScript Quick Starts docs.microsoft.com 입니다.
- 본 번역문서는 AI : Face API JavaScript 퀵 스타트 www.taeyo.net 에서도 함께 제공됩니다.
본문에서는 JavaScript와 Face API를 사용해서 다음과 같은 작업을 신속하게 수행하기 위해 필요한 유용한 정보와 예제 코드를 제공합니다:
무료 구독 키를 발급받는 방법은 구독 키 발급받기 문서를 참고하시기 바랍니다.
JavaScript를 이용해서 Face API로 이미지의 얼굴 감지하기
Face - Detect 메서드를 이용해서 이미지의 얼굴을 감지하고 다음과 같은 얼굴 특징을 반환받습니다:
- 얼굴 ID: 다양한 Face API 시나리오에서 사용되는 얼굴의 고유 ID
- 얼굴 사각형: 이미지 내의 얼굴 위치를 나타내는 Left, Top, Width, Height
- 랜드마크: 얼굴 구성 요소의 중요한 위치를 나타내는 27 곳의 얼굴 랜드마크 배열
- 나이, 성별, 미소짓는 정도, 머리 자세 및 얼굴의 털을 비롯한 얼굴 특징
얼굴 감지 JavaScript 요청 예제
예제를 실행하려면 다음의 과정을 따라하십시오:
- 
            detectFaces.html등의 이름으로 파일을 생성하고, 다음 예제 코드를 복사하여 붙여 넣은 다음 저장합니다.
- 
            subscriptionKey의 값을 여러분이 발급받은 유효한 구독 키로 변경합니다.
- 
            uriBase의 값을 구독 키를 발급받은 지역의 URL 주소로 변경합니다.
- 파일을 브라우저에 드래그 & 드랍합니다.
- 
            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
            }
        ]
    }
]- Face API 2017-12-05 08:00
- 이미지에서 얼굴 감지하기 2017-12-07 08:00
- 이미지의 얼굴 식별하기 2017-12-12 08:00
- 얼굴을 대량으로 추가하는 방법 2017-12-14 08:00
- Face API cURL 퀵 스타트 2017-12-19 08:00
- Face API C# 퀵 스타트 2017-12-21 08:00
- Face API Java 퀵 스타트 2017-12-26 08:00
- Face API JavaScript 퀵 스타트 2017-12-28 08:00
- Face API 시작하기 C# 자습서 2018-01-02 08:00
- Face API 시작하기 Android Java 자습서 2018-01-04 08:00

 sign in
 sign in
 join
 join 
    




 확인
 확인 취소
 취소