대학교 시절 프로젝트 성으로 잠깐 약간 맛만 봤었는데 이번 게임데이 준비하면서 좀 더 깊게 파볼 생각...

딥 러닝 기반 시각 분석 서비스 인데.. 신기하다 신기해! 약간 YOLO랑 비슷한 느낌?

 

참고: https://aws.amazon.com/ko/blogs/machine-learning/build-your-own-face-recognition-service-using-amazon-rekognition


  • Indexing(blue flow): 나중에 분석하기 위해 얼굴 이미지를 컬렉션으로 가져오는 프로세스
  • Analysis(black flow): 인덱스 내에서 일치하는 얼굴 컬렉션 쿼리하는 프로세스

  • CloudFormation 실행(한번에 다 설치해줌...)

템플릿 다운

위의 이미지는 스택 생성 후 생성된 리소스들이다. 과정 하나씩 살펴보자.

  • rekognition create-collection
aws rekognition create-collection --collection-id family-collection

위의 명령어를 AWS CLI에 입력해 collection을 생성하는 과정을 거친다.

 

  • DynamoDB create-table

RekognitionId 를 파티션 키로 family-collection 테이블을 생성했다.

 

  • IndexFaces 작업

S3 버킷 생성

 

IAM 역할 설정

1) S3 객체에 액세스할 수 있는 권한을 lambda에 부여

2) Rekognition의 IndexFaces 함수를 시작하고 FaceId 간의 매핑을 위해 DynamoDB key-value 저장소 내에 여러 항목 생성  가능

더보기
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::training-bucket-221004/*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "rekognition:IndexFaces"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "dynamodb:PutItem"
            ],
            "Resource": "arn:aws:dynamodb:<Region>:<ACCOUNT-ID>:table/family-collection",
            "Effect": "Allow"
        }
    ]
}

해당 IAM 역할을 Lambda 함수에 붙여주자.

 

마지막으로 새 사진이 S3에 업로드될 때마다 트리거되는 Lambda 함수 생성(트리거 추가)

 

해당 lambda 함수에 코드 넣어주기.

1) Rekognition IndexFaces API를 사용하여 입력 이미지에서 얼굴을 감지하고 지정된 컬렉션에 추가

2) 성공하면 S3에 있는 객체의 메타데이터에서 사람의 전체 이름을 검색, 그런 다음 나중에 참조할 수 있도록 DynamoDB 테이블에 FaceId가 있는 key-value 튜플로 저장

더보기
import os
import boto3
from decimal import Decimal
import json
import urllib

print('Loading function')

dynamodb = boto3.client('dynamodb')
s3 = boto3.client('s3')
rekognition = boto3.client('rekognition')


# --------------- Helper Functions ------------------

def index_faces(bucket, key):
    CollectionId = os.getenv("CollectionName")

    response = rekognition.index_faces(
        Image={"S3Object": {"Bucket": bucket, "Name": key}},
        CollectionId=CollectionId,
    )
    return response


def update_index(tableName,faceId, fullName):
    response = dynamodb.put_item(
        TableName=tableName,
        Item={
        'RekognitionId': {'S': faceId},
        'FullName': {'S': fullName}
        }
    )

# --------------- Main handler ------------------

def lambda_handler(event, context):

    # Get the object from the event
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
              

    try:
        # Calls Amazon Rekognition IndexFaces API to detect faces in S3 object
        # to index faces into specified collection
        response = index_faces(bucket, key)

        # Commit faceId and full name object metadata to DynamoDB
        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            faceId = response['FaceRecords'][0]['Face']['FaceId']

            ret = s3.head_object(Bucket=bucket,Key=key)
            personFullName = ret['Metadata']['fullname']

            update_index(os.getenv("DynamoDBTableName"), faceId, personFullName)

        # Print response to console.
        print(response)

        return response
    except Exception as e:
        print(e)
        print("Error processing {} from bucket {}. ".format(key, bucket)) 
        raise e

 

이후에 이미지를 S3에 업로드한 뒤에 해당 코드를 통해 Face collection을 시드할 수 있다.

(현재는 S3 버킷에 이미지가 없음....;; 따라서 코드 실행에 에러 나는게 당연하다..?)

 

해당 컬렉션이 잘 만들어졌는지 확인하기 위해선

aws rekognition list-faces --collection-id family-collection

 

위의 명령어를 사용하면 된다.

 

  • 분석 작업

컬렉션이 채워지면 얼굴이 포함된 다른 이미지를 전달하여 쿼리가 가능하다.

SearchFacesByImageAPI를 사용하여 쿼리할 컬렉션 이름과 분석할 이미지에 대한 참조 두 가지 이상의 매개변수 제공

아래의 코드는 이미지를 bytestream으로 제출하는 방법을 보여준다.

(응답의 경우 일치 항목의 FaceId가 포함된 JSON 객체를 반환, (메타데이터 중 신뢰도 점수, 이미지 내 얼굴의 좌표))

더보기
import boto3
import io
from PIL import Image

rekognition = boto3.client('rekognition', region_name='eu-west-1')
dynamodb = boto3.client('dynamodb', region_name='eu-west-1')
    
image = Image.open("group1.jpeg")
stream = io.BytesIO()
image.save(stream,format="JPEG")
image_binary = stream.getvalue()


response = rekognition.search_faces_by_image(
        CollectionId='family_collection',
        Image={'Bytes':image_binary}                                       
        )
    
for match in response['FaceMatches']:
    print (match['Face']['FaceId'],match['Face']['Confidence'])
        
    face = dynamodb.get_item(
        TableName='family_collection',  
        Key={'RekognitionId': {'S': match['Face']['FaceId']}}
        )
    
    if 'Item' in face:
        print (face['Item']['FullName']['S'])
    else:
        print ('no match found in person lookup')

 

 

❗ 우씨 뭐가뭔지 모르겠다... Rekognition 구조부터 파악하고 해봐야할듯?! ❗

'Cloud > AWS' 카테고리의 다른 글

[AWS] Lambda Layer  (0) 2022.10.07
[AWS] Amazon Rekognition 개념  (1) 2022.10.05
[AWS] EC2로 MQTT 통신 테스트  (0) 2022.09.27
[AWS] Amazon Kinesis 개념  (0) 2022.09.26
[AWS] IoT Core 살펴보기 -4(데이터 레이크)  (0) 2022.09.26

참고: https://catalog.us-east-1.prod.workshops.aws/workshops/4a2a9a24-071d-4d96-b9be-0cc57b7db434/en-US

Rekognition에 궁금증이 생겨 좀 다뤄볼까 한다..

(꼭.. us-east-1에서 진행하세요!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!)


Preprocessing

  • S3에 데이터 업로드

버킷을 하나 생성해주고 aws 로고 이미지들을 '버킷/aws' 경로로 올려준다.

 

  • Rekognition 프로젝트 만들기

Rekognition → 사용자 지정 레이블 만들기(Custom Labels)

❗ 프로젝트를 눌러 생성하면 되는데.. 왜 자꾸 처음에 s3 버킷을 생성하라고 뜰까?! ❗

과정을 마치고 해당 버킷으로 돌아와 보면 위 이미지 처럼 객체들이 들어가있다.

아마 생성했던 프로젝트들, 라벨들을 관리(?) 하는 버킷의 느낌이다.

 

 

  • Dataset 생성

single dataset으로 선택 후

아까 생성했던 s3 버킷으로 지정하고 라벨링을 위한 작업을 위해 해당 체크 표시를 해준다.

(Automatically assign image-level labels to images based on the folder name)

 

정책을 복사해 버킷 정책에 붙여 넣는다.

해당 파란색 링크를 클릭하면 알아서 해당 버킷으로 데려가 줌!

정책을 붙여넣고 create dataset 클릭.

 

  • Start labeling

이미지들 선택 후에 Draw bounding boxes 선택(단일 페이지에서만 이미지 선택 가능 - 첫번째 페이지 하고 두번 째)

이런 식으로 aws 로고 선택해주자..

단순 반복 작업...

다 끝내면 Save changes 버튼을 클릭해준다.

 

 

Training

  • Train model

Train model을 클릭한다.

방금 생성한 프로젝트를 선택하고 Train model 클릭

(모델 트레이닝은 50-60분 정도 소요된다...?! 취소하고 싶으면 CLI 환경에서 모델 트레이닝 중지를 시켜야함.. 콘솔 불가)

 

Inference

와... 서울 리전 데모 애플리케이션이 없다... 대충 이런 프로세스 느낌이라는 것만 알면 될 듯...?

(여러분은 us-east-1으로 진행하세요...😥)

https://github.com/aws-samples/amazon-rekognition-custom-labels-demo

과정만 간단히 살펴 보자면..

 모델의 상태가 TRAINING_COMPLETED 인 경우에 훈련이 끝난 것..

모델을 클릭하고 레이블별 성능을 확인해본다. 만족 시 Use model을 클릭해서 사용하면 된다.

 

이후 과정에선 저 위의 링크에 들어가 CloudFormation으로 애플리케이션을 활용해 테스트 해보는 과정인데..

잘못된 리전 선택으로.. 하지 못했..다...ㅠㅠ

무튼 이미지를 넣고 Results에 신뢰도 점수가 표시된다!

그리고 테스트가 끝나면 Stop the model 클릭을 하는 거 까지가 과정이다!!

+ Recent posts