Created
November 22, 2023 16:04
-
-
Save arihantdaga/5c8c92e0ab865b3b513e4ada721fecf9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
from PIL import Image | |
import io | |
rekognition_client = boto3.client("rekognition") | |
def get_face_details(image_bytes): | |
response = rekognition_client.detect_faces(Image={"Bytes": image_bytes}, Attributes=["ALL"]) | |
# Assuming the first face is the one we need | |
face_details = response["FaceDetails"][0] if response["FaceDetails"] else None | |
return face_details | |
def image_to_bytes(image): | |
image_byte_arr = io.BytesIO() | |
image.save(image_byte_arr, format="JPEG") | |
return image_byte_arr.getvalue() | |
def rotate_image(image, roll): | |
rotated_image = image.rotate(roll) # Not using negative because PIL's rotate is opposite to AWS's roll | |
return rotated_image | |
# Function to crop image | |
def crop_face(original_image, face_detail, padding_factor=0.3): | |
box = face_detail["BoundingBox"] | |
original_size = original_image.size | |
padding_width = box["Width"] * original_size[0] * padding_factor | |
padding_height = box["Height"] * original_size[1] * padding_factor | |
left = max(0, box["Left"] * original_size[0] - padding_width) | |
top = max(0, box["Top"] * original_size[1] - padding_height) | |
right = min(original_size[0], left + box["Width"] * original_size[0] + 2 * padding_width) | |
bottom = min(original_size[1], top + box["Height"] * original_size[1] + 2 * padding_height) | |
return original_image.crop((left, top, right, bottom)) | |
def process_image(image_path): | |
# Open the image | |
with open(image_path, "rb") as img_file: | |
image_bytes = img_file.read() | |
# First detection | |
face_details = get_face_details(image_bytes) | |
if not face_details: | |
raise ValueError("No face detected in the image") | |
roll = face_details["Pose"]["Roll"] | |
# Rotate original image | |
image = Image.open(io.BytesIO(image_bytes)) | |
rotated_image = rotate_image(image, roll) | |
rotated_image_bytes = image_to_bytes(rotated_image) | |
# Second detection on rotated image | |
face_details_rotated = get_face_details(rotated_image_bytes) | |
if not face_details_rotated: | |
raise ValueError("No face detected in the rotated image") | |
cropped_image = crop_face(rotated_image, face_details_rotated) | |
cropped_image.show() | |
image_path = "inpu.jpg" | |
process_image(image_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment