Created
June 11, 2024 14:34
-
-
Save korantu/38045668a9b31b75377550e79293188e to your computer and use it in GitHub Desktop.
eye detection with insightface
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 insightface | |
from insightface.app import FaceAnalysis | |
import cv2 | |
import numpy as np | |
import time | |
input_images = ["face.jpg", "face2.jpg"] | |
# Initialize the FaceAnalysis module | |
app = FaceAnalysis() | |
app.prepare(ctx_id=0, det_size=(640, 640), det_thresh=0.5) | |
def resize_image(image, max_size=300): | |
h, w = image.shape[:2] | |
if max(h, w) > max_size: | |
if h > w: | |
new_h = max_size | |
new_w = int(w * (max_size / h)) | |
else: | |
new_w = max_size | |
new_h = int(h * (max_size / w)) | |
image = cv2.resize(image, (new_w, new_h)) | |
# Pad the image to make it 640x640 with the original image centered | |
padded_image = np.zeros((640, 640, 3), dtype=np.uint8) | |
h, w = image.shape[:2] | |
y_offset = (640 - h) // 2 | |
x_offset = (640 - w) // 2 | |
padded_image[y_offset:y_offset+h, x_offset:x_offset+w] = image | |
return padded_image, (x_offset, y_offset, w, h) | |
def unresize_image(image, original_size): | |
x_offset, y_offset, w, h = original_size | |
return image[y_offset:y_offset+h, x_offset:x_offset+w] | |
for image_path in input_images: | |
image = cv2.imread(image_path) | |
image, original_size = resize_image(image) | |
cv2.imwrite("resized_" + image_path, image) | |
start_time = time.time() | |
faces = app.get(image) | |
end_time = time.time() | |
detection_time_ms = (end_time - start_time) * 1000 | |
print(f"Found {len(faces)} faces in {image_path} in {detection_time_ms:.2f} ms") | |
for face in faces: | |
left_eye_points = [face.landmark_2d_106[35], face.landmark_2d_106[40], | |
face.landmark_2d_106[39], face.landmark_2d_106[33]] | |
right_eye_points = [face.landmark_2d_106[89], face.landmark_2d_106[87], | |
face.landmark_2d_106[93], face.landmark_2d_106[94]] | |
left_eye_rect = cv2.boundingRect(np.array(left_eye_points)) | |
right_eye_rect = cv2.boundingRect(np.array(right_eye_points)) | |
# Enlarge the rectangles by 3 pixels | |
left_eye_rect = (left_eye_rect[0] - 3, left_eye_rect[1] - 3, | |
left_eye_rect[2] + 6, left_eye_rect[3] + 6) | |
right_eye_rect = (right_eye_rect[0] - 3, right_eye_rect[1] - 3, | |
right_eye_rect[2] + 6, right_eye_rect[3] + 6) | |
cv2.rectangle(image, left_eye_rect, (0, 255, 0), 1) | |
cv2.rectangle(image, right_eye_rect, (0, 255, 0), 1) | |
unresized_image = unresize_image(image, original_size) | |
cv2.imwrite("output_" + image_path, unresized_image) | |
Author
korantu
commented
Jun 12, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment