DevOps/AWS

AWS S3와 연결하여 AWS Rekognition으로 이미지 인식 태그 API 만들기

567Rabbit 2024. 5. 28. 15:10

https://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/labels-detect-labels-image.html

 

이미지에서 레이블 감지 - Amazon Rekognition

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다. 이미지에서 레이블 감지 이 DetectLabels작업을 사용하여 이미지에서 레이블 (

docs.aws.amazon.com

- 메뉴얼을 참고한다.

 

 

 

 

아래를 참고하여 버킷을 만든다.

 

https://msdev-st.tistory.com/155

 

[AWS] S3 버킷 만들기 _ 스토리지 만들어서 사용하기

S3 버킷 만들기 _ 스토리지 만들어서 사용하기AWS의 S3란? Simple Storage Service의 약자로 파일 서버의 역할을 하는 서비스다. 일반적인 파일서버는 트래픽이 증가함에 따라서 장비를 증설하는 작

msdev-st.tistory.com

 

 

 

 

 

aws의 IAM에서,  AmazonRekognitionFullAcess 권한추가하기

 

 

 

 

 

 

 

serverless로 만든 폴더를 vscode로 연다.

 

 

 

 

 

버킷 만들 때 사용한 이름을 넣으면 된다.

 

 

 

 

 

app.py 작성

from flask import Flask
from flask_restful import Api

from resources.image import FileUploadResource

app = Flask(__name__)

api = Api(app)

# 경로와 리소스를 연결한다.
api.add_resource( FileUploadResource , '/upload' )

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

 

 

 

 

 

resources 폴더 안에 image.py 작성

from flask_restful import Resource
from flask import request

from datetime import datetime

import boto3

from config import Config


class FileUploadResource(Resource) :

    def post(self):
        # 1. 클라이언트로부터 데이터를 받아온다.
        #    파일은 request.files 안에 있고,
        #    텍스트는 request.form 안에 있다.

        if 'photo' not in request.files :
            return {"result":"fail", "error":"파일을 업로드 하세요."}, 400
        
        if 'content' not in request.form :
            return {"result":"fail", "error":"내용을 작성 하세요."}, 400
        
        file = request.files.get('photo')
        
        if 'image' not in file.content_type :
            return {'result':'fail',
                    'error':'이미지 파일만 업로드 가능합니다'}, 400
        
        print(file)

        content = request.form['content']
        print(content)

        # 파일을 s3에 업로드 해야 하는데,
        # 먼저, 파일명은 유니크 해야 한다.
        # 따라서, 유니크한 파일명으로 바꿔서 업로드 한다.

        # 현재시간과 유저아이디 등을 조합해서 만든다.
        current_time = datetime.now()
        file_name = current_time.isoformat().replace(':','_') + '.' + file.content_type.split('/')[-1]
        print(file_name)

        # 유저가 업로드한 파일명을, 내가 만든 파일명으로 바꾼다.
        file.filename = file_name

        # s3에 파일을 업로드한다.
        # aws의 서비스들을 파이썬코드로 작성 할 수 있는 
        # boto3 라이브러리를 이용해서 코드를 작성한다.
        # ( 설치는, $ pip install boto3 )

        client = boto3.client('s3' ,
                               aws_access_key_id = Config.AWS_ACCESS_KEY,
                               aws_secret_access_key = Config.AWS_SECRET_ACCESS_KEY)

        # ExtraArgs = {'ACL':'public-read','ContentType':'image/jpg'} 중요부분

        try :
            client.upload_fileobj(file,
                                  Config.S3_BUCKET,
                                  file_name,
                                  ExtraArgs = {'ACL':'public-read',
                                               'ContentType':file.content_type})
        except Exception as e:
            return {"result":"fail", "error":str(e)}, 500


        return {"result":"success", "url":Config.S3_URL + file_name}

 

 

 

vscode cmd에서 설치한다.

pip install boto3

 

 

 

rekognition.py 작성

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

from config import Config


class ObjectDetectionResource(Resource):
    def post(self):

        if 'photo' not in request.files :
            return {"result":"fail", "error":"사진은 필수입니다."}, 400
        
        file = request.files['photo']

        if 'image' not in file.content_type :
            return {"result":"fail", "error":"이미지파일을 업로드 하세요."}, 400
        
        current_time = datetime.now()
        file_name = current_time.isoformat().replace(':','_') + '.jpg'

        file.filename = file_name

        # s3에 업로드
        # rekognition 서비스를 이용하려면,
        # 먼저 s3에 이미지 파일을 업로드 해놔야 한다

        client = boto3.client('s3',
                     aws_access_key_id = Config.AWS_ACCESS_KEY,
                     aws_secret_access_key = Config.AWS_SECRET_ACCESS_KEY)
        
        try :
            client.upload_fileobj(file,
                                  Config.S3_BUCKET,
                                  file_name,
                                  ExtraArgs = {'ACL' : 'public-read',
                                               'ContentType':'image/jpeg'})
        except Exception as e:
            return {"result":"fail", "error":str(e)}, 500


        # 리코그니션을 이용
        label_list = self.detect_labels(file_name, Config.S3_BUCKET)
        

        return {"result":"success", "lable": label_list}
    
    def detect_labels(self, photo, bucket):

        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_labels(Image={'S3Object':{'Bucket':bucket,'Name':photo}},
        MaxLabels=10,
        # Uncomment to use image properties and filtration settings
        #Features=["GENERAL_LABELS", "IMAGE_PROPERTIES"],
        #Settings={"GeneralLabels": {"LabelInclusionFilters":["Cat"]},
        # "ImageProperties": {"MaxDominantColors":10}}
        )

        print('Detected labels for ' + photo)
        print()
        print(response['Labels'])

        label_list = []

        for label in response['Labels']:
            print("Label: " + label['Name'])
            label_list.append(label['Name'])



        return label_list

 

 

 

 

 

 

사진 업로드 API 포스트맨 작성

 

 

 

 

 

send하고, s3 버킷에 들어가보면 아래처럼 사진을 send한 목록들이 뜬다.

 

 

 

 

 

 

object detection API 포스트맨 작성하고 send하면

 

 

 

 

 

vscode에서는 이렇게 뜬다.

 

 

 

 

 

 

 

.jpeg, .jpg 등의 타입 설명 홈페이지 링크이다.

 

https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

 

Common MIME types - HTTP | MDN

This topic lists the most common MIME types with corresponding document types, ordered by their common extensions.

developer.mozilla.org