본문 바로가기
데이터/AWS

[AWS]AWS CLI 개발환경 구축 & 객체감지(Rekognition) 연습

by stubborngastropod 2023. 3. 26.
728x90

우분투 환경에서 개발하는 것을 전제로 한다.

  • 패키지 목록 업데이트, 파이썬 및 pip, AWS CLI 설치
sudo apt update
sudo apt install python3
sudo apt install python3-pip
sudo apt install awscli

AWS 사용자 권한을 CLI에 부여하기 위해 IAM 서비스에서 액세스 키와 비밀 액세스 키를 붙여넣는다. 리전은 미국 동부 버지니아, 출력 포맷은 JSON으로 한다.

aws configure
AWS Access Key ID [None]: <AWS 액세스 키>
AWS Secret Access Key [None]: <AWS 비밀 액세스 키>
Default region name [None]: us-east-1
Default output format [None]: json
  • CLI로 Rekognition 서비스 호출

s3에 존재하는 버킷 확인

aws s3 ls
# contents.stubborngastropod.ai
# data.stubborngastropod.ai
# website.stubborngastropod.ai

해당 버킷에 존재하는 파일 확인

aws s3 ls s3://contents.stubborngastropod.ai
# 4309941 pexels-lisa-fotios-15658259.jpg

객체 탐지 기능 호출

aws rekognition detect-labels --image S3Object=\Bucket=contents.stubborngastropod.ai,Name=pexels-lisa-fotios-15658259.jpg\}

<<
{
    "Labels": [
        {
            "Name": "Indoors",
            "Confidence": 99.97044372558594,
            "Instances": [],
            "Parents": [],
            "Aliases": [],
            "Categories": [
                {
                    "Name": "Home and Indoors"
                }
            ]
        },
        {
            "Name": "Restaurant",
            "Confidence": 99.97044372558594,
            "Instances": [],
            "Parents": [
                {
                    "Name": "Indoors"
                }
            ],
            "Aliases": [],
            "Categories": [
                {
                    "Name": "Buildings and Architecture"
                }
            ]
        },
        {
            "Name": "City",
            "Confidence": 99.95919036865234,
            "Instances": [],
            "Parents": [],
            "Aliases": [
                {
                    "Name": "Town"
                }
            ],
            "Categories": [
                {
                    "Name": "Buildings and Architecture"
                }
            ]
        },
        {
            "Name": "Road",
            "Confidence": 99.94469451904297,
            "Instances": [],
            "Parents": [],
            "Aliases": [],
            "Categories": [
                {
                    "Name": "Transport and Logistics"
                }
            ]
        },
.
.
.
>>
  • 파이썬 개발환경 구축

가상환경 구축 및 boto(AWS의 파이썬 SDK) 설치

pip install pipenv
mkdir ObjectDetectionDemo
cd ObjectDetectionDemo/
pipenv install boto3
  • AWS SDK로 Rekognition 애플리케이션 구현

가상환경 실행 및 구현에 필요한 소스파일 작성, pipenv shell 실행 후 파일 실행

pipenv run
touch storage_service.py
edit storage_service.py
touch recognition_service.py
edit recognition_service.py
touch object_detection_demo.py
edit object_detection_demo.py
pipenv shell
python3 object_detection_demo.py
# storage_service.py

import boto3

class StorageService:
    def __init__(self):
        self.s3 = boto3.resource('s3')

    def get_all_files(self, storage_location):
        return self.s3.Bucket(storage_location).objects.all()
# object_detection_demo.py

from storage_service import StorageService
from recognition_service import RecognitionService

storage_service = StorageService()
recognition_service = RecognitionService()

bucket_name = 'contents.stubborngastropod.ai'

for file in storage_service.get_all_files(bucket_name):
    if file.key.endswith('.jpg'):
        print(file.key + 'Detected object from image: ')
        labels = recognition_service.detect_objects(file.bucket_name, file.key)

        for label in labels:
            print('-- ' + label['Name'] + ': ' + str(label['Confidence']))
# recognition_service.py

import boto3

class RecognitionService:
    def __init__(self):
        self.client = boto3.client('rekognition')

    def detect_objects(self, storage_location, image_file):
        response = self.client.detect_labels(
            Image = {
                'S3Object': {
                    'Bucket': storage_location,
                    'Name': image_file
                }
            }
        )

        return response['Labels']

해당 프로그램 실행 시, 다음과 같은 결과가 출력된다.

-- Indoors: 99.97044372558594
-- Restaurant: 99.97044372558594
-- City: 99.95919036865234
-- Road: 99.94469451904297
-- Street: 99.94469451904297
-- Urban: 99.94469451904297
-- Accessories: 99.60762023925781
-- Bag: 99.60762023925781
-- Handbag: 99.60762023925781
-- Neighborhood: 99.26884460449219
.
.
.

 

참고자료: http://www.yes24.com/Product/Goods/101806234

 

AWS 기반 AI 애플리케이션 개발 - YES24

전반적으로 유지보수가 쉬운 AI 애플리케이션을 개발, 배포, 운영하는 방법에 대해 설명하고, 다양한 AWS AI/ML 서비스를 활용해서 효과적으로 AI 애플리케이션을 개발하는 방법을 실습 중심으로

www.yes24.com

 

728x90

댓글