

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

# 인물 경로 추적
<a name="persons"></a>

**참고**  
*지원 종료 알림:* 2025년 10월 31일에 AWS는 Amazon Rekognition 인물 경로에 대한 지원을 중단합니다. 2025년 10월 31일 이후에는 Rekognition 인물 경로 기능을 더 이상 사용할 수 없습니다. 자세한 내용은 이 [블로그 게시물](https://aws.amazon.com/blogs/machine-learning/transitioning-from-amazon-rekognition-people-pathing-exploring-other-alternatives/)을 참조하세요.

Amazon Rekognition Video는 비디오 속 인물이 선택하는 경로의 트랙을 생성하고 다음과 같은 정보를 제공할 수 있습니다.
+ 비디오 프레임에 있는 사람의 경로가 추적될 때의 위치입니다.
+ 왼쪽 눈의 위치와 같은 얼굴 표식(감지된 경우).

Amazon Rekognition Video의 저장된 비디오 속 인물 경로 추적은 비동기식 작업입니다. 비디오 속 인물의 경로 추적을 시작하려면 [StartPersonTracking](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartPersonTracking.html)을 직접 호출하세요. Amazon Rekognition Video는 비디오 분석의 완료 상태를 Amazon Simple Notification Service 주제에 게시합니다. 비디오 분석이 성공적으로 완료되면 [GetPersonTracking](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetPersonTracking.html)을 직접 호출하여 비디오 분석 결과를 가져오세요. Amazon Rekognition Video API 작업 직접 호출에 대한 자세한 내용은 [Amazon Rekognition Video 작업 직접 호출](api-video.md) 섹션을 참조하세요.

다음 절차는 Amazon S3 버킷에 저장된 비디오를 통해 사람의 경로를 추적하는 방법을 보여줍니다. 이 예제는 Amazon Simple Queue Service 대기열을 사용하여 비디오 분석 요청의 완료 상태를 가져오는 [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`에 다음 코드를 추가합니다.

------
#### [ 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.)
   
           //Persons========================================================================
           private static void StartPersonDetection(String bucket, String video) throws Exception{
               
               
               NotificationChannel channel= new NotificationChannel()
                       .withSNSTopicArn(snsTopicArn)
                       .withRoleArn(roleArn);
               
            StartPersonTrackingRequest req = new StartPersonTrackingRequest()
                    .withVideo(new Video()
                            .withS3Object(new S3Object()
                                .withBucket(bucket)
                                .withName(video)))
                    .withNotificationChannel(channel);
                                   
                
               
            StartPersonTrackingResult startPersonDetectionResult = rek.startPersonTracking(req);
            startJobId=startPersonDetectionResult.getJobId();
               
           } 
           
           private static void GetPersonDetectionResults() throws Exception{
               int maxResults=10;
               String paginationToken=null;
               GetPersonTrackingResult personTrackingResult=null;
               
               do{
                   if (personTrackingResult !=null){
                       paginationToken = personTrackingResult.getNextToken();
                   }
                   
                   personTrackingResult = rek.getPersonTracking(new GetPersonTrackingRequest()
                        .withJobId(startJobId)
                        .withNextToken(paginationToken)
                        .withSortBy(PersonTrackingSortBy.TIMESTAMP)
                        .withMaxResults(maxResults));
             
                   VideoMetadata videoMetaData=personTrackingResult.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 persons, confidence and detection times
                   List<PersonDetection> detectedPersons= personTrackingResult.getPersons();
                
                   for (PersonDetection detectedPerson: detectedPersons) { 
                       
                      long seconds=detectedPerson.getTimestamp()/1000;
                      System.out.print("Sec: " + Long.toString(seconds) + " ");
                      System.out.println("Person Identifier: "  + detectedPerson.getPerson().getIndex());
                         System.out.println();             
                   }
               }  while (personTrackingResult !=null && personTrackingResult.getNextToken() != null);
               
           }
   ```

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

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

   다음으로 바꿉니다.

   ```
           StartPersonDetection(amzn-s3-demo-bucket, video);
   
           if (GetSQSMessageSuccess()==true)
           	GetPersonDetectionResults();
   ```

------
#### [ 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/VideoPersonDetection.java)에서 확인하세요.

   ```
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.S3Object;
   import software.amazon.awssdk.services.rekognition.model.NotificationChannel;
   import software.amazon.awssdk.services.rekognition.model.StartPersonTrackingRequest;
   import software.amazon.awssdk.services.rekognition.model.Video;
   import software.amazon.awssdk.services.rekognition.model.StartPersonTrackingResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.GetPersonTrackingResponse;
   import software.amazon.awssdk.services.rekognition.model.GetPersonTrackingRequest;
   import software.amazon.awssdk.services.rekognition.model.VideoMetadata;
   import software.amazon.awssdk.services.rekognition.model.PersonDetection;
   import java.util.List;
   
   /**
    * 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 VideoPersonDetection {
       private static String startJobId = "";
   
       public static void main(String[] args) {
   
           final String usage = """
   
                   Usage:    <bucket> <video> <topicArn> <roleArn>
   
                   Where:
                      bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s
                      video - The name of video (for example, people.mp4).\s
                      topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s
                      roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s
                   """;
   
           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)
                   .build();
   
           NotificationChannel channel = NotificationChannel.builder()
                   .snsTopicArn(topicArn)
                   .roleArn(roleArn)
                   .build();
   
           startPersonLabels(rekClient, channel, bucket, video);
           getPersonDetectionResults(rekClient);
           System.out.println("This example is done!");
           rekClient.close();
       }
   
       public static void startPersonLabels(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();
   
               StartPersonTrackingRequest personTrackingRequest = StartPersonTrackingRequest.builder()
                       .jobTag("DetectingLabels")
                       .video(vidOb)
                       .notificationChannel(channel)
                       .build();
   
               StartPersonTrackingResponse labelDetectionResponse = rekClient.startPersonTracking(personTrackingRequest);
               startJobId = labelDetectionResponse.jobId();
   
           } catch (RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
   
       public static void getPersonDetectionResults(RekognitionClient rekClient) {
           try {
               String paginationToken = null;
               GetPersonTrackingResponse personTrackingResult = null;
               boolean finished = false;
               String status;
               int yy = 0;
   
               do {
                   if (personTrackingResult != null)
                       paginationToken = personTrackingResult.nextToken();
   
                   GetPersonTrackingRequest recognitionRequest = GetPersonTrackingRequest.builder()
                           .jobId(startJobId)
                           .nextToken(paginationToken)
                           .maxResults(10)
                           .build();
   
                   // Wait until the job succeeds
                   while (!finished) {
   
                       personTrackingResult = rekClient.getPersonTracking(recognitionRequest);
                       status = personTrackingResult.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 = personTrackingResult.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");
   
                   List<PersonDetection> detectedPersons = personTrackingResult.persons();
                   for (PersonDetection detectedPerson : detectedPersons) {
                       long seconds = detectedPerson.timestamp() / 1000;
                       System.out.print("Sec: " + seconds + " ");
                       System.out.println("Person Identifier: " + detectedPerson.person().index());
                       System.out.println();
                   }
   
               } while (personTrackingResult != null && personTrackingResult.nextToken() != null);
   
           } catch (RekognitionException | InterruptedException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
   }
   ```

------
#### [ 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.)
   
       # ============== People pathing ===============  
       def StartPersonPathing(self):
           response=self.rek.start_person_tracking(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 GetPersonPathingResults(self):
           maxResults = 10
           paginationToken = ''
           finished = False
   
           while finished == False:
               response = self.rek.get_person_tracking(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 personDetection in response['Persons']:
                   print('Index: ' + str(personDetection['Person']['Index']))
                   print('Timestamp: ' + str(personDetection['Timestamp']))
                   print()
   
               if 'NextToken' in response:
                   paginationToken = response['NextToken']
               else:
                   finished = True
   ```

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

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

   다음으로 바꿉니다.

   ```
       analyzer.StartPersonPathing()
       if analyzer.GetSQSMessageSuccess()==True:
           analyzer.GetPersonPathingResults()
   ```

------
#### [ CLI ]

   다음 AWS CLI 명령어를 실행하여 비디오에서 인물의 경로 추적을 시작합니다.

   ```
   aws rekognition start-person-tracking --video "{"S3Object":{"Bucket":"amzn-s3-demo-bucket","Name":"video-name"}}" \ 
   --notification-channel "{"SNSTopicArn":"topic-ARN","RoleArn":"role-ARN"}" \
   --region region-name --profile profile-name
   ```

   다음 값을 업데이트합니다.
   + `amzn-s3-demo-bucket` 및 `video-name`을 2단계에서 지정한 Amazon S3 버킷 이름과 파일 이름으로 변경합니다.
   + `region-name`을 사용 중인 AWS 리전으로 변경합니다.
   + Rekognition 세션을 생성하는 라인에서 `profile-name`의 값을 개발자 프로필의 이름으로 대체합니다.
   + `topic-ARN`을 [Amazon Rekognition Video 구성](api-video-roles.md)의 3단계에서 생성한 Amazon SNS 주제의 ARN으로 변경합니다.
   + `role-ARN`을 [Amazon Rekognition Video 구성](api-video-roles.md)의 7단계에서 생성한 IAM 서비스 역할의 ARN으로 변경합니다.

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

   ```
   aws rekognition start-person-tracking --video "{\"S3Object\":{\"Bucket\":\"amzn-s3-demo-bucket\",\"Name\":\"video-name\"}}" 
   --notification-channel "{\"SNSTopicArn\":\"topic-ARN\",\"RoleArn\":\"role-ARN\"}" \
   --region region-name --profile profile-name
   ```

   진행 중인 코드 예제를 실행한 후 반환된 `jobID`를 복사하여 다음 `GetPersonTracking` 명령에 제공하여 결과를 가져오고,`job-id-number`를 이전에 받은 `jobID`로 바꾸세요.

   ```
   aws rekognition get-person-tracking --job-id job-id-number                                
   ```

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

1. 코드를 실행합니다. 추적된 사람에 대한 고유 식별자는 인물의 경로가 추적된 시간(초)과 함께 표시됩니다.

## GetPersonTracking 작업 응답
<a name="getresultspersons-operation-response"></a>

`GetPersonTracking`은 비디오에서 감지된 인물에 대한 세부 정보와 그들의 경로가 추적된 시점을 포함하는 [PersonDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_PersonDetection.html) 객체의 배열인 `Persons`를 반환합니다.

`Persons` 입력 파라미터를 사용하여 `SortBy`를 정렬할 수 있습니다. 비디오에서 사람들의 경로를 추적하는 시간을 기준으로 요소를 정렬하려면 `TIMESTAMP`를 지정하십시오. 비디오에서 추적한 인물을 기준으로 정렬하려면 `INDEX`를 지정하십시오. 인물에 대한 각 결과 세트 내에서 경로 추적의 정확도에 대한 내림차순 신뢰도에 따라 요소가 정렬됩니다. 기본적으로 `Persons`은 `TIMESTAMP`를 기준으로 정렬되어 반환됩니다. 다음 예제는 `GetPersonDetection`의 JSON 응답입니다. 결과는 비디오가 시작된 이후부터 비디오에 인물의 경로가 추적된 시간(밀리초)에 따라 정렬됩니다. 응답에서 다음에 유의하십시오.
+ **인물 정보** - `PersonDetection` 배열 요소에는 감지된 인물에 대한 정보가 포함되어 있습니다. 예를 들어 인물이 감지된 시간(`Timestamp`), 감지 당시 비디오 프레임에 있는 인물의 위치(`BoundingBox`), 인물 감지의 정확성에 대한 Amazon Rekognition Video​​​의 신뢰도(`Confidence`)입니다.

  사람의 경로가 추적되는 모든 타임스탬프에서 얼굴 특징은 반환되지 않습니다. 또한 상황에 따라 추적한 인물의 몸이 보이지 않을 수 있으며 이 경우 얼굴 위치만 반환됩니다.
+ **페이징 정보** - 이 예제는 인물 감지 정보의 페이지 하나를 보여줍니다. `MaxResults`의 `GetPersonTracking` 입력 파라미터에 반환될 사람 요소의 수를 지정할 수 있습니다. `MaxResults` 보다 많은 결과가 존재할 경우 `GetPersonTracking`은 결과의 다음 페이지를 가져올 때 사용되는 토큰(`NextToken`)을 반환합니다. 자세한 내용은 [Amazon Rekognition Video 분석 결과 가져오기](api-video.md#api-video-get) 섹션을 참조하세요.
+ **인덱스** - 비디오 전체에서 인물을 식별하기 위한 고유 식별자입니다.
+ **비디오 정보** - 응답에는`GetPersonDetection`에서 반환된 정보의 각 페이지에 있는 비디오 형식(`VideoMetadata`)에 관한 정보가 포함되어 있습니다.

```
{
    "JobStatus": "SUCCEEDED",
    "NextToken": "AcDymG0fSSoaI6+BBYpka5wVlqttysSPP8VvWcujMDluj1QpFo/vf+mrMoqBGk8eUEiFlllR6g==",
    "Persons": [
        {
            "Person": {
                "BoundingBox": {
                    "Height": 0.8787037134170532,
                    "Left": 0.00572916679084301,
                    "Top": 0.12129629403352737,
                    "Width": 0.21666666865348816
                },
                "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
                    }
                },
                "Index": 0
            },
            "Timestamp": 0
        },
        {
            "Person": {
                "BoundingBox": {
                    "Height": 0.9074074029922485,
                    "Left": 0.24791666865348816,
                    "Top": 0.09259258955717087,
                    "Width": 0.375
                },
                "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
                    }
                },
                "Index": 1
            },
            "Timestamp": 0
        }.....

    ],
    "VideoMetadata": {
        "Codec": "h264",
        "DurationMillis": 67301,
        "FileExtension": "mp4",
        "Format": "QuickTime / MOV",
        "FrameHeight": 1080,
        "FrameRate": 29.970029830932617,
        "FrameWidth": 1920
    }
}
```