본문 바로가기
Restful API

[Restful API] S3에 저장한 이미지를 객체 탐지하는 API만들기(Rekognition)

by coding_su 2023. 1. 12.

📝S3에 저장한 이미지를 객체 탐지하는 API만들기

Amazon Rekognition을 사용하여 Object Detection 결과를 응답하는 API를 만들어 보겠다

 

우선 포스트맨에서 경로를 설정해주고 ex) http://localhost:5000/object_detection

GET으로 Params에 키값을 입력하고 밸류에 S3에 저장한 파일명을 입력해준다

Visual Studio Code를 실행해 코드를 작성해준다

※ rekognition을 사용하기 위해서 IAM에서 AmazonRekognitionFullAccess 권한 추가

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

class ObjectDetectionResource(Resource) :

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

        # 클라이언트로부터 파일명을 받아온다
        filename = request.args.get('filename')

        # 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)

        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

+ Amazon Rekognition 메뉴얼 확인

(https://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/what-is.html)

 

객체 탐지한 이름만 가져와서 태그로 만들고 싶다면 for루프 하나만 추가해주면 된다

Labels_list = []
for i in response['Labels'] :
    Labels_list.append(i['Name'])
    
return {"result" : "success", "Labels" : Labels_list}, 200

※ 구조파악을 쉽게 하기 위해서 json online editor 활용하기(https://jsoneditoronline.org/)

댓글