login register Sysop! about ME  
qrcode
    최초 작성일 :    2018년 02월 04일
  최종 수정일 :    2018년 02월 04일
  작성자 :    soggun
  편집자 :    soggun (송원석)
  읽음수 :    12,390

강좌 목록으로 돌아가기

필자의 잡담~

이번 문서는 Microsoft 인공지능 서비스인 Cognitive Service의 Face API에 대해 설명합니다.

개발자들이 쉽게 접근하고, 사용할 수 있는 Cognitive Service의 다양한 컬럼들을 계속해서 번역하여 제공할 예정입니다.

본 번역문서는 개인적인 취지로 번역되어 제공되는 문서로, 원문을 비롯한 모든 저작권은 마이크로소프트사에 있습니다. 마이크로소프트사의 요청이 있을 경우, 언제라도 게시가 중단될 수 있습니다. 본 번역문서에는 오역이 포함되어 있을 수 있으며 주석도 번역자 개인의 견해일뿐입니다. 마이크로소프트사는 본 문서의 번역된 내용에 대해 일체의 보장을 하지 않습니다. 번역이 완료된 뒤에도 제품이 업그레이드 되거나 기능이 변경됨에 따라 원문도 변경되거나 보완되었을 수 있으므로 참고하시기 바랍니다.

원문: https://docs.microsoft.com/ko-kr/azure/cognitive-services/face/quickstarts/javascript

Face API JavaScript 퀵 스타트

본문에서는 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:1020pxdisplay:table;">
        <div id="jsonOutput" style="width:600pxdisplay:table-cell;">
            Response:
            <br><br>
            <textarea id="responseTextArea" class="UIInput" style="width:580pxheight:400px;"></textarea>
        </div>
        <div id="imageDiv" style="width:420pxdisplay: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
            }
        ]
    }
]

authored by


 
 
.NET과 Java 동영상 기반의 교육사이트

로딩 중입니다...

서버 프레임워크 지원 : NeoDEEX
based on ASP.NET 3.5
Creative Commons License
{5}
{2} 읽음   :{3} ({4})