Masterdqqq/Facial_Expression_Recognition
1
1"""2File: face_utils.py3Author: Elena Ryumina and Dmitry Ryumin4Description: This module contains utility functions related to facial landmarks and image processing.5License: MIT License6"""7 8import numpy as np9import math10import cv211 12 13def norm_coordinates(normalized_x, normalized_y, image_width, image_height):14 x_px = min(math.floor(normalized_x * image_width), image_width - 1)15 y_px = min(math.floor(normalized_y * image_height), image_height - 1)16 return x_px, y_px17 18 19def get_box(fl, w, h):20 idx_to_coors = {}21 for idx, landmark in enumerate(fl.landmark):22 landmark_px = norm_coordinates(landmark.x, landmark.y, w, h)23 if landmark_px:24 idx_to_coors[idx] = landmark_px25 26 x_min = np.min(np.asarray(list(idx_to_coors.values()))[:, 0])27 y_min = np.min(np.asarray(list(idx_to_coors.values()))[:, 1])28 endX = np.max(np.asarray(list(idx_to_coors.values()))[:, 0])29 endY = np.max(np.asarray(list(idx_to_coors.values()))[:, 1])30 31 (startX, startY) = (max(0, x_min), max(0, y_min))32 (endX, endY) = (min(w - 1, endX), min(h - 1, endY))33 34 return startX, startY, endX, endY35 36def display_info(img, text, margin=1.0, box_scale=1.0):37 img_copy = img.copy()38 img_h, img_w, _ = img_copy.shape39 line_width = int(min(img_h, img_w) * 0.001)40 thickness = max(int(line_width / 3), 1)41 42 font_face = cv2.FONT_HERSHEY_SIMPLEX43 font_color = (0, 0, 0)44 font_scale = thickness / 1.545 46 t_w, t_h = cv2.getTextSize(text, font_face, font_scale, None)[0]47 48 margin_n = int(t_h * margin)49 sub_img = img_copy[0 + margin_n: 0 + margin_n + t_h + int(2 * t_h * box_scale),50 img_w - t_w - margin_n - int(2 * t_h * box_scale): img_w - margin_n]51 52 white_rect = np.ones(sub_img.shape, dtype=np.uint8) * 25553 54 img_copy[0 + margin_n: 0 + margin_n + t_h + int(2 * t_h * box_scale),55 img_w - t_w - margin_n - int(2 * t_h * box_scale):img_w - margin_n] = cv2.addWeighted(sub_img, 0.5, white_rect, .5, 1.0)56 57 cv2.putText(img=img_copy,58 text=text,59 org=(img_w - t_w - margin_n - int(2 * t_h * box_scale) // 2,60 0 + margin_n + t_h + int(2 * t_h * box_scale) // 2),61 fontFace=font_face,62 fontScale=font_scale,63 color=font_color,64 thickness=thickness,65 lineType=cv2.LINE_AA,66 bottomLeftOrigin=False)67 68 return img_copy69 