Rest API

AmazonRekognition을 사용하여 객체탐지(Object detection) / 자동 태그 API 개발

왕현성 2023. 1. 13. 11:11
728x90
 

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

Amazon Rekognition란? Amazon Rekognition Rekognition을 사용하면 애플리케이션에 이미지 및 비디오 분석을 쉽게 추가할 수 있습니다. Amazon Rekognition API에 이미지나 비디오를 제공하면 서비스에서 객체, 사람

hyunsungstory.tistory.com

 

 

API 설계는 위와같이 진행 하였고

class PhotoRekognitionResource(Resource) :
    def post(self) :
        
        if 'photo' not in request.files :
            return {'error':'파일 업로드 하세요'},400

        file = request.files['photo']

        # 클라이언트가 보낸 파일의 파일명을
        # 변경시켜서 S3에 올려야 유니크하게 
        # 파일을 관리할 수 있다.

        # 파일명을 유니크하게 만드는 방법
        current_time=datetime.now()
        new_file_name=current_time.isoformat().replace(':','_') + '.jpg'

        print(new_file_name)

        # 파일명을, 유니크한 이름으로 변경한다.
        # 클라이언트에서 보낸 파일명을 대체!

        file.filename = new_file_name

        # S3에 파일을 업로드하면 된다.
        # S3에 파일 업로드하는 라이브러리가 필요
        # boto3 라이브러리를 이용해서 업로드한다.
        # 참고 : 라이브러리 설치는 pip install boto3

        client=boto3.client('s3',
                    aws_access_key_id = Config.ACCESS_KEY ,
                    aws_secret_access_key = Config.SECRET_ACCESS)
        
        try :
            client.upload_fileobj(file,Config.S3_BUCKET,new_file_name,
                                    ExtraArgs ={'ACL':'public-read','ContentType':file.content_type})
        
        except Exception as e :
            return {'error':str(e)}, 500

        # 리코그니션 서비스를 이용할 수 있는지
        # 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':new_file_name}},
                            MaxLabels= 10 )

        num=np.arange(0,9+1)
        print(response['Labels'][0]['Name'])
        print(num)
        labels = []
        for x in num :
            labels.append(response['Labels'][x]['Name'])
        
        print (labels)

        

        # 위의 response에서 필요한 데이터만 가져와서
        # 클라이언트에게 보내준다
        # labels : [  ]


        return {'result':'success','labels':labels},200

코드는 이렇게 작성하였습니다.

 

response 변수에 저장한 것은 Json으로 구성되어있는데 구조를 파악하기 위해 

https://jsoneditoronline.org/

 

JSON Editor Online: JSON editor, JSON formatter, query JSON

You need to enable JavaScript to run this app. JSON Editor Online JSON Editor Online is a web-based tool to view, edit, format, repair, compare, query, transform, validate, and share your JSON data. About JSON Editor Online JSON Editor Online is a versatil

jsoneditoronline.org

위 사이트에서 

ctrl + f 를 눌러 ' 는 Json에서 인식을 안 하기 때문에 "로 Replace All 해준 뒤 구조 파악을 한 결과

 

response['Labels'][x]['Name']

위 코드로 데이터 억세스를 하면 자동 태그 추천을 하기 위한 Name만 가져올 수 있었다.

 

포스트맨 테스트 결과