"""MediaPipe solution drawing utils.""" import math from typing import List, Mapping, Optional, Tuple, Union import cv2 import dataclasses import matplotlib.pyplot as plt import numpy as np from mediapipe.framework.formats import detection_pb2 from mediapipe.framework.formats import location_data_pb2 from mediapipe.framework.formats import landmark_pb2 from .general import get_main_sub_faces, get_final_result, get_original_coordinate _PRESENCE_THRESHOLD = 0.5 _VISIBILITY_THRESHOLD = 0.5 _BGR_CHANNELS = 3 WHITE_COLOR = (224, 224, 224) BLACK_COLOR = (0, 0, 0) RED_COLOR = (0, 0, 255) GREEN_COLOR = (0, 128, 0) BLUE_COLOR = (255, 0, 0) @dataclasses.dataclass class DrawingSpec: # Color for drawing the annotation. Default to the white color. color: Tuple[int, int, int] = WHITE_COLOR # Thickness for drawing the annotation. Default to 2 pixels. thickness: int = 2 # Circle radius. Default to 2 pixels. circle_radius: int = 2 def _normalized_to_pixel_coordinates( normalized_x: float, normalized_y: float, image_width: int, image_height: int) -> Union[None, Tuple[int, int]]: """Converts normalized value pair to pixel coordinates.""" # Checks if the float value is between 0 and 1. def is_valid_normalized_value(value: float) -> bool: return (value > 0 or math.isclose(0, value)) and (value < 1 or math.isclose(1, value)) if not (is_valid_normalized_value(normalized_x) and is_valid_normalized_value(normalized_y)): normalized_x = min(max(normalized_x, 0), 1) normalized_y = min(max(normalized_y, 0), 1) x_px = min(math.floor(normalized_x * image_width), image_width - 1) y_px = min(math.floor(normalized_y * image_height), image_height - 1) return x_px, y_px def draw_detection( image: np.ndarray, detection: detection_pb2.Detection, detection_color: tuple = (255, 255, 255), keypoint_drawing_spec: DrawingSpec = DrawingSpec(color=RED_COLOR), bbox_drawing_spec: DrawingSpec = DrawingSpec(), draw_keypoints: bool = True): """Draws the detction bounding box and keypoints on the image. Args: image: A three channel BGR image represented as numpy ndarray. detection: A detection proto message to be annotated on the image. keypoint_drawing_spec: A DrawingSpec object that specifies the keypoints' drawing settings such as color, line thickness, and circle radius. bbox_drawing_spec: A DrawingSpec object that specifies the bounding box's drawing settings such as color and line thickness. Raises: ValueError: If one of the followings: a) If the input image is not three channel BGR. b) If the location data is not relative data. """ if not detection.location_data: return if image.shape[2] != _BGR_CHANNELS: raise ValueError('Input image must contain three channel bgr data.') image_rows, image_cols, _ = image.shape location = detection.location_data if location.format != location_data_pb2.LocationData.RELATIVE_BOUNDING_BOX: raise ValueError( 'LocationData must be relative for this drawing funtion to work.') # Draws keypoints. if draw_keypoints: for keypoint in location.relative_keypoints: keypoint_px = _normalized_to_pixel_coordinates(keypoint.x, keypoint.y, image_cols, image_rows) cv2.circle(image, keypoint_px, keypoint_drawing_spec.circle_radius, keypoint_drawing_spec.color, keypoint_drawing_spec.thickness) # Draws bounding box if exists. if not location.HasField('relative_bounding_box'): return relative_bounding_box = location.relative_bounding_box rect_start_point = _normalized_to_pixel_coordinates( relative_bounding_box.xmin, relative_bounding_box.ymin, image_cols, image_rows) rect_end_point = _normalized_to_pixel_coordinates( relative_bounding_box.xmin + relative_bounding_box.width, relative_bounding_box.ymin + relative_bounding_box.height, image_cols, image_rows) cv2.rectangle(image, rect_start_point, rect_end_point, detection_color, bbox_drawing_spec.thickness) def draw_landmarks( image: np.ndarray, landmark_list: landmark_pb2.NormalizedLandmarkList, connections: Optional[List[Tuple[int, int]]] = None, landmark_drawing_spec: Union[DrawingSpec, Mapping[int, DrawingSpec]] = DrawingSpec( color=RED_COLOR), connection_drawing_spec: Union[DrawingSpec, Mapping[Tuple[int, int], DrawingSpec]] = DrawingSpec()): """Draws the landmarks and the connections on the image. Args: image: A three channel BGR image represented as numpy ndarray. landmark_list: A normalized landmark list proto message to be annotated on the image. connections: A list of landmark index tuples that specifies how landmarks to be connected in the drawing. landmark_drawing_spec: Either a DrawingSpec object or a mapping from hand landmarks to the DrawingSpecs that specifies the landmarks' drawing settings such as color, line thickness, and circle radius. If this argument is explicitly set to None, no landmarks will be drawn. connection_drawing_spec: Either a DrawingSpec object or a mapping from hand connections to the DrawingSpecs that specifies the connections' drawing settings such as color and line thickness. If this argument is explicitly set to None, no landmark connections will be drawn. Raises: ValueError: If one of the followings: a) If the input image is not three channel BGR. b) If any connetions contain invalid landmark index. """ if not landmark_list: return if image.shape[2] != _BGR_CHANNELS: raise ValueError('Input image must contain three channel bgr data.') image_rows, image_cols, _ = image.shape idx_to_coordinates = {} for idx, landmark in enumerate(landmark_list.landmark): if ((landmark.HasField('visibility') and landmark.visibility < _VISIBILITY_THRESHOLD) or (landmark.HasField('presence') and landmark.presence < _PRESENCE_THRESHOLD)): continue landmark_px = _normalized_to_pixel_coordinates(landmark.x, landmark.y, image_cols, image_rows) if landmark_px: idx_to_coordinates[idx] = landmark_px if connections: num_landmarks = len(landmark_list.landmark) # Draws the connections if the start and end landmarks are both visible. for connection in connections: start_idx = connection[0] end_idx = connection[1] if not (0 <= start_idx < num_landmarks and 0 <= end_idx < num_landmarks): raise ValueError(f'Landmark index is out of range. Invalid connection ' f'from landmark #{start_idx} to landmark #{end_idx}.') if start_idx in idx_to_coordinates and end_idx in idx_to_coordinates: drawing_spec = connection_drawing_spec[connection] if isinstance( connection_drawing_spec, Mapping) else connection_drawing_spec cv2.line(image, idx_to_coordinates[start_idx], idx_to_coordinates[end_idx], drawing_spec.color, drawing_spec.thickness) # Draws landmark points after finishing the connection lines, which is # aesthetically better. if landmark_drawing_spec: for idx, landmark_px in idx_to_coordinates.items(): drawing_spec = landmark_drawing_spec[idx] if isinstance( landmark_drawing_spec, Mapping) else landmark_drawing_spec # White circle border circle_border_radius = max(drawing_spec.circle_radius + 1, int(drawing_spec.circle_radius * 1.2)) cv2.circle(image, landmark_px, circle_border_radius, WHITE_COLOR, drawing_spec.thickness) # Fill color into the circle cv2.circle(image, landmark_px, drawing_spec.circle_radius, drawing_spec.color, drawing_spec.thickness) def draw_axis(image: np.ndarray, rotation: np.ndarray, translation: np.ndarray, focal_length: Tuple[float, float] = (1.0, 1.0), principal_point: Tuple[float, float] = (0.0, 0.0), axis_length: float = 0.1, axis_drawing_spec: DrawingSpec = DrawingSpec()): """Draws the 3D axis on the image. Args: image: A three channel BGR image represented as numpy ndarray. rotation: Rotation matrix from object to camera coordinate frame. translation: Translation vector from object to camera coordinate frame. focal_length: camera focal length along x and y directions. principal_point: camera principal point in x and y. axis_length: length of the axis in the drawing. axis_drawing_spec: A DrawingSpec object that specifies the xyz axis drawing settings such as line thickness. Raises: ValueError: If one of the followings: a) If the input image is not three channel BGR. """ if image.shape[2] != _BGR_CHANNELS: raise ValueError('Input image must contain three channel bgr data.') image_rows, image_cols, _ = image.shape # Create axis points in camera coordinate frame. axis_world = np.float32([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]) axis_cam = np.matmul(rotation, axis_length * axis_world.T).T + translation x = axis_cam[..., 0] y = axis_cam[..., 1] z = axis_cam[..., 2] # Project 3D points to NDC space. fx, fy = focal_length px, py = principal_point x_ndc = np.clip(-fx * x / (z + 1e-5) + px, -1., 1.) y_ndc = np.clip(-fy * y / (z + 1e-5) + py, -1., 1.) # Convert from NDC space to image space. x_im = np.int32((1 + x_ndc) * 0.5 * image_cols) y_im = np.int32((1 - y_ndc) * 0.5 * image_rows) # Draw xyz axis on the image. origin = (x_im[0], y_im[0]) x_axis = (x_im[1], y_im[1]) y_axis = (x_im[2], y_im[2]) z_axis = (x_im[3], y_im[3]) cv2.arrowedLine(image, origin, x_axis, RED_COLOR, axis_drawing_spec.thickness) cv2.arrowedLine(image, origin, y_axis, GREEN_COLOR, axis_drawing_spec.thickness) cv2.arrowedLine(image, origin, z_axis, BLUE_COLOR, axis_drawing_spec.thickness) def _normalize_color(color): return tuple(v / 255. for v in color) def plot_landmarks(landmark_list: landmark_pb2.NormalizedLandmarkList, connections: Optional[List[Tuple[int, int]]] = None, landmark_drawing_spec: DrawingSpec = DrawingSpec( color=RED_COLOR, thickness=5), connection_drawing_spec: DrawingSpec = DrawingSpec( color=BLACK_COLOR, thickness=5), elevation: int = 10, azimuth: int = 10): """Plot the landmarks and the connections in matplotlib 3d. Args: landmark_list: A normalized landmark list proto message to be plotted. connections: A list of landmark index tuples that specifies how landmarks to be connected. landmark_drawing_spec: A DrawingSpec object that specifies the landmarks' drawing settings such as color and line thickness. connection_drawing_spec: A DrawingSpec object that specifies the connections' drawing settings such as color and line thickness. elevation: The elevation from which to view the plot. azimuth: the azimuth angle to rotate the plot. Raises: ValueError: If any connection contains an invalid landmark index. """ if not landmark_list: return plt.figure(figsize=(10, 10)) ax = plt.axes(projection='3d') ax.view_init(elev=elevation, azim=azimuth) plotted_landmarks = {} for idx, landmark in enumerate(landmark_list.landmark): if ((landmark.HasField('visibility') and landmark.visibility < _VISIBILITY_THRESHOLD) or (landmark.HasField('presence') and landmark.presence < _PRESENCE_THRESHOLD)): continue ax.scatter3D( xs=[-landmark.z], ys=[landmark.x], zs=[-landmark.y], color=_normalize_color(landmark_drawing_spec.color[::-1]), linewidth=landmark_drawing_spec.thickness) plotted_landmarks[idx] = (-landmark.z, landmark.x, -landmark.y) if connections: num_landmarks = len(landmark_list.landmark) # Draws the connections if the start and end landmarks are both visible. for connection in connections: start_idx = connection[0] end_idx = connection[1] if not (0 <= start_idx < num_landmarks and 0 <= end_idx < num_landmarks): raise ValueError(f'Landmark index is out of range. Invalid connection ' f'from landmark #{start_idx} to landmark #{end_idx}.') if start_idx in plotted_landmarks and end_idx in plotted_landmarks: landmark_pair = [ plotted_landmarks[start_idx], plotted_landmarks[end_idx] ] ax.plot3D( xs=[landmark_pair[0][0], landmark_pair[1][0]], ys=[landmark_pair[0][1], landmark_pair[1][1]], zs=[landmark_pair[0][2], landmark_pair[1][2]], color=_normalize_color(connection_drawing_spec.color[::-1]), linewidth=connection_drawing_spec.thickness) plt.show() def draw_informations_for_face(image, detection, pad_infos, detection_color, pos, coordinate, use_face_keypoints, direction, position, show_coordinate=True, precise_info=False): draw_detection(image, detection, detection_color=detection_color, draw_keypoints=use_face_keypoints) if precise_info: img_h, img_w = image.shape[:2] pad_top, pad_bot, pad_left, pad_right = pad_infos xmin = detection.location_data.relative_bounding_box.xmin ymin = detection.location_data.relative_bounding_box.ymin width = detection.location_data.relative_bounding_box.width height = detection.location_data.relative_bounding_box.height xmin_ori = (xmin * img_w) / (img_w - pad_top - pad_bot) ymin_ori = (ymin * img_h) / (img_h - pad_left - pad_right) width_ori = (width * img_w) / (img_w - pad_top - pad_bot) height_ori = (height * img_h) / (img_h - pad_left - pad_right) cv2.putText(image, f"Direction: {direction}", (int(xmin*image.shape[1]), int(ymin*image.shape[0]-5)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 5) cv2.putText(image, f"Direction: {direction}", (int(xmin*image.shape[1]), int(ymin*image.shape[0]-5)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 3) cv2.putText(image, f"Position: {position}", (int(xmin*image.shape[1]), int(ymin*image.shape[0]+16)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 4) cv2.putText(image, f"Position: {position}", (int(xmin*image.shape[1]), int(ymin*image.shape[0]+16)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2) if show_coordinate: cv2.putText(image, f"({str(np.round(pos[0], 2))}, {str(np.round(pos[1], 2))}, {str(np.round(pos[2], 2))})", (int(xmin*image.shape[1]), int(ymin*image.shape[0]+36)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (140, 215, 255), 4) cv2.putText(image, f"({str(np.round(pos[0], 2))}, {str(np.round(pos[1], 2))}, {str(np.round(pos[2], 2))})", (int(xmin*image.shape[1]), int(ymin*image.shape[0]+36)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 255), 2) cv2.putText(image, f"<{xmin_ori:.2f}, {ymin_ori:.2f}, {xmin_ori+width_ori:.2f}, {ymin_ori+height_ori:.2f}>", (int(xmin*image.shape[1]), int(ymin*image.shape[0]+56)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (140, 215, 255), 4) cv2.putText(image, f"<{xmin_ori:.2f}, {ymin_ori:.2f}, {xmin_ori+width_ori:.2f}, {ymin_ori+height_ori:.2f}>", (int(xmin*image.shape[1]), int(ymin*image.shape[0]+56)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 255), 2) def draw_all_informations(image, face_detection_infos, face_direction_infos, face_position_infos, face_coordinate_infos, face_pose_infos, face_area_infos, chosen_rectangle_pos_list, img_size, pad_infos, ratio_infos, session_state, head_pose_info): img_w, img_h = img_size pad_top, pad_bot, pad_left, pad_right = pad_infos w_ratio, h_ratio = ratio_infos if len(face_detection_infos) == 0: final_direction = 'NO FACE' final_position = 'NO_FACE' final_pose = (0, 0, 0) final_detection = (0, 0, 0, 0) else: cur_main_sub_faces, cur_face_ratios = get_main_sub_faces(face_detection_infos, head_pose_info['FACE_OPTIONS']['MIN_FACE_RATIO_OVER_MAX_FACE_TO_BE_MAIN']) final_detection, final_direction, final_position, final_coordinate, final_pose, final_area, final_chosen_rectangle, final_main_id = \ get_final_result(cur_main_sub_faces, cur_face_ratios, face_detection_infos, face_direction_infos, face_position_infos, face_coordinate_infos, face_pose_infos, face_area_infos, chosen_rectangle_pos_list) if face_detection_infos: if session_state.show_all_main_faces or session_state.show_all_sub_faces: for face_id, detection in enumerate(face_detection_infos): if cur_main_sub_faces[face_id] == 0 and session_state.show_all_sub_faces: draw_informations_for_face(image, detection, pad_infos, head_pose_info['FACE_OPTIONS']['SUB_FACE_BBOX_COLOR'], face_pose_infos[face_id], face_coordinate_infos[face_id], False, face_direction_infos[face_id], face_position_infos[face_id], True, session_state.turn_on_visualize) elif cur_main_sub_faces[face_id] == 1 and session_state.show_all_main_faces: draw_informations_for_face(image, detection, pad_infos, head_pose_info['FACE_OPTIONS']['MAIN_FACE_BBOX_COLOR'], face_pose_infos[face_id], face_coordinate_infos[face_id], False, face_direction_infos[face_id], face_position_infos[face_id], True, session_state.turn_on_visualize) draw_informations_for_face(image, face_detection_infos[final_main_id], pad_infos, head_pose_info['FACE_OPTIONS']['REPRESENTATIVE_FACE_BBOX_COLOR'], final_pose, final_coordinate, False, final_direction, final_position, True, session_state.turn_on_visualize) if session_state.show_rectangle_position: for pos_id, (head_pose_pos_name, head_pose_pos) in enumerate(head_pose_info['POSITION'].items()): if head_pose_pos_name == 'NO_FACE': continue cv2.rectangle(image, (int(head_pose_pos[0][0]*img_w*w_ratio + pad_left), int(head_pose_pos[0][1]*img_h*h_ratio + pad_top)), (int(head_pose_pos[1][0]*img_w*w_ratio + pad_left), int(head_pose_pos[1][1]*img_h*h_ratio + pad_top)), (0, 0, 0), 3) cv2.putText(image, f"{head_pose_pos[2]}", (int(head_pose_pos[0][0]*img_w*w_ratio + pad_left + 10), int(head_pose_pos[0][1]*img_h*h_ratio + pad_top + 20)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,255,255), 5) cv2.putText(image, f"{head_pose_pos[2]}", (int(head_pose_pos[0][0]*img_w*w_ratio + pad_left + 10), int(head_pose_pos[0][1]*img_h*h_ratio + pad_top + 20)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0,0,0), 2) if session_state.show_all_main_faces: for face_id, head_pose_pos in enumerate(chosen_rectangle_pos_list): if cur_main_sub_faces[face_id] == 1: cv2.rectangle(image, (int(head_pose_pos[0][0]*img_w*w_ratio + pad_left), int(head_pose_pos[0][1]*img_h*h_ratio + pad_top)), (int(head_pose_pos[1][0]*img_w*w_ratio + pad_left), int(head_pose_pos[1][1]*img_h*h_ratio + pad_top)), (0, 255, 0), 3) else: cv2.rectangle(image, (int(final_chosen_rectangle[0][0]*img_w*w_ratio + pad_left), int(final_chosen_rectangle[0][1]*img_h*h_ratio + pad_top)), (int(final_chosen_rectangle[1][0]*img_w*w_ratio + pad_left), int(final_chosen_rectangle[1][1]*img_h*h_ratio + pad_top)), (0, 255, 0), 3) ## Draw results cv2.putText(image, f"Direction: {final_direction}", (int(img_size[0]*0.01), int(img_size[1]*0.87)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,255,255), 5) cv2.putText(image, f"Direction: {final_direction}", (int(img_size[0]*0.01), int(img_size[1]*0.87)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, tuple(head_pose_info['FACE_OPTIONS']['RESULTS_COLOR']), 2) cv2.putText(image, f"Position: {head_pose_info['POSITION'][final_position][2]}", (int(img_size[0]*0.01), int(img_size[1]*0.91)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,255,255), 5) cv2.putText(image, f"Position: {head_pose_info['POSITION'][final_position][2]}", (int(img_size[0]*0.01), int(img_size[1]*0.91)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, tuple(head_pose_info['FACE_OPTIONS']['RESULTS_COLOR']), 2) cv2.putText(image, f"Coordinate: < x: {final_pose[0]:.2f}, y: {final_pose[1]:.2f}, z: {final_pose[2]:.2f} >", (int(img_size[0]*0.01), int(img_size[1]*0.95)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,255,255), 5) cv2.putText(image, f"Coordinate: < x: {final_pose[0]:.2f}, y: {final_pose[1]:.2f}, z: {final_pose[2]:.2f} >", (int(img_size[0]*0.01), int(img_size[1]*0.95)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, tuple(head_pose_info['FACE_OPTIONS']['RESULTS_COLOR']), 2) if len(face_detection_infos) != 0: final_xmin_ori, final_ymin_ori, final_width_ori, final_height_ori = \ get_original_coordinate(final_detection, img_size, pad_infos) else: final_xmin_ori, final_ymin_ori, final_width_ori, final_height_ori = final_detection cv2.putText(image, f"Bounding box: < x1: {final_xmin_ori:.2f}, y1: {final_ymin_ori:.2f}, x2: {final_xmin_ori+final_width_ori:.2f}, y2: {final_ymin_ori+final_height_ori:.2f} >", (int(img_size[0]*0.01), int(img_size[1]*0.99)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255,255,255), 5) cv2.putText(image, f"Bounding box: < x1: {final_xmin_ori:.2f}, y1: {final_ymin_ori:.2f}, x2: {final_xmin_ori+final_width_ori:.2f}, y2: {final_ymin_ori+final_height_ori:.2f} >", (int(img_size[0]*0.01), int(img_size[1]*0.99)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, tuple(head_pose_info['FACE_OPTIONS']['RESULTS_COLOR']), 2)