728x90
AWS CLI Profile 설정
1. 새로운 Profile을 추가해줍니다.
aws configure --profile my-account
2. Profile을 설정해줍니다. (위에 액세스 키를 우선 발급받아 줍니다)
AWS Access Key ID [None]: YOUR_OTHER_ACCOUNT_ACCESS_KEY_ID
AWS Secret Access Key [None]: YOUR_OTHER_ACCOUNT_SECRET_ACCESS_KEY
Default region name [None]: YOUR_REGION
Default output format [None]: json
3. Profile을 사용하여 Rekognition Collection 생성
aws rekognition create-collection --collection-id employees-faces --profile my-account --region your-region
4. 이런 문구가 뜨시면 성공적으로 Collection이 생성되었다고 생각하시면 됩니다.
S3 이미지 파일을 Rekognition Collection에 넣기
1. S3 파일에 있는 이미지들을 Rekognition Collection에 넣는 파이썬 코드
import boto3
# AWS 인증 정보 설정 (프로파일 사용)
session = boto3.Session(profile_name='your-profile-name')
rekognition = session.client('rekognition', region_name='ap-northeast-2')
s3 = session.client('s3', region_name='ap-northeast-2')
# 컬렉션 ID 설정
collection_id = 'employees-faces'
bucket_name = 'your-bucket-name'
prefix = 'your-prefix-name/'
# S3 버킷에서 이미지 목록 가져오기
response = s3.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
image_files = [content['Key'] for content in response.get('Contents', [])]
print(f'Image files in {bucket_name}/{prefix}:')
for image_file in image_files:
print(image_file)
# # 이미지 파일을 사용하여 Rekognition 컬렉션에 얼굴 추가
for image_file in image_files:
response = rekognition.index_faces(
CollectionId=collection_id,
Image={
'S3Object': {
'Bucket': bucket_name,
'Name': image_file
}
},
ExternalImageId=image_file.split('/')[1].split('.')[0],
DetectionAttributes=['ALL']
)
print(f'Indexed faces from image {image_file}:')
for face_record in response['FaceRecords']:
print(f' Face ID: {face_record["Face"]["FaceId"]}')
print(f' Location: {face_record["Face"]["BoundingBox"]}')
간단하게 매커니즘을 보면, 저는 prefix/사람이름.jpeg 형식으로 이미지 파일을 저장해놔서, 사람이름만 가져와서 ExternalImageId로 넣어줬습니다.
여기서 다음 스텝으로는 추가되는 사진들을 넣어줘야 하는데, 어떻게 넣어줄까 고민했는데, 새로 추가한 사진만 넣기에는 너무 저의
노가다(?)가 들어갈 것 같아서, 전체 이미지 목록을 다시 불러와서 이미 컬렉션에 추가된 이미지를 제외하고 새로운 이미지만 추가하는 방법으로 코드를 작성해보려고 합니당..!
S3 이미지 파일을 Rekognition Collection에 넣기[Ver.2] Update 버전
import boto3
import os
# AWS 인증 정보 설정 (프로파일 사용)
session = boto3.Session(profile_name='your-profile-name')
rekognition = session.client('rekognition', region_name='ap-northeast-2')
s3 = session.client('s3', region_name='ap-northeast-2')
# 컬렉션 ID 설정
collection_id = 'employees-faces'
bucket_name = 'your-bucket-name'
prefix = 'your-prefix-name/'
# S3 버킷에서 이미지 목록 가져오기
response = s3.list_objects_v2(Bucket=bucket_name, Prefix=prefix)
image_files = [content['Key'] for content in response.get('Contents', [])]
# 컬렉션에서 이미 존재하는 얼굴 ID 목록 가져오기
existing_faces = set()
response = rekognition.list_faces(CollectionId=collection_id)
while True:
for face in response['Faces']:
existing_faces.add(face['ExternalImageId'])
if 'NextToken' in response:
response = rekognition.list_faces(CollectionId=collection_id, NextToken=response['NextToken'])
else:
break
for image_file in image_files:
external_image_id = os.path.splitext(os.path.basename(image_file))[0]
print(external_image_id)
response = rekognition.index_faces(
CollectionId=collection_id,
Image={
'S3Object': {
'Bucket': bucket_name,
'Name': image_file
}
},
ExternalImageId=external_image_id,
DetectionAttributes=['ALL']
)
print(f'Indexed faces from image {image_file}:')
for face_record in response['FaceRecords']:
print(f' Face ID: {face_record["Face"]["FaceId"]}')
print(f' Location: {face_record["Face"]["BoundingBox"]}')
파일 이름 분리할 때 꿀팁..[이런 꿀팁 많이 공유해주세요..ㅜ]
- os.path.splitext(path)
- splittext는 파일명을 입력으로 받아 확장자 전까지의 파일 이름과 확장자를 분리해서 반환
- os.path.basename(path)
- 상위 경로를 제외한 파일명만 반환
https://docs.python.org/ko/3/library/os.path.html
'개발 > AWS' 카테고리의 다른 글
[AWS] Github Actions S3와 github repository 연결하기 [Ver 2] (0) | 2024.07.04 |
---|---|
[AWS] Cloudwatch 콘솔에서 Lambda 함수 로그 그룹이 존재하지 않는다 오류 해결법 (0) | 2024.07.03 |
[AWS] API Gateway와 Lambda 그리고 Face Rekognition을 활용한 얼굴 비교 웹 사이트 구축 (2) | 2024.07.01 |
[AWS] 티스토리 API 없이 크롤링하여 Lambda를 활용한 실시간 최신 블로그 포스트 보여주기 (0) | 2024.06.25 |
[AWS] [Step 5 - CloudFront] (1) | 2024.06.03 |