API 개발/AWS S3 & Rekognition API 파일 업로드

AWS rekognition : AWS rekognition 활용한 얼굴 인식 API

신강희 2024. 6. 25. 10:32
728x90

< AWS rekognition 활용한 얼굴 인식 API >

 

# Amazon Rekognition은 AWS에서 제공하는 이미지 및 비디오 분석 서비스로, 이 서비스는 기계 학습 모델을 사용하여 다양한 객체, 장면, 얼굴, 텍스트 등을 감지하고 분석할 수 있게 해준다.

 

# 주요 기능

  1. 객체 및 장면 감지 (Object and Scene Detection):
    • 이미지나 비디오에서 사람, 동물, 차량 등 다양한 객체와 장면을 감지할 수 있습니다.
  2. 텍스트 감지 (Text Detection):
    • 이미지와 비디오에서 텍스트를 감지하고 추출할 수 있습니다. OCR(Optical Character Recognition) 기능을 제공합니다.
  3. 얼굴 감지 및 분석 (Face Detection and Analysis):
    • 이미지나 비디오에서 얼굴을 감지하고, 성별, 나이, 감정 등의 얼굴 속성을 분석할 수 있습니다.
  4. 얼굴 비교 (Face Comparison):
    • 두 개의 얼굴 이미지를 비교하여 동일 인물인지 여부를 확인할 수 있습니다.
  5. 유해 콘텐츠 감지 (Content Moderation):
    • 이미지와 비디오에서 폭력적이거나 성인용 콘텐츠 등 유해 콘텐츠를 감지할 수 있습니다.
  6. 유사 이미지 검색 (Image and Video Search):
    • 대규모 이미지 및 비디오 컬렉션에서 유사한 이미지와 비디오를 검색할 수 있습니다.
  7. 모션 감지 및 추적 (Activity and Movement Detection):
    • 비디오에서 사람의 동작과 활동을 감지하고 추적할 수 있습니다.
  8. Custom Labels:
    • 사용자 정의 라벨을 생성하여 특정 비즈니스 요구에 맞춘 모델을 학습시키고 사용할 수 있습니다.

# 참고 URL : https://ap-northeast-2.console.aws.amazon.com/rekognition/home?region=ap-northeast-2#/

 

https://ap-northeast-2.console.aws.amazon.com/rekognition/home?region=ap-northeast-2#/

 

ap-northeast-2.console.aws.amazon.com

 

# 이중 얼굴 감지 및 분석 기능과 얼굴 비교 기능 구현!

 

# 이전에 작성했었던 S3 업로드 프로젝트에 파일을 추가하여 신규 클래스로 작성

- 참고 : https://sorktjrrb.tistory.com/170

 

Restful API : AWS boto3 로 S3에 파일 업로드 하기

# Boto3 란??- Boto3는 Python 프로그래밍 언어를 위한 AWS SDK(Software Development Kit)- Boto3를 사용하면 Python 애플리케이션에서 Amazon Web Services(AWS)의 다양한 서비스와 쉽게 상호 작용할 수 있다. - Boto3는 AWS

sorktjrrb.tistory.com

 

# facedetection.py 파일 생성하여 작성

 
from flask import request
from flask_restful import Resource
from datetime import datetime
import boto3
from config import Config

class FaceDetectionResource(Resource):

    # 얼군인식 API
    def post(self) :
        # 1. 클라이언트로부터 데이터를 받아온다.
        file = request.files.get('photo')
        # 2 S3에 저장한다.
        if file is None :
            return {'error' : '파일을 업로드 하세요'}, 400
        current_time = datetime.now()
        new_file_name = current_time.isoformat().replace(':','_') + '.jpg'

        # 유저가 올린 파일의 이름을 새로운 파일 이름으로 변경한다.
        file.filename = new_file_name

        # S3에 업로드를 위해 boto3 라이브러리를 사용.        
        # boto3 라이브러리는, AWS의 모든 서비스를
        # 파이썬 코드로 작성할 수 있는 라이브러리이다. => pip install boto3 설치
        s3 = boto3.client( 's3',
                     aws_access_key_id = Config.AWS_ACCESS_KEY,
                     aws_secret_access_key = Config.AWS_SECRET_ACCESS_KEY)    
        try :
            s3.upload_fileobj(file, Config.S3_BUCKET,
                            file.filename,
                            ExtraArgs = {'ACL' : 'public-read', 'ContentType' : 'image/jpeg'} )
        except Exception as e :
                            print(e)
                            return {'error' : str(e)}, 500
       
        # 3 S3에 이미지가 있으니,
        # rekognition 을 이용해서,
        # object detection 한다.
        region = 'ap-northeast-2'
        faces_list = self.detect_faces(new_file_name,Config.S3_BUCKET,region)

    # 얼굴 감지 함수
    def detect_faces(self, photo, bucket, region):
        client = boto3.client('rekognition',
                     'ap-northeast-2',
                     aws_access_key_id = Config.AWS_ACCESS_KEY,
                     aws_secret_access_key = Config.AWS_SECRET_ACCESS_KEY)
        response = client.detect_faces(Image={'S3Object':{'Bucket':bucket,'Name':photo}},
                                   Attributes=['ALL'])
        print('Detected faces for ' + photo)
        faces_list = []
        for faceDetail in response['FaceDetails']:
            face_info = {
                "성별": str(faceDetail['Gender']),
                '예상 연령대 ': str(faceDetail['AgeRange']['Low'])
                + ' ~ ' + str(faceDetail['AgeRange']['High']) + '세',
                "웃고있는가?": str(faceDetail['Smile']),
                "안경 착용 여부": str(faceDetail['Eyeglasses']),
                "얼굴 가려짐 여부": str(faceDetail['FaceOccluded']),
                "표정": str(faceDetail['Emotions'][0]),
                "눈 뜬 여부": str(faceDetail['EyesOpen'])
            }
            faces_list.append(face_info)
            print("성별: " + str(faceDetail['Gender']))
            print("웃고있는가?: " + str(faceDetail['Smile']))
            print("안경 착용 여부: " + str(faceDetail['Eyeglasses']))
            print("얼굴 가려짐 여부: " + str(faceDetail['FaceOccluded']))
            print("표정: " + str(faceDetail['Emotions'][0]))
            print('예상 연령대: ' + str(faceDetail['AgeRange']['Low'])
                + '세 ~ ' + str(faceDetail['AgeRange']['High']) + '세')            
            print("눈 뜬 여부" + str(faceDetail['EyesOpen']))
        return (faces_list)
   
    # S3로 저장후 불러오는 코드
    def post(self) :
        # 1 클라이언트로부터 데이터를 받아온다.
        file = request.files.get('photo')

        # 2 S3에 저장한다.
        if file is None :
            return {'error' : '파일을 업로드 하세요'}, 400
        current_time = datetime.now()
        new_file_name = current_time.isoformat().replace(':','_') + '.jpg'

        # 유저가 올린 파일의 이름을 새로운 파일 이름으로 변경한다.
        file.filename = new_file_name

        # S3에 업로드를 위해 boto3 라이브러리 사용      
        s3 = boto3.client( 's3',
                     aws_access_key_id = Config.AWS_ACCESS_KEY,
                     aws_secret_access_key = Config.AWS_SECRET_ACCESS_KEY)    
                     
        try :
            s3.upload_fileobj(file, Config.S3_BUCKET,
                              file.filename,
                              ExtraArgs = {'ACL' : 'public-read', 'ContentType' : 'image/jpeg'} )
        except Exception as e :
            print(e)
            return {'error' : str(e)}, 500
   
        # 3 S3에 이미지가 있으니,
        # rekognition 을 이용해서,
        # object detection 한다.
        region = 'ap-northeast-2'
        faces_list = self.detect_faces(new_file_name,Config.S3_BUCKET,region)
       
       
        # 추가된 리턴부분
        return {'result' : 'success',
            'list' : faces_list,
            'count' : len(faces_list)
            }, 200
 

 

# app.py 파일에도 연결 코드 작성

 
from flask import Flask
from flask_restful import Api

from resources.facematch import FaceMatchResource
from resources.image import FileUploadResource
from resources.rekognition import ObjectDetectionResource
from resources.facedetection import FaceDetectionResource

app = Flask(__name__)

api = Api(app)

# 경로와 리소스를 연결하는 코드 작성
api.add_resource( FileUploadResource , '/upload' )
api.add_resource( ObjectDetectionResource , '/object_detection' )
api.add_resource( FaceDetectionResource , '/face_detection' )
 

 

# 이제 flask run 실행 후 post man 으로 테스트!

 

# 다른 사진도 평가해보자!

 

# VS Code에 CMD 창에서도 결과를 확인할수 있다.

 

다음 게시글로 계속~!

 

반응형