카테고리 없음
AWS S3/Rekognotion과 라즈베리 파이를 이용한 얼굴인식
Wood Pecker
2021. 7. 23. 23:39
1. 개요
라이베리 파이에 부착된 카메라를 이용하여 촬영하는 실시간 영상을 아마존 AWS에 전송하고 AWS 인공지능 API를 이용하여 얼굴인식을 하여본다. 이 방법을 응용하면 가정용 비디오 폰에 적용하거나 출퇴근관리, 컨퍼런스 자동 태그 출력 등에 활용할 수 있다.
2. AWS설정
AWS의 사용자 계정 IAM User을 이용하여 작업을 한다. S3 서비스에 Create Bucket을 만든다.
방금 만든 버켓 아래에 얼굴인식을 하고자 하는 사람수 만큼 폴더를 만들어준다. friend01,friend02, 2개의 폴더를 만들었다. 각각의 폴더에는 해당 사람의 사진을 여러장 upload 올려준다.
각각 같은 사람의 사진을 3장씩 올렸다.
Progrmmatic Access를 하는 user를 등록한다. S3와 Rekognition Full Access 권한을 부여한다.
Access key ID와 Secret access key가 생성된다. 이 값을 잘 보관하자. 아래 프로그램 코드에서 사용할 것이다.
3. Create New Collection
아래의 프로그램을 라즈베리(또는 PC)에서 작성하고 실행한다. S3에 저장한 이미지로 부터 collection을 만드는 프로그램이다.
#
#make face index (Create new collection)
#
import boto3
s3_client = boto3.client(
's3',
aws_access_key_id='AK....D',
aws_secret_access_key='TS...d',
region_name='us-east-1' )
collectionId='mycollection' #collection name
rek_client=boto3.client('rekognition',
aws_access_key_id='AK....D',
aws_secret_access_key='TS...d',
region_name='us-east-1' )
bucket = 'myfacerecog' #S3 bucket name
all_objects = s3_client.list_objects(Bucket =bucket )
#1. delete existing collection if it exists
list_response=rek_client.list_collections(MaxResults=2)
if collectionId in list_response['CollectionIds']:
rek_client.delete_collection(CollectionId=collectionId)
#2. create a new collection
rek_client.create\_collection(CollectionId=collectionId)
#3. add all images in current bucket to the collections, use folder names as the labels
for content in all_objects['Contents']:
collection_name,collection_image =content['Key'].split('/')
if collection_image:
label = collection_name
print('indexing: ',label)
image = content['Key']
index_response=rek_client.index_faces(CollectionId=collectionId,
Image={'S3Object':{'Bucket':bucket,'Name':image}},
ExternalImageId=label,
MaxFaces=1,
QualityFilter="AUTO",
DetectionAttributes=['ALL'])
print('FaceId: ',index_response['FaceRecords'][0]['Face']['FaceId'])
pass
4. 얼굴인식
라즈베리파이(또는 PC)에 pi-카메라 또는 web-카메라(USB)를 부착하고 아래의 프로그램을 실행한다.
import time
import boto3
import cv2
directory = '/home/pi/FaceDetect/res/' #folder name on your raspberry pi
collectionId='mycollection' #collection name
cap = cv2.VideoCapture(0)
if (cap.isOpened()== False):
print("Error opening video stream or file")
sys.exit(0)
print("starting...")
time.sleep(2.0) # allow camera sensor to warm up
rek_client=boto3.client('rekognition',
aws_access_key_id='AK....D',
aws_secret_access_key='TS...d',
region_name='us-east-1')
while True:
ret, image = cap.read()
image = cv2.resize(image, (640, 480))
cv2.imshow("Captured", image)
retval, buff = cv2.imencode(".jpg", image)
buff= bytearray(buff)
try:
match_response = rek_client.search_faces_by_image(CollectionId=collectionId, Image={'Bytes': buff}, MaxFaces=1, FaceMatchThreshold=85)
if match_response['FaceMatches']:
print('Hello, ',match_response['FaceMatches'][0]['Face']['ExternalImageId'])
print('Similarity: ',match_response['FaceMatches'][0]['Similarity'])
print('Confidence: ',match_response['FaceMatches'][0]['Face']['Confidence'])
print(match_response)
else:
print('No faces matched')
except:
print('No face detected')
cv2.waitKey(1)
AWS에서 인식결과를 다음과 같이 보내준다.
{'SearchedFaceBoundingBox': {'Width': 0.14712901413440704, 'Height': 0.23208625614643097, 'Left': 0.3395724296569824, 'Top': 0.10269246250391006},
'SearchedFaceConfidence': 99.99800872802734,
'FaceMatches': [{'Similarity': 99.96697998046875,
'Face': {'FaceId': '9d7c67b2-43b8-48c0-b674-1639403c06d9',
'BoundingBox': {'Width': 0.31395798921585083, 'Height': 0.3479419946670532, 'Left': 0.3848719894886017, 'Top': 0.1178240031003952},
'ImageId': 'd41ab4dc-1d41-3f12-b826-cc496727d13e',
'ExternalImageId': 'friend01', 'Confidence': 99.99610137939453}}],
'FaceModelVersion': '5.0',
'ResponseMetadata': {'RequestId': 'd5655ff4-cf44-489b-b58e-95ade4967698', 'HTTPStatusCode': 200,
'HTTPHeaders': {'content-type': 'application/x-amz-json-1.1', 'date': 'Fri, 23 Jul 2021 11:52:51 GMT',
'x-amzn-requestid': 'd5655ff4-cf44-489b-b58e-95ade4967698', 'content-length': '544', 'connection': 'keep-alive'},
'RetryAttempts': 0}}
반응형