

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 저장된 비디오에서 얼굴 감지
<a name="faces-sqs-video"></a>

Amazon Rekognition Video는 Amazon S3 버킷에 저장된 비디오에서 얼굴을 감지하여 다음과 같은 정보를 제공할 수 있습니다.
+ 비디오에서 얼굴이 감지된 시간
+ 얼굴이 감지된 시점에 비디오 프레임에서 해당 얼굴의 위치
+ 왼쪽 눈의 위치와 같은 얼굴 표식 
+ [얼굴 속성에 대한 가이드라인](guidance-face-attributes.md) 페이지에 설명된 추가 속성.

Amazon Rekognition Video의 저장된 비디오 속 얼굴 감지는 비동기 작업입니다. 비디오에서 얼굴 인식을 시작하려면 [StartFaceDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartFaceDetection.html)을 직접 호출하세요. Amazon Rekognition Video는 동영상 분석 작업의 완료 상태를 Amazon Simple Notification Service(SNS) 주제에 게시합니다. 비디오 분석이 성공적으로 완료되면 [GetFaceDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetFaceDetection.html)을 직접 호출하여 비디오 분석 결과를 가져올 수 있습니다. 비디오 분석 시작 및 결과 가져오기에 대한 자세한 내용은 [Amazon Rekognition Video 작업 직접 호출](api-video.md) 단원을 참조하십시오.

이 절차는 동영상 분석 요청의 완료 상태를 가져오기 위해 Amazon Simple Queue Service(Amazon SQS) 대기열을 사용하는 [Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)](video-analyzing-with-sqs.md)의 코드를 확장합니다.

**Amazon S3 버킷에 저장된 비디오에서 얼굴을 감지하려면(SDK)**

1. [Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)](video-analyzing-with-sqs.md)을 수행합니다.

1. 1단계에서 만든 클래스 `VideoDetect`에 다음 코드를 추가합니다.

------
#### [ AWS CLI ]
   + 다음 코드 샘플에서 `amzn-s3-demo-bucket` 및 `video-name`을 2단계에서 지정한 Amazon S3 버킷 이름과 파일 이름으로 변경합니다.
   + `region-name`을 사용 중인 AWS 리전으로 변경합니다. `profile_name`의 값을 개발자 프로필 이름으로 바꿉니다.
   + `TopicARN`을 [Amazon Rekognition Video 구성](api-video-roles.md)의 3단계에서 생성한 Amazon SNS 주제의 ARN으로 변경합니다.
   + `RoleARN`을 [Amazon Rekognition Video 구성](api-video-roles.md)의 7단계에서 생성한 IAM 서비스 역할의 ARN으로 변경합니다.

   ```
   aws rekognition start-face-detection --video "{"S3Object":{"Bucket":"amzn-s3-demo-bucket","Name":"Video-Name"}}" --notification-channel
   "{"SNSTopicArn":"Topic-ARN","RoleArn":"Role-ARN"}" --region region-name --profile profile-name
   ```

   Windows 디바이스에서 CLI에 액세스하는 경우 작은따옴표 대신 큰따옴표를 사용하고 내부 큰따옴표는 백슬래시(즉 \$1)로 이스케이프 처리하여 발생할 수 있는 구문 분석 오류를 해결합니다. 예를 들어 다음을 참조하세요.

   ```
   aws rekognition start-face-detection --video "{\"S3Object\":{\"Bucket\":\"amzn-s3-demo-bucket\",\"Name\":\"Video-Name\"}}" --notification-channel
   "{\"SNSTopicArn\":\"Topic-ARN\",\"RoleArn\":\"Role-ARN\"}" --region region-name --profile profile-name
   ```

   `StartFaceDetection` 작업을 실행하고 작업 ID 번호를 가져온 후 다음 `GetFaceDetection` 작업을 실행하고 작업 ID 번호를 제공합니다.

   ```
   aws rekognition get-face-detection --job-id job-id-number  --profile profile-name
   ```

------
#### [ Java ]

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   
   private static void StartFaceDetection(String bucket, String video) throws Exception{
            
       NotificationChannel channel= new NotificationChannel()
               .withSNSTopicArn(snsTopicArn)
               .withRoleArn(roleArn);
       
       StartFaceDetectionRequest req = new StartFaceDetectionRequest()
               .withVideo(new Video()
                       .withS3Object(new S3Object()
                           .withBucket(bucket)
                           .withName(video)))
               .withNotificationChannel(channel);
                           
                           
       
       StartFaceDetectionResult startLabelDetectionResult = rek.startFaceDetection(req);
       startJobId=startLabelDetectionResult.getJobId();
       
   } 
   
   private static void GetFaceDetectionResults() throws Exception{
       
       int maxResults=10;
       String paginationToken=null;
       GetFaceDetectionResult faceDetectionResult=null;
       
       do{
           if (faceDetectionResult !=null){
               paginationToken = faceDetectionResult.getNextToken();
           }
       
           faceDetectionResult = rek.getFaceDetection(new GetFaceDetectionRequest()
                .withJobId(startJobId)
                .withNextToken(paginationToken)
                .withMaxResults(maxResults));
       
           VideoMetadata videoMetaData=faceDetectionResult.getVideoMetadata();
               
           System.out.println("Format: " + videoMetaData.getFormat());
           System.out.println("Codec: " + videoMetaData.getCodec());
           System.out.println("Duration: " + videoMetaData.getDurationMillis());
           System.out.println("FrameRate: " + videoMetaData.getFrameRate());
               
               
           //Show faces, confidence and detection times
           List<FaceDetection> faces= faceDetectionResult.getFaces();
        
           for (FaceDetection face: faces) { 
               long seconds=face.getTimestamp()/1000;
               System.out.print("Sec: " + Long.toString(seconds) + " ");
               System.out.println(face.getFace().toString());
               System.out.println();           
           }
       } while (faceDetectionResult !=null && faceDetectionResult.getNextToken() != null);
         
           
   }
   ```

   `main` 함수에서 다음 줄을 바꿉니다.

   ```
           StartLabelDetection(amzn-s3-demo-bucket, video);
   
           if (GetSQSMessageSuccess()==true)
           	GetLabelDetectionResults();
   ```

   다음으로 바꿉니다.

   ```
           StartFaceDetection(amzn-s3-demo-bucket, video);
   
           if (GetSQSMessageSuccess()==true)
           	GetFaceDetectionResults();
   ```

------
#### [ Java V2 ]

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/VideoDetectFaces.java)에서 확인하세요.

   ```
   //snippet-start:[rekognition.java2.recognize_video_faces.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.*;
   import java.util.List;
   //snippet-end:[rekognition.java2.recognize_video_faces.import]
   
   
   /**
   * Before running this Java V2 code example, set up your development environment, including your credentials.
   *
   * For more information, see the following documentation topic:
   *
   * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
   */
   public class VideoDetectFaces {
   
    private static String startJobId ="";
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "   <bucket> <video> <topicArn> <roleArn>\n\n" +
            "Where:\n" +
            "   bucket - The name of the bucket in which the video is located (for example, (for example, amzn-s3-demo-bucket). \n\n"+
            "   video - The name of video (for example, people.mp4). \n\n" +
            "   topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic. \n\n" +
            "   roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use. \n\n" ;
   
        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }
   
        String bucket = args[0];
        String video = args[1];
        String topicArn = args[2];
        String roleArn = args[3];
   
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        NotificationChannel channel = NotificationChannel.builder()
            .snsTopicArn(topicArn)
            .roleArn(roleArn)
            .build();
   
        StartFaceDetection(rekClient, channel, bucket, video);
        GetFaceResults(rekClient);
        System.out.println("This example is done!");
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.recognize_video_faces.main]
    public static void StartFaceDetection(RekognitionClient rekClient,
                                          NotificationChannel channel,
                                          String bucket,
                                          String video) {
   
        try {
            S3Object s3Obj = S3Object.builder()
                .bucket(bucket)
                .name(video)
                .build();
   
            Video vidOb = Video.builder()
                .s3Object(s3Obj)
                .build();
   
            StartFaceDetectionRequest  faceDetectionRequest = StartFaceDetectionRequest.builder()
                .jobTag("Faces")
                .faceAttributes(FaceAttributes.ALL)
                .notificationChannel(channel)
                .video(vidOb)
                .build();
   
            StartFaceDetectionResponse startLabelDetectionResult = rekClient.startFaceDetection(faceDetectionRequest);
            startJobId=startLabelDetectionResult.jobId();
   
        } catch(RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
   
    public static void GetFaceResults(RekognitionClient rekClient) {
   
        try {
            String paginationToken=null;
            GetFaceDetectionResponse faceDetectionResponse=null;
            boolean finished = false;
            String status;
            int yy=0 ;
   
            do{
                if (faceDetectionResponse !=null)
                    paginationToken = faceDetectionResponse.nextToken();
   
                GetFaceDetectionRequest recognitionRequest = GetFaceDetectionRequest.builder()
                    .jobId(startJobId)
                    .nextToken(paginationToken)
                    .maxResults(10)
                    .build();
   
                // Wait until the job succeeds
                while (!finished) {
   
                    faceDetectionResponse = rekClient.getFaceDetection(recognitionRequest);
                    status = faceDetectionResponse.jobStatusAsString();
   
                    if (status.compareTo("SUCCEEDED") == 0)
                        finished = true;
                    else {
                        System.out.println(yy + " status is: " + status);
                        Thread.sleep(1000);
                    }
                    yy++;
                }
   
                finished = false;
   
                // Proceed when the job is done - otherwise VideoMetadata is null
                VideoMetadata videoMetaData=faceDetectionResponse.videoMetadata();
                System.out.println("Format: " + videoMetaData.format());
                System.out.println("Codec: " + videoMetaData.codec());
                System.out.println("Duration: " + videoMetaData.durationMillis());
                System.out.println("FrameRate: " + videoMetaData.frameRate());
                System.out.println("Job");
   
                // Show face information
                List<FaceDetection> faces= faceDetectionResponse.faces();
   
                for (FaceDetection face: faces) {
                    String age = face.face().ageRange().toString();
                    String smile = face.face().smile().toString();
                    System.out.println("The detected face is estimated to be"
                                + age + " years old.");
                    System.out.println("There is a smile : "+smile);
                }
   
            } while (faceDetectionResponse !=null && faceDetectionResponse.nextToken() != null);
   
        } catch(RekognitionException | InterruptedException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.recognize_video_faces.main]
   }
   ```

------
#### [ Python ]

   ```
   #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
       # ============== Faces===============
       def StartFaceDetection(self):
           response=self.rek.start_face_detection(Video={'S3Object': {'Bucket': self.bucket, 'Name': self.video}},
               NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn})
   
           self.startJobId=response['JobId']
           print('Start Job Id: ' + self.startJobId)
   
       def GetFaceDetectionResults(self):
           maxResults = 10
           paginationToken = ''
           finished = False
   
           while finished == False:
               response = self.rek.get_face_detection(JobId=self.startJobId,
                                               MaxResults=maxResults,
                                               NextToken=paginationToken)
   
               print('Codec: ' + response['VideoMetadata']['Codec'])
               print('Duration: ' + str(response['VideoMetadata']['DurationMillis']))
               print('Format: ' + response['VideoMetadata']['Format'])
               print('Frame rate: ' + str(response['VideoMetadata']['FrameRate']))
               print()
   
               for faceDetection in response['Faces']:
                   print('Face: ' + str(faceDetection['Face']))
                   print('Confidence: ' + str(faceDetection['Face']['Confidence']))
                   print('Timestamp: ' + str(faceDetection['Timestamp']))
                   print()
   
               if 'NextToken' in response:
                   paginationToken = response['NextToken']
               else:
                   finished = True
   ```

   `main` 함수에서 다음 줄을 바꿉니다.

   ```
       analyzer.StartLabelDetection()
       if analyzer.GetSQSMessageSuccess()==True:
           analyzer.GetLabelDetectionResults()
   ```

   다음으로 바꿉니다.

   ```
       analyzer.StartFaceDetection()
       if analyzer.GetSQSMessageSuccess()==True:
           analyzer.GetFaceDetectionResults()
   ```

------
**참고**  
[Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)](video-analyzing-with-sqs.md) 이외에 비디오 예제를 이미 실행한 경우, 바꿀 함수 이름이 다릅니다.

1. 코드를 실행합니다. 비디오에서 감지된 얼굴에 관한 정보가 표시됩니다.

## GetFaceDetection 작업 응답
<a name="getfacedetection-operation-response"></a>

`GetFaceDetection`은 비디오에서 감지된 얼굴에 대한 정보가 포함된 배열(`Faces`)을 반환합니다. 배열 요소인 [FaceDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_FaceDetection.html)은 비디오에서 얼굴이 감지될 때마다 존재합니다. 반환된 배열 요소는 비디오 시작 후 시간별로(밀리초) 정렬되어 반환됩니다.

다음 예제는 `GetFaceDetection`의 부분 JSON 응답입니다. 응답에서 다음에 유의하십시오.
+ **경계 상자** - 얼굴 주위를 두르는 경계 상자의 좌표.
+ **신뢰도** - 경계 상자에 얼굴이 포함될 신뢰도 수준.
+ **얼굴 표식** – 얼굴 표식의 배열. 응답은 왼쪽 눈, 오른쪽 눈, 입 같은 각각의 표식에 대해 `x`, `y` 좌표를 제공합니다.
+ **얼굴 속성** - AgeRange, Beard, Emotions, Eyeglasses, EyesOpen, Gender, MouthOpen, Mustache, Smile, Sunglasses를 포함하는 얼굴 속성 집합입니다. 이 값은 부울(사람이 선글라스를 착용하고 있는지), 문자열(남성인지 여성인지) 등 다양한 형식이 될 수 있습니다. 또한 대부분의 속성의 경우, 응답은 해당 속성에 대해 감지된 값의 신뢰도도 제공합니다. 단, FaceOccluded 속성과 EyeDirection 속성은 `DetectFaces`를 사용할 때는 지원되지만, `StartFaceDetection` 및 `GetFaceDetection`을 사용하여 비디오를 분석할 때는 지원되지 않습니다.
+ **타임스탬프** - 비디오에서 얼굴이 감지된 시간입니다.
+ **페이징 정보** - 이 예제는 얼굴 감지 정보의 페이지 하나를 보여줍니다. `GetFaceDetection`의 `MaxResults` 입력 파라미터에 반환될 사람 요소의 수를 지정할 수 있습니다. `MaxResults` 보다 많은 결과가 존재할 경우 `GetFaceDetection`은 결과의 다음 페이지를 가져올 때 사용되는 토큰(`NextToken`)을 반환합니다. 자세한 내용은 [Amazon Rekognition Video 분석 결과 가져오기](api-video.md#api-video-get) 단원을 참조하십시오.
+ **비디오 정보** - 이 응답은 `GetFaceDetection`이 반환하는 정보의 각 페이지에 있는 비디오 형식(`VideoMetadata`)에 관한 정보를 포함합니다.
+ **품질** – 얼굴의 밝기와 선명도를 기술합니다.
+ **자세** – 이미지 내 얼굴의 회전을 기술합니다.

```
{
    "Faces": [
        {
            "Face": {
                "BoundingBox": {
                    "Height": 0.23000000417232513,
                    "Left": 0.42500001192092896,
                    "Top": 0.16333332657814026,
                    "Width": 0.12937499582767487
                },
                "Confidence": 99.97504425048828,
                "Landmarks": [
                    {
                        "Type": "eyeLeft",
                        "X": 0.46415066719055176,
                        "Y": 0.2572723925113678
                    },
                    {
                        "Type": "eyeRight",
                        "X": 0.5068183541297913,
                        "Y": 0.23705792427062988
                    },
                    {
                        "Type": "nose",
                        "X": 0.49765899777412415,
                        "Y": 0.28383663296699524
                    },
                    {
                        "Type": "mouthLeft",
                        "X": 0.487221896648407,
                        "Y": 0.3452930748462677
                    },
                    {
                        "Type": "mouthRight",
                        "X": 0.5142884850502014,
                        "Y": 0.33167609572410583
                    }
                ],
                "Pose": {
                    "Pitch": 15.966927528381348,
                    "Roll": -15.547388076782227,
                    "Yaw": 11.34195613861084
                },
                "Quality": {
                    "Brightness": 44.80223083496094,
                    "Sharpness": 99.95819854736328
                }
            },
            "Timestamp": 0
        },
        {
            "Face": {
                "BoundingBox": {
                    "Height": 0.20000000298023224,
                    "Left": 0.029999999329447746,
                    "Top": 0.2199999988079071,
                    "Width": 0.11249999701976776
                },
                "Confidence": 99.85971069335938,
                "Landmarks": [
                    {
                        "Type": "eyeLeft",
                        "X": 0.06842322647571564,
                        "Y": 0.3010137975215912
                    },
                    {
                        "Type": "eyeRight",
                        "X": 0.10543643683195114,
                        "Y": 0.29697132110595703
                    },
                    {
                        "Type": "nose",
                        "X": 0.09569807350635529,
                        "Y": 0.33701086044311523
                    },
                    {
                        "Type": "mouthLeft",
                        "X": 0.0732642263174057,
                        "Y": 0.3757539987564087
                    },
                    {
                        "Type": "mouthRight",
                        "X": 0.10589495301246643,
                        "Y": 0.3722417950630188
                    }
                ],
                "Pose": {
                    "Pitch": -0.5589138865470886,
                    "Roll": -5.1093974113464355,
                    "Yaw": 18.69594955444336
                },
                "Quality": {
                    "Brightness": 43.052337646484375,
                    "Sharpness": 99.68138885498047
                }
            },
            "Timestamp": 0
        },
        {
            "Face": {
                "BoundingBox": {
                    "Height": 0.2177777737379074,
                    "Left": 0.7593749761581421,
                    "Top": 0.13333334028720856,
                    "Width": 0.12250000238418579
                },
                "Confidence": 99.63436889648438,
                "Landmarks": [
                    {
                        "Type": "eyeLeft",
                        "X": 0.8005779385566711,
                        "Y": 0.20915353298187256
                    },
                    {
                        "Type": "eyeRight",
                        "X": 0.8391435146331787,
                        "Y": 0.21049551665782928
                    },
                    {
                        "Type": "nose",
                        "X": 0.8191410899162292,
                        "Y": 0.2523227035999298
                    },
                    {
                        "Type": "mouthLeft",
                        "X": 0.8093273043632507,
                        "Y": 0.29053622484207153
                    },
                    {
                        "Type": "mouthRight",
                        "X": 0.8366993069648743,
                        "Y": 0.29101791977882385
                    }
                ],
                "Pose": {
                    "Pitch": 3.165884017944336,
                    "Roll": 1.4182015657424927,
                    "Yaw": -11.151537895202637
                },
                "Quality": {
                    "Brightness": 28.910892486572266,
                    "Sharpness": 97.61507415771484
                }
            },
            "Timestamp": 0
        }.......

    ],
    "JobStatus": "SUCCEEDED",
    "NextToken": "i7fj5XPV/fwviXqz0eag9Ow332Jd5G8ZGWf7hooirD/6V1qFmjKFOQZ6QPWUiqv29HbyuhMNqQ==",
    "VideoMetadata": {
        "Codec": "h264",
        "DurationMillis": 67301,
        "FileExtension": "mp4",
        "Format": "QuickTime / MOV",
        "FrameHeight": 1080,
        "FrameRate": 29.970029830932617,
        "FrameWidth": 1920
    }
}
```