Rest API

AmazonRekognition을 사용하여 객체탐지(Object detection) API 개발

왕현성 2023. 1. 12. 17:38
728x90

Amazon Rekognition란?

 

Amazon Rekognition Rekognition을 사용하면 애플리케이션에 이미지 및 비디오 분석을 쉽게 추가할 수 있습니다. Amazon Rekognition API에 이미지나 비디오를 제공하면 서비스에서 객체, 사람, 텍스트, 장면 및 활동을 식별할 수 있습니다. 부적절한 콘텐츠를 감지할 수도 있습니다. Amazon Rekognition Rekognition은 매우 정확한 얼굴 분석, 얼굴 비교 및 얼굴 검색 기능도 제공합니다. 사용자 확인, 카탈로그 작성, 인원 계산 및 공공 안전을 포함하여 다양한 사용 사례에서 얼굴을 탐지, 분석, 비교할 수 있습니다.

 

자세한 설명 : https://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/what-is.html

 

Amazon Rekognition 란 무엇입니까? - Amazon Rekognition

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다. Amazon Rekognition 란 무엇입니까? Amazon Rekognition Rekognition을 사용하면 애플리케

docs.aws.amazon.com

우선 사용하기 위해 AWS IAM에서 권한을 추가해줍니다.

App.py 코드

from flask import Flask
from flask_restful import Api
from config import Config
from flask_jwt_extended import JWTManager

from resources.image import FileUploadResource
from resources.rekognition import ObjectDetectionResource


app = Flask(__name__)
# 환경변수 셋팅
app.config.from_object(Config)

# JWT 매니저 초기화
jwt=JWTManager(app)



api = Api(app)
# 경로와 리소스 코드를 연결한다.
api.add_resource(FileUploadResource,'/upload')
api.add_resource(ObjectDetectionResource,'/object_detection')


if __name__ == '__main__' :
    app.run()

rekognition.py 코드

코드 안에 주석처리로 설명이 쓰여져있습니다.

from flask import request
from flask_restful import Resource
from flask_jwt_extended import create_access_token,jwt_required,get_jwt
from flask_jwt_extended import create_access_token,jwt_required,get_jwt
from mysql.connector import Error
from mysql_connection import get_connection
from datetime import datetime
import boto3
from config import Config

class ObjectDetectionResource(Resource) :
    
    # S3에 저장되어있는 이미지를
    # 객체 탐지하는 API
    
    def get(self) :

        # 1. 클라이언트로부터 파일명을 받아온다.
        filename = request.args.get('filename')
        # 2. 위의 파일은 이미 S3에 있는 상황
        # 따라서 AWS의 Rekognition 인공지능 서비스를 이용해서
        # Object detection한다.


        # 리코그니션 서비스를 이용할 수 있는지
        # IAM의 유저 권한 확인하고 설정해준다.
        client=boto3.client('rekognition',
                    'ap-northeast-2',
                    aws_access_key_id=Config.ACCESS_KEY,
                    aws_secret_access_key=Config.SECRET_ACCESS)
        response=client.detect_labels(Image={'S3Object':{'Bucket':Config.S3_BUCKET,'Name':filename}},
                            MaxLabels= 10 )

        print(response['Labels'][0])

        for label in response['Labels']:
            print ("Label: " + label['Name'])
            print ("Confidence: " + str(label['Confidence']))
            print ("Instances:")
            for instance in label['Instances']:
                print ("  Bounding box")
                print ("    Top: " + str(instance['BoundingBox']['Top']))
                print ("    Left: " + str(instance['BoundingBox']['Left']))
                print ("    Width: " +  str(instance['BoundingBox']['Width']))
                print ("    Height: " +  str(instance['BoundingBox']['Height']))
                print ("  Confidence: " + str(instance['Confidence']))
                print()
                print ("Parents:")
                for parent in label['Parents']:
                    print ("   " + parent['Name'])
                    print ("----------")
                    print ()
        return {'result':'success','Labels':response['Labels']},200

포스트맨 테스트 결과

{
    "result": "success",
    "Labels": [
        {
            "Name": "Rodent",
            "Confidence": 99.51905822753906,
            "Instances": [],
            "Parents": [
                {
                    "Name": "Animal"
                },
                {
                    "Name": "Mammal"
                }
            ],
            "Aliases": [],
            "Categories": [
                {
                    "Name": "Animals and Pets"
                }
            ]
        },
        {
            "Name": "Mammal",
            "Confidence": 99.51905822753906,
            "Instances": [],
            "Parents": [
                {
                    "Name": "Animal"
                }
            ],
            "Aliases": [],
            "Categories": [
                {
                    "Name": "Animals and Pets"
                }
            ]
        },
        {
            "Name": "Animal",
            "Confidence": 99.51905822753906,
            "Instances": [],
            "Parents": [],
            "Aliases": [],
            "Categories": [
                {
                    "Name": "Animals and Pets"
                }
            ]
        },
        {
            "Name": "Rat",
            "Confidence": 98.81503295898438,
            "Instances": [
                {
                    "BoundingBox": {
                        "Width": 0.8761737942695618,
                        "Height": 0.992196798324585,
                        "Left": 0.12026045471429825,
                        "Top": 0.005233540665358305
                    },
                    "Confidence": 98.81503295898438
                }
            ],
            "Parents": [
                {
                    "Name": "Animal"
                },
                {
                    "Name": "Mammal"
                },
                {
                    "Name": "Rodent"
                }
            ],
            "Aliases": [],
            "Categories": [
                {
                    "Name": "Animals and Pets"
                }
            ]
        },
        {
            "Name": "Squirrel",
            "Confidence": 98.1663589477539,
            "Instances": [],
            "Parents": [
                {
                    "Name": "Animal"
                },
                {
                    "Name": "Mammal"
                },
                {
                    "Name": "Rodent"
                }
            ],
            "Aliases": [],
            "Categories": [
                {
                    "Name": "Animals and Pets"
                }
            ]
        }
    ]
}