From 89be4c7b64f047318589e2d76a754bdcd9ae712c Mon Sep 17 00:00:00 2001 From: kinaryml Date: Sun, 12 Mar 2023 16:09:04 -0700 Subject: [PATCH 01/12] Added some files for the face landmarker implementation --- .../tasks/python/components/containers/BUILD | 9 + .../components/containers/matrix_data.py | 79 +++ mediapipe/tasks/python/test/vision/BUILD | 25 + .../test/vision/face_landmarker_test.py | 182 +++++++ mediapipe/tasks/python/vision/BUILD | 25 + .../tasks/python/vision/face_landmarker.py | 449 ++++++++++++++++++ 6 files changed, 769 insertions(+) create mode 100644 mediapipe/tasks/python/components/containers/matrix_data.py create mode 100644 mediapipe/tasks/python/test/vision/face_landmarker_test.py create mode 100644 mediapipe/tasks/python/vision/face_landmarker.py diff --git a/mediapipe/tasks/python/components/containers/BUILD b/mediapipe/tasks/python/components/containers/BUILD index 7108617f..f60f6dc2 100644 --- a/mediapipe/tasks/python/components/containers/BUILD +++ b/mediapipe/tasks/python/components/containers/BUILD @@ -73,6 +73,15 @@ py_library( ], ) +py_library( + name = "matrix_data", + srcs = ["matrix_data.py"], + deps = [ + "//mediapipe/framework/formats:matrix_data_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) + py_library( name = "detections", srcs = ["detections.py"], diff --git a/mediapipe/tasks/python/components/containers/matrix_data.py b/mediapipe/tasks/python/components/containers/matrix_data.py new file mode 100644 index 00000000..9f0d5dfd --- /dev/null +++ b/mediapipe/tasks/python/components/containers/matrix_data.py @@ -0,0 +1,79 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Matrix data data class.""" + +import dataclasses +import enum +from typing import Any, Optional + +from mediapipe.framework.formats import matrix_data_pb2 +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_MatrixDataProto = matrix_data_pb2.MatrixData + + +@dataclasses.dataclass +class MatrixData: + """This stores the Matrix data. + + Here the data is stored in column-major order by default. + + Attributes: + rows: The number of rows in the matrix. + cols: The number of columns in the matrix. + data: The data stored in the matrix. + layout: The order in which the data are stored. Defaults to COLUMN_MAJOR. + """ + + class Layout(enum.Enum): + COLUMN_MAJOR = 0 + ROW_MAJOR = 1 + + rows: Optional[int] = None + cols: Optional[int] = None + data: Optional[float] = None + layout: Optional[Layout] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _MatrixDataProto: + """Generates a MatrixData protobuf object.""" + return _MatrixDataProto( + rows=self.rows, + cols=self.cols, + data=self.data, + layout=self.layout) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _MatrixDataProto) -> 'MatrixData': + """Creates a `MatrixData` object from the given protobuf object.""" + return MatrixData( + rows=pb2_obj.rows, + cols=pb2_obj.cols, + data=pb2_obj.data, + layout=pb2_obj.layout) + + def __eq__(self, other: Any) -> bool: + """Checks if this object is equal to the given object. + + Args: + other: The object to be compared with. + + Returns: + True if the objects are equal. + """ + if not isinstance(other, MatrixData): + return False + + return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index 48ecc30b..0a1a18ff 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -114,3 +114,28 @@ py_test( "@com_google_protobuf//:protobuf_python", ], ) + +py_test( + name = "face_landmarker_test", + srcs = ["face_landmarker_test.py"], + data = [ + "//mediapipe/tasks/testdata/vision:test_images", + "//mediapipe/tasks/testdata/vision:test_models", + "//mediapipe/tasks/testdata/vision:test_protos", + ], + deps = [ + "//mediapipe/python:_framework_bindings", + "//mediapipe/framework/formats:landmark_py_pb2", + "//mediapipe/tasks/python/components/containers:category", + "//mediapipe/tasks/python/components/containers:landmark", + "//mediapipe/tasks/python/components/containers:rect", + "//mediapipe/tasks/python/components/containers:classification_result", + "//mediapipe/tasks/python/components/containers:matrix_data", + "//mediapipe/tasks/python/core:base_options", + "//mediapipe/tasks/python/test:test_utils", + "//mediapipe/tasks/python/vision:face_landmarker", + "//mediapipe/tasks/python/vision/core:image_processing_options", + "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + "@com_google_protobuf//:protobuf_python", + ], +) diff --git a/mediapipe/tasks/python/test/vision/face_landmarker_test.py b/mediapipe/tasks/python/test/vision/face_landmarker_test.py new file mode 100644 index 00000000..acdc0251 --- /dev/null +++ b/mediapipe/tasks/python/test/vision/face_landmarker_test.py @@ -0,0 +1,182 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for face landmarker.""" + +import enum +from unittest import mock + +from absl.testing import absltest +from absl.testing import parameterized +import numpy as np + +from google.protobuf import text_format +from mediapipe.framework.formats import landmark_pb2 +from mediapipe.python._framework_bindings import image as image_module +from mediapipe.tasks.python.components.containers import category as category_module +from mediapipe.tasks.python.components.containers import landmark as landmark_module +from mediapipe.tasks.python.components.containers import rect as rect_module +from mediapipe.tasks.python.components.containers import classification_result as classification_result_module +from mediapipe.tasks.python.core import base_options as base_options_module +from mediapipe.tasks.python.test import test_utils +from mediapipe.tasks.python.vision import face_landmarker +from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module +from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module + +FaceLandmarkerResult = face_landmarker.FaceLandmarkerResult +_BaseOptions = base_options_module.BaseOptions +_Category = category_module.Category +_Rect = rect_module.Rect +_Landmark = landmark_module.Landmark +_NormalizedLandmark = landmark_module.NormalizedLandmark +_Image = image_module.Image +_FaceLandmarker = face_landmarker.FaceLandmarker +_FaceLandmarkerOptions = face_landmarker.FaceLandmarkerOptions +_RUNNING_MODE = running_mode_module.VisionTaskRunningMode +_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions + +_FACE_LANDMARKER_BUNDLE_ASSET_FILE = 'face_landmarker.task' +_FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE = 'face_landmarker_with_blendshapes.task' +_PORTRAIT_IMAGE = 'portrait.jpg' +_PORTRAIT_EXPECTED_FACE_LANDMARKS = 'portrait_expected_face_landmarks.pbtxt' +_PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION = 'portrait_expected_face_landmarks_with_attention.pbtxt' +_PORTRAIT_EXPECTED_BLENDSHAPES = 'portrait_expected_blendshapes_with_attention.pbtxt' +_LANDMARKS_DIFF_MARGIN = 0.03 +_BLENDSHAPES_DIFF_MARGIN = 0.1 +_FACIAL_TRANSFORMATION_MATRIX_DIFF_MARGIN = 0.02 + + +def _get_expected_face_landmarks(file_path: str): + proto_file_path = test_utils.get_test_data_path(file_path) + with open(proto_file_path, 'rb') as f: + proto = landmark_pb2.NormalizedLandmarkList() + text_format.Parse(f.read(), proto) + landmarks = [] + for landmark in proto.landmark: + landmarks.append(_NormalizedLandmark.create_from_pb2(landmark)) + return landmarks + + +class ModelFileType(enum.Enum): + FILE_CONTENT = 1 + FILE_NAME = 2 + + +class HandLandmarkerTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self.test_image = _Image.create_from_file( + test_utils.get_test_data_path(_PORTRAIT_IMAGE)) + self.model_path = test_utils.get_test_data_path( + _FACE_LANDMARKER_BUNDLE_ASSET_FILE) + + def _expect_landmarks_correct(self, actual_landmarks, expected_landmarks): + # Expects to have the same number of faces detected. + self.assertLen(actual_landmarks, len(expected_landmarks)) + + for i, rename_me in enumerate(actual_landmarks): + self.assertAlmostEqual( + rename_me.x, + expected_landmarks[i].x, + delta=_LANDMARKS_DIFF_MARGIN) + self.assertAlmostEqual( + rename_me.y, + expected_landmarks[i].y, + delta=_LANDMARKS_DIFF_MARGIN) + + def _expect_blendshapes_correct(self, actual_blendshapes, expected_blendshapes): + # Expects to have the same number of blendshapes. + self.assertLen(actual_blendshapes, len(expected_blendshapes)) + + for i, rename_me in enumerate(actual_blendshapes): + self.assertEqual(rename_me.index, expected_blendshapes[i].index) + self.assertAlmostEqual( + rename_me.score, + expected_blendshapes[i].score, + delta=_BLENDSHAPES_DIFF_MARGIN) + + def _expect_facial_transformation_matrix_correct(self, actual_matrix_list, + expected_matrix_list): + self.assertLen(actual_matrix_list, len(expected_matrix_list)) + + for i, rename_me in enumerate(actual_matrix_list): + self.assertEqual(rename_me.rows, expected_matrix_list[i].rows) + self.assertEqual(rename_me.cols, expected_matrix_list[i].cols) + self.assertAlmostEqual( + rename_me.data, + expected_matrix_list[i].data, + delta=_FACIAL_TRANSFORMATION_MATRIX_DIFF_MARGIN) + + def test_create_from_file_succeeds_with_valid_model_path(self): + # Creates with default option and valid model file successfully. + with _FaceLandmarker.create_from_model_path(self.model_path) as landmarker: + self.assertIsInstance(landmarker, _FaceLandmarker) + + def test_create_from_options_succeeds_with_valid_model_path(self): + # Creates with options containing model file successfully. + base_options = _BaseOptions(model_asset_path=self.model_path) + options = _FaceLandmarkerOptions(base_options=base_options) + with _FaceLandmarker.create_from_options(options) as landmarker: + self.assertIsInstance(landmarker, _FaceLandmarker) + + def test_create_from_options_fails_with_invalid_model_path(self): + # Invalid empty model path. + with self.assertRaisesRegex( + RuntimeError, 'Unable to open file at /path/to/invalid/model.tflite'): + base_options = _BaseOptions( + model_asset_path='/path/to/invalid/model.tflite') + options = _FaceLandmarkerOptions(base_options=base_options) + _FaceLandmarker.create_from_options(options) + + def test_create_from_options_succeeds_with_valid_model_content(self): + # Creates with options containing model content successfully. + with open(self.model_path, 'rb') as f: + base_options = _BaseOptions(model_asset_buffer=f.read()) + options = _FaceLandmarkerOptions(base_options=base_options) + landmarker = _FaceLandmarker.create_from_options(options) + self.assertIsInstance(landmarker, _FaceLandmarker) + + @parameterized.parameters( + (ModelFileType.FILE_NAME, + _get_expected_face_landmarks(_PORTRAIT_EXPECTED_FACE_LANDMARKS)), + (ModelFileType.FILE_CONTENT, + _get_expected_face_landmarks(_PORTRAIT_EXPECTED_FACE_LANDMARKS))) + def test_detect(self, model_file_type, expected_result): + # Creates face landmarker. + if model_file_type is ModelFileType.FILE_NAME: + base_options = _BaseOptions(model_asset_path=self.model_path) + elif model_file_type is ModelFileType.FILE_CONTENT: + with open(self.model_path, 'rb') as f: + model_content = f.read() + base_options = _BaseOptions(model_asset_buffer=model_content) + else: + # Should never happen + raise ValueError('model_file_type is invalid.') + + options = _FaceLandmarkerOptions(base_options=base_options, + output_face_blendshapes=True) + landmarker = _FaceLandmarker.create_from_options(options) + + # Performs face landmarks detection on the input. + detection_result = landmarker.detect(self.test_image) + # Comparing results. + self._expect_landmarks_correct(detection_result.face_landmarks, + expected_result.face_landmarks) + # Closes the face landmarker explicitly when the face landmarker is not used + # in a context. + landmarker.close() + + +if __name__ == '__main__': + absltest.main() diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index eda8e290..62b76056 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -152,3 +152,28 @@ py_library( "//mediapipe/tasks/python/vision/core:vision_task_running_mode", ], ) + +py_library( + name = "face_landmarker", + srcs = [ + "face_landmarker.py", + ], + deps = [ + "//mediapipe/framework/formats:classification_py_pb2", + "//mediapipe/framework/formats:landmark_py_pb2", + "//mediapipe/framework/formats:matrix_data_py_pb2", + "//mediapipe/python:_framework_bindings", + "//mediapipe/python:packet_creator", + "//mediapipe/python:packet_getter", + "//mediapipe/tasks/cc/vision/face_landmarker/proto:face_landmarker_graph_options_py_pb2", + "//mediapipe/tasks/python/components/containers:category", + "//mediapipe/tasks/python/components/containers:landmark", + "//mediapipe/tasks/python/components/containers:matrix_data", + "//mediapipe/tasks/python/core:base_options", + "//mediapipe/tasks/python/core:optional_dependencies", + "//mediapipe/tasks/python/core:task_info", + "//mediapipe/tasks/python/vision/core:base_vision_task_api", + "//mediapipe/tasks/python/vision/core:image_processing_options", + "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + ], +) diff --git a/mediapipe/tasks/python/vision/face_landmarker.py b/mediapipe/tasks/python/vision/face_landmarker.py new file mode 100644 index 00000000..93a296f9 --- /dev/null +++ b/mediapipe/tasks/python/vision/face_landmarker.py @@ -0,0 +1,449 @@ +# Copyright 2022 The MediaPipe Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""MediaPipe face landmarker task.""" + +import dataclasses +import enum +from typing import Callable, Mapping, Optional, List + +from mediapipe.framework.formats import classification_pb2 +from mediapipe.framework.formats import landmark_pb2 +from mediapipe.framework.formats import matrix_data_pb2 +from mediapipe.python import packet_creator +from mediapipe.python import packet_getter +from mediapipe.python._framework_bindings import image as image_module +from mediapipe.python._framework_bindings import packet as packet_module +from mediapipe.tasks.cc.vision.face_landmarker.proto import face_landmarker_graph_options_pb2 +from mediapipe.tasks.python.components.containers import category as category_module +from mediapipe.tasks.python.components.containers import landmark as landmark_module +from mediapipe.tasks.python.components.containers import matrix_data as matrix_data_module +from mediapipe.tasks.python.core import base_options as base_options_module +from mediapipe.tasks.python.core import task_info as task_info_module +from mediapipe.tasks.python.core.optional_dependencies import doc_controls +from mediapipe.tasks.python.vision.core import base_vision_task_api +from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module +from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module + +_BaseOptions = base_options_module.BaseOptions +_FaceLandmarkerGraphOptionsProto = face_landmarker_graph_options_pb2.FaceLandmarkerGraphOptions +_RunningMode = running_mode_module.VisionTaskRunningMode +_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions +_TaskInfo = task_info_module.TaskInfo + +_IMAGE_IN_STREAM_NAME = 'image_in' +_IMAGE_OUT_STREAM_NAME = 'image_out' +_IMAGE_TAG = 'IMAGE' +_NORM_RECT_STREAM_NAME = 'norm_rect_in' +_NORM_RECT_TAG = 'NORM_RECT' +_NORM_LANDMARKS_STREAM_NAME = 'norm_landmarks' +_NORM_LANDMARKS_TAG = 'NORM_LANDMARKS' +_BLENDSHAPES_STREAM_NAME = 'blendshapes' +_BLENDSHAPES_TAG = 'BLENDSHAPES' +_FACE_GEOMETRY_STREAM_NAME = 'face_geometry' +_FACE_GEOMETRY_TAG = 'FACE_GEOMETRY' +_TASK_GRAPH_NAME = 'mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph' +_MICRO_SECONDS_PER_MILLISECOND = 1000 + + +class Blendshapes(enum.IntEnum): + """The 52 blendshape coefficients.""" + NEUTRAL = 0 + BROW_DOWN_LEFT = 1 + BROW_DOWN_RIGHT = 2 + BROW_INNER_UP = 3 + BROW_OUTER_UP_LEFT = 4 + BROW_OUTER_UP_RIGHT = 5 + CHEEK_PUFF = 6 + CHEEK_SQUINT_LEFT = 7 + CHEEK_SQUINT_RIGHT = 8 + EYE_BLINK_LEFT = 9 + EYE_BLINK_RIGHT = 10 + EYE_LOOK_DOWN_LEFT = 11 + EYE_LOOK_DOWN_RIGHT = 12 + EYE_LOOK_IN_LEFT = 13 + EYE_LOOK_IN_RIGHT = 14 + EYE_LOOK_OUT_LEFT = 15 + EYE_LOOK_OUT_RIGHT = 16 + EYE_LOOK_UP_LEFT = 17 + EYE_LOOK_UP_RIGHT = 18 + EYE_SQUINT_LEFT = 19 + EYE_SQUINT_RIGHT = 20 + EYE_WIDE_LEFT = 21 + EYE_WIDE_RIGHT = 22 + JAW_FORWARD = 23 + JAW_LEFT = 24 + JAW_OPEN = 25 + JAW_RIGHT = 26 + MOUTH_CLOSE = 27 + MOUTH_DIMPLE_LEFT = 28 + MOUTH_DIMPLE_RIGHT = 29 + MOUTH_FROWN_LEFT = 30 + MOUTH_FROWN_RIGHT = 31 + MOUTH_FUNNEL = 32 + MOUTH_LEFT = 33 + MOUTH_LOWER_DOWN_LEFT = 34 + MOUTH_LOWER_DOWN_RIGHT = 35 + MOUTH_PRESS_LEFT = 36 + MOUTH_PRESS_RIGHT = 37 + MOUTH_PUCKER = 38 + MOUTH_RIGHT = 39 + MOUTH_ROLL_LOWER = 40 + MOUTH_ROLL_UPPER = 41 + MOUTH_SHRUG_LOWER = 42 + MOUTH_SHRUG_UPPER = 43 + MOUTH_SMILE_LEFT = 44 + MOUTH_SMILE_RIGHT = 45 + MOUTH_STRETCH_LEFT = 46 + MOUTH_STRETCH_RIGHT = 47 + MOUTH_UPPER_UP_LEFT = 48 + MOUTH_UPPER_UP_RIGHT = 49 + NOSE_SNEER_LEFT = 50 + NOSE_SNEER_RIGHT = 51 + + +@dataclasses.dataclass +class FaceLandmarkerResult: + """The face landmarks detection result from FaceLandmarker, where each vector element represents a single face detected in the image. + + Attributes: + face_landmarks: Detected face landmarks in normalized image coordinates. + face_blendshapes: Optional face blendshapes results. + facial_transformation_matrixes: Optional facial transformation matrix. + """ + + face_landmarks: List[List[landmark_module.NormalizedLandmark]] + face_blendshapes: List[List[category_module.Category]] + facial_transformation_matrixes: List[matrix_data_module.MatrixData] + + +def _build_landmarker_result( + output_packets: Mapping[str, packet_module.Packet]) -> FaceLandmarkerResult: + """Constructs a `FaceLandmarkerResult` from output packets.""" + face_landmarks_proto_list = packet_getter.get_proto_list( + output_packets[_NORM_LANDMARKS_STREAM_NAME]) + face_blendshapes_proto_list = packet_getter.get_proto_list( + output_packets[_BLENDSHAPES_STREAM_NAME]) + facial_transformation_matrixes_proto_list = packet_getter.get_proto_list( + output_packets[_FACE_GEOMETRY_STREAM_NAME]) + + face_landmarks_results = [] + for proto in face_landmarks_proto_list: + face_landmarks = landmark_pb2.NormalizedLandmarkList() + face_landmarks.MergeFrom(proto) + face_landmarks_list = [] + for face_landmark in face_landmarks.landmark: + face_landmarks.append( + landmark_module.NormalizedLandmark.create_from_pb2(face_landmark)) + face_landmarks_results.append(face_landmarks_list) + + face_blendshapes_results = [] + for proto in face_blendshapes_proto_list: + face_blendshapes_categories = [] + face_blendshapes_classifications = classification_pb2.ClassificationList() + face_blendshapes_classifications.MergeFrom(proto) + for face_blendshapes in face_blendshapes_classifications.classification: + face_blendshapes_categories.append( + category_module.Category( + index=face_blendshapes.index, + score=face_blendshapes.score, + display_name=face_blendshapes.display_name, + category_name=face_blendshapes.label)) + face_blendshapes_results.append(face_blendshapes_categories) + + facial_transformation_matrixes_results = [] + for proto in facial_transformation_matrixes_proto_list: + matrix_data = matrix_data_pb2.MatrixData() + matrix_data.MergeFrom(proto) + matrix = matrix_data_module.MatrixData.create_from_pb2(matrix_data) + facial_transformation_matrixes_results.append(matrix) + + return FaceLandmarkerResult(face_landmarks_results, face_blendshapes_results, + facial_transformation_matrixes_results) + + +@dataclasses.dataclass +class FaceLandmarkerOptions: + """Options for the face landmarker task. + + Attributes: + base_options: Base options for the face landmarker task. + running_mode: The running mode of the task. Default to the image mode. + HandLandmarker has three running modes: 1) The image mode for detecting + face landmarks on single image inputs. 2) The video mode for detecting + face landmarks on the decoded frames of a video. 3) The live stream mode + for detecting face landmarks on the live stream of input data, such as + from camera. In this mode, the "result_callback" below must be specified + to receive the detection results asynchronously. + num_faces: The maximum number of faces that can be detected by the + FaceLandmarker. + min_face_detection_confidence: The minimum confidence score for the face + detection to be considered successful. + min_face_presence_confidence: The minimum confidence score of face presence + score in the face landmark detection. + min_tracking_confidence: The minimum confidence score for the face tracking + to be considered successful. + output_face_blendshapes: Whether FaceLandmarker outputs face blendshapes + classification. Face blendshapes are used for rendering the 3D face model. + output_facial_transformation_matrixes: Whether FaceLandmarker outputs facial + transformation_matrix. Facial transformation matrix is used to transform + the face landmarks in canonical face to the detected face, so that users + can apply face effects on the detected landmarks. + result_callback: The user-defined result callback for processing live stream + data. The result callback should only be specified when the running mode + is set to the live stream mode. + """ + base_options: _BaseOptions + running_mode: _RunningMode = _RunningMode.IMAGE + num_faces: Optional[int] = 1 + min_face_detection_confidence: Optional[float] = 0.5 + min_face_presence_confidence: Optional[float] = 0.5 + min_tracking_confidence: Optional[float] = 0.5 + output_face_blendshapes: Optional[bool] = False + output_facial_transformation_matrixes: Optional[bool] = False + result_callback: Optional[Callable[ + [FaceLandmarkerResult, image_module.Image, int], None]] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _FaceLandmarkerGraphOptionsProto: + """Generates an FaceLandmarkerGraphOptions protobuf object.""" + base_options_proto = self.base_options.to_pb2() + base_options_proto.use_stream_mode = False if self.running_mode == _RunningMode.IMAGE else True + + # Initialize the face landmarker options from base options. + face_landmarker_options_proto = _FaceLandmarkerGraphOptionsProto( + base_options=base_options_proto) + + # Configure face detector options. + face_landmarker_options_proto.face_detector_graph_options.num_faces = self.num_faces + face_landmarker_options_proto.face_detector_graph_options.min_detection_confidence = self.min_face_detection_confidence + + # Configure face landmark detector options. + face_landmarker_options_proto.min_tracking_confidence = self.min_tracking_confidence + face_landmarker_options_proto.face_landmarks_detector_graph_options.min_detection_confidence = self.min_face_detection_confidence + return face_landmarker_options_proto + + +class FaceLandmarker(base_vision_task_api.BaseVisionTaskApi): + """Class that performs face landmarks detection on images.""" + + @classmethod + def create_from_model_path(cls, model_path: str) -> 'FaceLandmarker': + """Creates an `FaceLandmarker` object from a TensorFlow Lite model and the default `FaceLandmarkerOptions`. + + Note that the created `FaceLandmarker` instance is in image mode, for + detecting face landmarks on single image inputs. + + Args: + model_path: Path to the model. + + Returns: + `FaceLandmarker` object that's created from the model file and the + default `FaceLandmarkerOptions`. + + Raises: + ValueError: If failed to create `FaceLandmarker` object from the + provided file such as invalid file path. + RuntimeError: If other types of error occurred. + """ + base_options = _BaseOptions(model_asset_path=model_path) + options = FaceLandmarkerOptions( + base_options=base_options, running_mode=_RunningMode.IMAGE) + return cls.create_from_options(options) + + @classmethod + def create_from_options(cls, + options: FaceLandmarkerOptions) -> 'FaceLandmarker': + """Creates the `FaceLandmarker` object from face landmarker options. + + Args: + options: Options for the face landmarker task. + + Returns: + `FaceLandmarker` object that's created from `options`. + + Raises: + ValueError: If failed to create `FaceLandmarker` object from + `FaceLandmarkerOptions` such as missing the model. + RuntimeError: If other types of error occurred. + """ + + def packets_callback(output_packets: Mapping[str, packet_module.Packet]): + if output_packets[_IMAGE_OUT_STREAM_NAME].is_empty(): + return + + image = packet_getter.get_image(output_packets[_IMAGE_OUT_STREAM_NAME]) + if output_packets[_IMAGE_OUT_STREAM_NAME].is_empty(): + return + + if output_packets[_NORM_LANDMARKS_STREAM_NAME].is_empty(): + empty_packet = output_packets[_NORM_LANDMARKS_STREAM_NAME] + options.result_callback( + FaceLandmarkerResult([], [], []), image, + empty_packet.timestamp.value // _MICRO_SECONDS_PER_MILLISECOND) + return + + face_landmarks_result = _build_landmarker_result(output_packets) + timestamp = output_packets[_NORM_LANDMARKS_STREAM_NAME].timestamp + options.result_callback(face_landmarks_result, image, + timestamp.value // _MICRO_SECONDS_PER_MILLISECOND) + + task_info = _TaskInfo( + task_graph=_TASK_GRAPH_NAME, + input_streams=[ + ':'.join([_IMAGE_TAG, _IMAGE_IN_STREAM_NAME]), + ':'.join([_NORM_RECT_TAG, _NORM_RECT_STREAM_NAME]), + ], + output_streams=[ + ':'.join([_NORM_LANDMARKS_TAG, _NORM_LANDMARKS_STREAM_NAME]), + ':'.join([_BLENDSHAPES_TAG, _BLENDSHAPES_STREAM_NAME]), + ':'.join([ + _FACE_GEOMETRY_TAG, _FACE_GEOMETRY_STREAM_NAME + ]), ':'.join([_IMAGE_TAG, _IMAGE_OUT_STREAM_NAME]) + ], + task_options=options) + return cls( + task_info.generate_graph_config( + enable_flow_limiting=options.running_mode == + _RunningMode.LIVE_STREAM), options.running_mode, + packets_callback if options.result_callback else None) + + def detect( + self, + image: image_module.Image, + image_processing_options: Optional[_ImageProcessingOptions] = None + ) -> FaceLandmarkerResult: + """Performs face landmarks detection on the given image. + + Only use this method when the FaceLandmarker is created with the image + running mode. + + The image can be of any size with format RGB or RGBA. + TODO: Describes how the input image will be preprocessed after the yuv + support is implemented. + + Args: + image: MediaPipe Image. + image_processing_options: Options for image processing. + + Returns: + The face landmarks detection results. + + Raises: + ValueError: If any of the input arguments is invalid. + RuntimeError: If face landmarker detection failed to run. + """ + normalized_rect = self.convert_to_normalized_rect( + image_processing_options, roi_allowed=False) + output_packets = self._process_image_data({ + _IMAGE_IN_STREAM_NAME: + packet_creator.create_image(image), + _NORM_RECT_STREAM_NAME: + packet_creator.create_proto(normalized_rect.to_pb2()) + }) + + if output_packets[_NORM_LANDMARKS_STREAM_NAME].is_empty(): + return FaceLandmarkerResult([], [], []) + + return _build_landmarker_result(output_packets) + + def detect_for_video( + self, + image: image_module.Image, + timestamp_ms: int, + image_processing_options: Optional[_ImageProcessingOptions] = None + ) -> FaceLandmarkerResult: + """Performs face landmarks detection on the provided video frame. + + Only use this method when the FaceLandmarker is created with the video + running mode. + + Only use this method when the FaceLandmarker is created with the video + running mode. It's required to provide the video frame's timestamp (in + milliseconds) along with the video frame. The input timestamps should be + monotonically increasing for adjacent calls of this method. + + Args: + image: MediaPipe Image. + timestamp_ms: The timestamp of the input video frame in milliseconds. + image_processing_options: Options for image processing. + + Returns: + The face landmarks detection results. + + Raises: + ValueError: If any of the input arguments is invalid. + RuntimeError: If face landmarker detection failed to run. + """ + normalized_rect = self.convert_to_normalized_rect( + image_processing_options, roi_allowed=False) + output_packets = self._process_video_data({ + _IMAGE_IN_STREAM_NAME: + packet_creator.create_image(image).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND), + _NORM_RECT_STREAM_NAME: + packet_creator.create_proto(normalized_rect.to_pb2()).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) + }) + + if output_packets[_NORM_LANDMARKS_STREAM_NAME].is_empty(): + return FaceLandmarkerResult([], [], []) + + return _build_landmarker_result(output_packets) + + def detect_async( + self, + image: image_module.Image, + timestamp_ms: int, + image_processing_options: Optional[_ImageProcessingOptions] = None + ) -> None: + """Sends live image data to perform face landmarks detection. + + The results will be available via the "result_callback" provided in the + FaceLandmarkerOptions. Only use this method when the FaceLandmarker is + created with the live stream running mode. + + Only use this method when the FaceLandmarker is created with the live + stream running mode. The input timestamps should be monotonically increasing + for adjacent calls of this method. This method will return immediately after + the input image is accepted. The results will be available via the + `result_callback` provided in the `FaceLandmarkerOptions`. The + `detect_async` method is designed to process live stream data such as + camera input. To lower the overall latency, face landmarker may drop the + input images if needed. In other words, it's not guaranteed to have output + per input image. + + The `result_callback` provides: + - The face landmarks detection results. + - The input image that the face landmarker runs on. + - The input timestamp in milliseconds. + + Args: + image: MediaPipe Image. + timestamp_ms: The timestamp of the input image in milliseconds. + image_processing_options: Options for image processing. + + Raises: + ValueError: If the current input timestamp is smaller than what the + face landmarker has already processed. + """ + normalized_rect = self.convert_to_normalized_rect( + image_processing_options, roi_allowed=False) + self._send_live_stream_data({ + _IMAGE_IN_STREAM_NAME: + packet_creator.create_image(image).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND), + _NORM_RECT_STREAM_NAME: + packet_creator.create_proto(normalized_rect.to_pb2()).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) + }) From efae2830f1e3559eeb50ddf7bdbd2e4ea02e7852 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Mon, 13 Mar 2023 08:46:41 -0700 Subject: [PATCH 02/12] Updated face landmarker implementation and tests --- mediapipe/python/BUILD | 1 + .../test/vision/face_landmarker_test.py | 9 ++- .../tasks/python/vision/face_landmarker.py | 66 +++++++++++-------- 3 files changed, 42 insertions(+), 34 deletions(-) diff --git a/mediapipe/python/BUILD b/mediapipe/python/BUILD index f56e5b3d..49142108 100644 --- a/mediapipe/python/BUILD +++ b/mediapipe/python/BUILD @@ -94,6 +94,7 @@ cc_library( "//mediapipe/tasks/cc/vision/image_embedder:image_embedder_graph", "//mediapipe/tasks/cc/vision/image_segmenter:image_segmenter_graph", "//mediapipe/tasks/cc/vision/object_detector:object_detector_graph", + "//mediapipe/tasks/cc/vision/face_landmarker:face_landmarker_graph", ] + select({ # TODO: Build text_classifier_graph and text_embedder_graph on Windows. "//mediapipe:windows": [], diff --git a/mediapipe/tasks/python/test/vision/face_landmarker_test.py b/mediapipe/tasks/python/test/vision/face_landmarker_test.py index acdc0251..a9dd5715 100644 --- a/mediapipe/tasks/python/test/vision/face_landmarker_test.py +++ b/mediapipe/tasks/python/test/vision/face_landmarker_test.py @@ -152,7 +152,7 @@ class HandLandmarkerTest(parameterized.TestCase): _get_expected_face_landmarks(_PORTRAIT_EXPECTED_FACE_LANDMARKS)), (ModelFileType.FILE_CONTENT, _get_expected_face_landmarks(_PORTRAIT_EXPECTED_FACE_LANDMARKS))) - def test_detect(self, model_file_type, expected_result): + def test_detect(self, model_file_type, expected_face_landmarks): # Creates face landmarker. if model_file_type is ModelFileType.FILE_NAME: base_options = _BaseOptions(model_asset_path=self.model_path) @@ -164,15 +164,14 @@ class HandLandmarkerTest(parameterized.TestCase): # Should never happen raise ValueError('model_file_type is invalid.') - options = _FaceLandmarkerOptions(base_options=base_options, - output_face_blendshapes=True) + options = _FaceLandmarkerOptions(base_options=base_options) landmarker = _FaceLandmarker.create_from_options(options) # Performs face landmarks detection on the input. detection_result = landmarker.detect(self.test_image) # Comparing results. - self._expect_landmarks_correct(detection_result.face_landmarks, - expected_result.face_landmarks) + self._expect_landmarks_correct(detection_result.face_landmarks[0], + expected_face_landmarks) # Closes the face landmarker explicitly when the face landmarker is not used # in a context. landmarker.close() diff --git a/mediapipe/tasks/python/vision/face_landmarker.py b/mediapipe/tasks/python/vision/face_landmarker.py index 93a296f9..c109c646 100644 --- a/mediapipe/tasks/python/vision/face_landmarker.py +++ b/mediapipe/tasks/python/vision/face_landmarker.py @@ -132,10 +132,6 @@ def _build_landmarker_result( """Constructs a `FaceLandmarkerResult` from output packets.""" face_landmarks_proto_list = packet_getter.get_proto_list( output_packets[_NORM_LANDMARKS_STREAM_NAME]) - face_blendshapes_proto_list = packet_getter.get_proto_list( - output_packets[_BLENDSHAPES_STREAM_NAME]) - facial_transformation_matrixes_proto_list = packet_getter.get_proto_list( - output_packets[_FACE_GEOMETRY_STREAM_NAME]) face_landmarks_results = [] for proto in face_landmarks_proto_list: @@ -143,30 +139,36 @@ def _build_landmarker_result( face_landmarks.MergeFrom(proto) face_landmarks_list = [] for face_landmark in face_landmarks.landmark: - face_landmarks.append( + face_landmarks_list.append( landmark_module.NormalizedLandmark.create_from_pb2(face_landmark)) face_landmarks_results.append(face_landmarks_list) face_blendshapes_results = [] - for proto in face_blendshapes_proto_list: - face_blendshapes_categories = [] - face_blendshapes_classifications = classification_pb2.ClassificationList() - face_blendshapes_classifications.MergeFrom(proto) - for face_blendshapes in face_blendshapes_classifications.classification: - face_blendshapes_categories.append( - category_module.Category( - index=face_blendshapes.index, - score=face_blendshapes.score, - display_name=face_blendshapes.display_name, - category_name=face_blendshapes.label)) - face_blendshapes_results.append(face_blendshapes_categories) + if _BLENDSHAPES_STREAM_NAME in output_packets: + face_blendshapes_proto_list = packet_getter.get_proto_list( + output_packets[_BLENDSHAPES_STREAM_NAME]) + for proto in face_blendshapes_proto_list: + face_blendshapes_categories = [] + face_blendshapes_classifications = classification_pb2.ClassificationList() + face_blendshapes_classifications.MergeFrom(proto) + for face_blendshapes in face_blendshapes_classifications.classification: + face_blendshapes_categories.append( + category_module.Category( + index=face_blendshapes.index, + score=face_blendshapes.score, + display_name=face_blendshapes.display_name, + category_name=face_blendshapes.label)) + face_blendshapes_results.append(face_blendshapes_categories) facial_transformation_matrixes_results = [] - for proto in facial_transformation_matrixes_proto_list: - matrix_data = matrix_data_pb2.MatrixData() - matrix_data.MergeFrom(proto) - matrix = matrix_data_module.MatrixData.create_from_pb2(matrix_data) - facial_transformation_matrixes_results.append(matrix) + if _FACE_GEOMETRY_STREAM_NAME in output_packets: + facial_transformation_matrixes_proto_list = packet_getter.get_proto_list( + output_packets[_FACE_GEOMETRY_STREAM_NAME]) + for proto in facial_transformation_matrixes_proto_list: + matrix_data = matrix_data_pb2.MatrixData() + matrix_data.MergeFrom(proto) + matrix = matrix_data_module.MatrixData.create_from_pb2(matrix_data) + facial_transformation_matrixes_results.append(matrix) return FaceLandmarkerResult(face_landmarks_results, face_blendshapes_results, facial_transformation_matrixes_results) @@ -298,19 +300,25 @@ class FaceLandmarker(base_vision_task_api.BaseVisionTaskApi): options.result_callback(face_landmarks_result, image, timestamp.value // _MICRO_SECONDS_PER_MILLISECOND) + output_streams = [ + ':'.join([_NORM_LANDMARKS_TAG, _NORM_LANDMARKS_STREAM_NAME]), + ':'.join([_IMAGE_TAG, _IMAGE_OUT_STREAM_NAME]) + ] + + if options.output_face_blendshapes: + output_streams.append( + ':'.join([_BLENDSHAPES_TAG, _BLENDSHAPES_STREAM_NAME])) + if options.output_facial_transformation_matrixes: + output_streams.append( + ':'.join([_FACE_GEOMETRY_TAG, _FACE_GEOMETRY_STREAM_NAME])) + task_info = _TaskInfo( task_graph=_TASK_GRAPH_NAME, input_streams=[ ':'.join([_IMAGE_TAG, _IMAGE_IN_STREAM_NAME]), ':'.join([_NORM_RECT_TAG, _NORM_RECT_STREAM_NAME]), ], - output_streams=[ - ':'.join([_NORM_LANDMARKS_TAG, _NORM_LANDMARKS_STREAM_NAME]), - ':'.join([_BLENDSHAPES_TAG, _BLENDSHAPES_STREAM_NAME]), - ':'.join([ - _FACE_GEOMETRY_TAG, _FACE_GEOMETRY_STREAM_NAME - ]), ':'.join([_IMAGE_TAG, _IMAGE_OUT_STREAM_NAME]) - ], + output_streams=output_streams, task_options=options) return cls( task_info.generate_graph_config( From 23681cde0dbb844e71a5cb5fb4b2c61d9cbb9fcf Mon Sep 17 00:00:00 2001 From: kinaryml Date: Tue, 14 Mar 2023 00:37:32 -0700 Subject: [PATCH 03/12] Revised face landmarker implementation and tests --- .../components/containers/matrix_data.py | 15 +-- mediapipe/tasks/python/test/vision/BUILD | 2 +- .../test/vision/face_landmarker_test.py | 109 ++++++++++++++++-- .../tasks/python/vision/face_landmarker.py | 1 + mediapipe/tasks/testdata/vision/BUILD | 2 + 5 files changed, 109 insertions(+), 20 deletions(-) diff --git a/mediapipe/tasks/python/components/containers/matrix_data.py b/mediapipe/tasks/python/components/containers/matrix_data.py index 9f0d5dfd..2cef4a5c 100644 --- a/mediapipe/tasks/python/components/containers/matrix_data.py +++ b/mediapipe/tasks/python/components/containers/matrix_data.py @@ -17,6 +17,7 @@ import dataclasses import enum from typing import Any, Optional +import numpy as np from mediapipe.framework.formats import matrix_data_pb2 from mediapipe.tasks.python.core.optional_dependencies import doc_controls @@ -32,7 +33,7 @@ class MatrixData: Attributes: rows: The number of rows in the matrix. cols: The number of columns in the matrix. - data: The data stored in the matrix. + data: The data stored in the matrix as a NumPy array. layout: The order in which the data are stored. Defaults to COLUMN_MAJOR. """ @@ -40,10 +41,10 @@ class MatrixData: COLUMN_MAJOR = 0 ROW_MAJOR = 1 - rows: Optional[int] = None - cols: Optional[int] = None - data: Optional[float] = None - layout: Optional[Layout] = None + rows: int = None + cols: int = None + data: np.ndarray = None + layout: Optional[Layout] = Layout.COLUMN_MAJOR @doc_controls.do_not_generate_docs def to_pb2(self) -> _MatrixDataProto: @@ -51,7 +52,7 @@ class MatrixData: return _MatrixDataProto( rows=self.rows, cols=self.cols, - data=self.data, + data=self.data.tolist(), layout=self.layout) @classmethod @@ -61,7 +62,7 @@ class MatrixData: return MatrixData( rows=pb2_obj.rows, cols=pb2_obj.cols, - data=pb2_obj.data, + data=np.array(pb2_obj.data), layout=pb2_obj.layout) def __eq__(self, other: Any) -> bool: diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index 0a1a18ff..55f619ae 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -126,10 +126,10 @@ py_test( deps = [ "//mediapipe/python:_framework_bindings", "//mediapipe/framework/formats:landmark_py_pb2", + "//mediapipe/framework/formats:classification_py_pb2", "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/components/containers:landmark", "//mediapipe/tasks/python/components/containers:rect", - "//mediapipe/tasks/python/components/containers:classification_result", "//mediapipe/tasks/python/components/containers:matrix_data", "//mediapipe/tasks/python/core:base_options", "//mediapipe/tasks/python/test:test_utils", diff --git a/mediapipe/tasks/python/test/vision/face_landmarker_test.py b/mediapipe/tasks/python/test/vision/face_landmarker_test.py index a9dd5715..49cdacbf 100644 --- a/mediapipe/tasks/python/test/vision/face_landmarker_test.py +++ b/mediapipe/tasks/python/test/vision/face_landmarker_test.py @@ -22,11 +22,12 @@ import numpy as np from google.protobuf import text_format from mediapipe.framework.formats import landmark_pb2 +from mediapipe.framework.formats import classification_pb2 from mediapipe.python._framework_bindings import image as image_module from mediapipe.tasks.python.components.containers import category as category_module from mediapipe.tasks.python.components.containers import landmark as landmark_module +from mediapipe.tasks.python.components.containers import matrix_data as matrix_data_module from mediapipe.tasks.python.components.containers import rect as rect_module -from mediapipe.tasks.python.components.containers import classification_result as classification_result_module from mediapipe.tasks.python.core import base_options as base_options_module from mediapipe.tasks.python.test import test_utils from mediapipe.tasks.python.vision import face_landmarker @@ -38,6 +39,7 @@ _BaseOptions = base_options_module.BaseOptions _Category = category_module.Category _Rect = rect_module.Rect _Landmark = landmark_module.Landmark +_MatrixData = matrix_data_module.MatrixData _NormalizedLandmark = landmark_module.NormalizedLandmark _Image = image_module.Image _FaceLandmarker = face_landmarker.FaceLandmarker @@ -51,6 +53,7 @@ _PORTRAIT_IMAGE = 'portrait.jpg' _PORTRAIT_EXPECTED_FACE_LANDMARKS = 'portrait_expected_face_landmarks.pbtxt' _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION = 'portrait_expected_face_landmarks_with_attention.pbtxt' _PORTRAIT_EXPECTED_BLENDSHAPES = 'portrait_expected_blendshapes_with_attention.pbtxt' +_PORTRAIT_EXPECTED_FACE_GEOMETRY = 'portrait_expected_face_geometry_with_attention.pbtxt' _LANDMARKS_DIFF_MARGIN = 0.03 _BLENDSHAPES_DIFF_MARGIN = 0.1 _FACIAL_TRANSFORMATION_MATRIX_DIFF_MARGIN = 0.02 @@ -61,10 +64,40 @@ def _get_expected_face_landmarks(file_path: str): with open(proto_file_path, 'rb') as f: proto = landmark_pb2.NormalizedLandmarkList() text_format.Parse(f.read(), proto) - landmarks = [] + face_landmarks = [] for landmark in proto.landmark: - landmarks.append(_NormalizedLandmark.create_from_pb2(landmark)) - return landmarks + face_landmarks.append(_NormalizedLandmark.create_from_pb2(landmark)) + return face_landmarks + + +def _get_expected_face_blendshapes(file_path: str): + proto_file_path = test_utils.get_test_data_path(file_path) + with open(proto_file_path, 'rb') as f: + proto = classification_pb2.ClassificationList() + text_format.Parse(f.read(), proto) + face_blendshapes_categories = [] + face_blendshapes_classifications = classification_pb2.ClassificationList() + face_blendshapes_classifications.MergeFrom(proto) + for face_blendshapes in face_blendshapes_classifications.classification: + face_blendshapes_categories.append( + category_module.Category( + index=face_blendshapes.index, + score=face_blendshapes.score, + display_name=face_blendshapes.display_name, + category_name=face_blendshapes.label)) + return face_blendshapes_categories + + +def _make_expected_facial_transformation_matrixes(): + data = np.array([[0.9995292, -0.005092691, 0.030254554, -0.37340546], + [0.0072318087, 0.99744856, -0.07102106, 22.212194], + [-0.029815676, 0.07120642, 0.9970159, -64.76358], + [0, 0, 0, 1]]) + rows, cols = len(data), len(data[0]) + facial_transformation_matrixes_results = [] + facial_transformation_matrix = _MatrixData(rows, cols, data) + facial_transformation_matrixes_results.append(facial_transformation_matrix) + return facial_transformation_matrixes_results class ModelFileType(enum.Enum): @@ -148,30 +181,82 @@ class HandLandmarkerTest(parameterized.TestCase): self.assertIsInstance(landmarker, _FaceLandmarker) @parameterized.parameters( + (ModelFileType.FILE_NAME, _FACE_LANDMARKER_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), + (ModelFileType.FILE_CONTENT, _FACE_LANDMARKER_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), (ModelFileType.FILE_NAME, - _get_expected_face_landmarks(_PORTRAIT_EXPECTED_FACE_LANDMARKS)), + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), (ModelFileType.FILE_CONTENT, - _get_expected_face_landmarks(_PORTRAIT_EXPECTED_FACE_LANDMARKS))) - def test_detect(self, model_file_type, expected_face_landmarks): + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), + (ModelFileType.FILE_NAME, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), None), + (ModelFileType.FILE_CONTENT, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), None), + # (ModelFileType.FILE_NAME, + # _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + # _get_expected_face_landmarks( + # _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + # _get_expected_face_blendshapes( + # _PORTRAIT_EXPECTED_BLENDSHAPES), + # _make_expected_facial_transformation_matrixes()), + # (ModelFileType.FILE_CONTENT, + # _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + # _get_expected_face_landmarks( + # _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + # _get_expected_face_blendshapes( + # _PORTRAIT_EXPECTED_BLENDSHAPES), + # _make_expected_facial_transformation_matrixes()) + ) + def test_detect(self, model_file_type, model_name, expected_face_landmarks, + expected_face_blendshapes, expected_facial_transformation_matrix): # Creates face landmarker. + model_path = test_utils.get_test_data_path(model_name) if model_file_type is ModelFileType.FILE_NAME: - base_options = _BaseOptions(model_asset_path=self.model_path) + base_options = _BaseOptions(model_asset_path=model_path) elif model_file_type is ModelFileType.FILE_CONTENT: - with open(self.model_path, 'rb') as f: + with open(model_path, 'rb') as f: model_content = f.read() base_options = _BaseOptions(model_asset_buffer=model_content) else: # Should never happen raise ValueError('model_file_type is invalid.') - options = _FaceLandmarkerOptions(base_options=base_options) + options = _FaceLandmarkerOptions( + base_options=base_options, + output_face_blendshapes=True if expected_face_blendshapes else False, + output_facial_transformation_matrixes=True + if expected_facial_transformation_matrix else False) landmarker = _FaceLandmarker.create_from_options(options) # Performs face landmarks detection on the input. detection_result = landmarker.detect(self.test_image) # Comparing results. - self._expect_landmarks_correct(detection_result.face_landmarks[0], - expected_face_landmarks) + if expected_face_landmarks is not None: + self._expect_landmarks_correct(detection_result.face_landmarks[0], + expected_face_landmarks) + if expected_face_blendshapes is not None: + self._expect_blendshapes_correct(detection_result.face_blendshapes[0], + expected_face_blendshapes) + if expected_facial_transformation_matrix is not None: + self._expect_facial_transformation_matrix_correct( + detection_result.facial_transformation_matrixes[0], + expected_facial_transformation_matrix) + # Closes the face landmarker explicitly when the face landmarker is not used # in a context. landmarker.close() diff --git a/mediapipe/tasks/python/vision/face_landmarker.py b/mediapipe/tasks/python/vision/face_landmarker.py index c109c646..519a78df 100644 --- a/mediapipe/tasks/python/vision/face_landmarker.py +++ b/mediapipe/tasks/python/vision/face_landmarker.py @@ -162,6 +162,7 @@ def _build_landmarker_result( facial_transformation_matrixes_results = [] if _FACE_GEOMETRY_STREAM_NAME in output_packets: + print(output_packets[_FACE_GEOMETRY_STREAM_NAME]) facial_transformation_matrixes_proto_list = packet_getter.get_proto_list( output_packets[_FACE_GEOMETRY_STREAM_NAME]) for proto in facial_transformation_matrixes_proto_list: diff --git a/mediapipe/tasks/testdata/vision/BUILD b/mediapipe/tasks/testdata/vision/BUILD index 63e3613e..f15b6bab 100644 --- a/mediapipe/tasks/testdata/vision/BUILD +++ b/mediapipe/tasks/testdata/vision/BUILD @@ -156,6 +156,7 @@ filegroup( "face_landmark.tflite", "face_landmark_with_attention.tflite", "face_landmarker.task", + "face_landmarker_with_blendshapes.task", "hair_segmentation.tflite", "hand_landmark_full.tflite", "hand_landmark_lite.tflite", @@ -191,6 +192,7 @@ filegroup( "pointing_up_landmarks.pbtxt", "pointing_up_rotated_landmarks.pbtxt", "portrait_expected_detection.pbtxt", + "portrait_expected_blendshapes_with_attention.pbtxt", "portrait_expected_face_geometry_with_attention.pbtxt", "portrait_expected_face_landmarks.pbtxt", "portrait_expected_face_landmarks_with_attention.pbtxt", From d83f400b0860001dcca0952c6762bb2e4cc62d3e Mon Sep 17 00:00:00 2001 From: kinaryml Date: Tue, 14 Mar 2023 22:32:39 -0700 Subject: [PATCH 04/12] Updated API and tests --- .../test/vision/face_landmarker_test.py | 28 +++++++++---------- .../tasks/python/vision/face_landmarker.py | 1 - 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/mediapipe/tasks/python/test/vision/face_landmarker_test.py b/mediapipe/tasks/python/test/vision/face_landmarker_test.py index 49cdacbf..eec19d58 100644 --- a/mediapipe/tasks/python/test/vision/face_landmarker_test.py +++ b/mediapipe/tasks/python/test/vision/face_landmarker_test.py @@ -207,20 +207,20 @@ class HandLandmarkerTest(parameterized.TestCase): _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), _get_expected_face_blendshapes( _PORTRAIT_EXPECTED_BLENDSHAPES), None), - # (ModelFileType.FILE_NAME, - # _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, - # _get_expected_face_landmarks( - # _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), - # _get_expected_face_blendshapes( - # _PORTRAIT_EXPECTED_BLENDSHAPES), - # _make_expected_facial_transformation_matrixes()), - # (ModelFileType.FILE_CONTENT, - # _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, - # _get_expected_face_landmarks( - # _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), - # _get_expected_face_blendshapes( - # _PORTRAIT_EXPECTED_BLENDSHAPES), - # _make_expected_facial_transformation_matrixes()) + (ModelFileType.FILE_NAME, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), + _make_expected_facial_transformation_matrixes()), + (ModelFileType.FILE_CONTENT, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), + _make_expected_facial_transformation_matrixes()) ) def test_detect(self, model_file_type, model_name, expected_face_landmarks, expected_face_blendshapes, expected_facial_transformation_matrix): diff --git a/mediapipe/tasks/python/vision/face_landmarker.py b/mediapipe/tasks/python/vision/face_landmarker.py index 519a78df..c109c646 100644 --- a/mediapipe/tasks/python/vision/face_landmarker.py +++ b/mediapipe/tasks/python/vision/face_landmarker.py @@ -162,7 +162,6 @@ def _build_landmarker_result( facial_transformation_matrixes_results = [] if _FACE_GEOMETRY_STREAM_NAME in output_packets: - print(output_packets[_FACE_GEOMETRY_STREAM_NAME]) facial_transformation_matrixes_proto_list = packet_getter.get_proto_list( output_packets[_FACE_GEOMETRY_STREAM_NAME]) for proto in facial_transformation_matrixes_proto_list: From 06c37c6442d058589d44fe2e076351279ec8fffc Mon Sep 17 00:00:00 2001 From: kinaryml Date: Wed, 15 Mar 2023 09:11:06 -0700 Subject: [PATCH 05/12] Updated mediapipe/python/BUILD and tests --- mediapipe/python/BUILD | 1 + mediapipe/tasks/python/test/vision/face_landmarker_test.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/mediapipe/python/BUILD b/mediapipe/python/BUILD index 8aa11f5f..879f8281 100644 --- a/mediapipe/python/BUILD +++ b/mediapipe/python/BUILD @@ -37,6 +37,7 @@ pybind_extension( deps = [ ":builtin_calculators", ":builtin_task_graphs", + "//mediapipe/tasks/cc/vision/face_geometry/calculators:geometry_pipeline_calculator", "//mediapipe/python/pybind:calculator_graph", "//mediapipe/python/pybind:image", "//mediapipe/python/pybind:image_frame", diff --git a/mediapipe/tasks/python/test/vision/face_landmarker_test.py b/mediapipe/tasks/python/test/vision/face_landmarker_test.py index eec19d58..fe189128 100644 --- a/mediapipe/tasks/python/test/vision/face_landmarker_test.py +++ b/mediapipe/tasks/python/test/vision/face_landmarker_test.py @@ -105,7 +105,7 @@ class ModelFileType(enum.Enum): FILE_NAME = 2 -class HandLandmarkerTest(parameterized.TestCase): +class FaceLandmarkerTest(parameterized.TestCase): def setUp(self): super().setUp() From 4a6015e65cf9ad3f64b6c70776b7bdce1db57534 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Wed, 15 Mar 2023 10:41:36 -0700 Subject: [PATCH 06/12] Fixed some issues in the MatrixData container, revised the implementation and added more tests --- .../components/containers/matrix_data.py | 17 +- .../test/vision/face_landmarker_test.py | 333 +++++++++++++++++- mediapipe/tasks/python/vision/BUILD | 1 + .../tasks/python/vision/face_landmarker.py | 17 +- 4 files changed, 341 insertions(+), 27 deletions(-) diff --git a/mediapipe/tasks/python/components/containers/matrix_data.py b/mediapipe/tasks/python/components/containers/matrix_data.py index 2cef4a5c..ded3a9b4 100644 --- a/mediapipe/tasks/python/components/containers/matrix_data.py +++ b/mediapipe/tasks/python/components/containers/matrix_data.py @@ -24,6 +24,11 @@ from mediapipe.tasks.python.core.optional_dependencies import doc_controls _MatrixDataProto = matrix_data_pb2.MatrixData +class Layout(enum.Enum): + COLUMN_MAJOR = 0 + ROW_MAJOR = 1 + + @dataclasses.dataclass class MatrixData: """This stores the Matrix data. @@ -37,10 +42,6 @@ class MatrixData: layout: The order in which the data are stored. Defaults to COLUMN_MAJOR. """ - class Layout(enum.Enum): - COLUMN_MAJOR = 0 - ROW_MAJOR = 1 - rows: int = None cols: int = None data: np.ndarray = None @@ -52,8 +53,8 @@ class MatrixData: return _MatrixDataProto( rows=self.rows, cols=self.cols, - data=self.data.tolist(), - layout=self.layout) + packed_data=self.data, + layout=self.layout.value) @classmethod @doc_controls.do_not_generate_docs @@ -62,8 +63,8 @@ class MatrixData: return MatrixData( rows=pb2_obj.rows, cols=pb2_obj.cols, - data=np.array(pb2_obj.data), - layout=pb2_obj.layout) + data=np.array(pb2_obj.packed_data), + layout=Layout(pb2_obj.layout)) def __eq__(self, other: Any) -> bool: """Checks if this object is equal to the given object. diff --git a/mediapipe/tasks/python/test/vision/face_landmarker_test.py b/mediapipe/tasks/python/test/vision/face_landmarker_test.py index fe189128..a6b6e02f 100644 --- a/mediapipe/tasks/python/test/vision/face_landmarker_test.py +++ b/mediapipe/tasks/python/test/vision/face_landmarker_test.py @@ -50,12 +50,13 @@ _ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _FACE_LANDMARKER_BUNDLE_ASSET_FILE = 'face_landmarker.task' _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE = 'face_landmarker_with_blendshapes.task' _PORTRAIT_IMAGE = 'portrait.jpg' +_CAT_IMAGE = 'cat.jpg' _PORTRAIT_EXPECTED_FACE_LANDMARKS = 'portrait_expected_face_landmarks.pbtxt' _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION = 'portrait_expected_face_landmarks_with_attention.pbtxt' _PORTRAIT_EXPECTED_BLENDSHAPES = 'portrait_expected_blendshapes_with_attention.pbtxt' _PORTRAIT_EXPECTED_FACE_GEOMETRY = 'portrait_expected_face_geometry_with_attention.pbtxt' _LANDMARKS_DIFF_MARGIN = 0.03 -_BLENDSHAPES_DIFF_MARGIN = 0.1 +_BLENDSHAPES_DIFF_MARGIN = 0.12 _FACIAL_TRANSFORMATION_MATRIX_DIFF_MARGIN = 0.02 @@ -90,12 +91,12 @@ def _get_expected_face_blendshapes(file_path: str): def _make_expected_facial_transformation_matrixes(): data = np.array([[0.9995292, -0.005092691, 0.030254554, -0.37340546], - [0.0072318087, 0.99744856, -0.07102106, 22.212194], - [-0.029815676, 0.07120642, 0.9970159, -64.76358], - [0, 0, 0, 1]]) + [0.0072318087, 0.99744856, -0.07102106, 22.212194], + [-0.029815676, 0.07120642, 0.9970159, -64.76358], + [0, 0, 0, 1]]) rows, cols = len(data), len(data[0]) facial_transformation_matrixes_results = [] - facial_transformation_matrix = _MatrixData(rows, cols, data) + facial_transformation_matrix = _MatrixData(rows, cols, data.flatten()) facial_transformation_matrixes_results.append(facial_transformation_matrix) return facial_transformation_matrixes_results @@ -147,8 +148,8 @@ class FaceLandmarkerTest(parameterized.TestCase): self.assertEqual(rename_me.rows, expected_matrix_list[i].rows) self.assertEqual(rename_me.cols, expected_matrix_list[i].cols) self.assertAlmostEqual( - rename_me.data, - expected_matrix_list[i].data, + rename_me.data.all(), + expected_matrix_list[i].data.all(), delta=_FACIAL_TRANSFORMATION_MATRIX_DIFF_MARGIN) def test_create_from_file_succeeds_with_valid_model_path(self): @@ -220,10 +221,10 @@ class FaceLandmarkerTest(parameterized.TestCase): _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), _get_expected_face_blendshapes( _PORTRAIT_EXPECTED_BLENDSHAPES), - _make_expected_facial_transformation_matrixes()) - ) - def test_detect(self, model_file_type, model_name, expected_face_landmarks, - expected_face_blendshapes, expected_facial_transformation_matrix): + _make_expected_facial_transformation_matrixes())) + def test_detect( + self, model_file_type, model_name, expected_face_landmarks, + expected_face_blendshapes, expected_facial_transformation_matrixes): # Creates face landmarker. model_path = test_utils.get_test_data_path(model_name) if model_file_type is ModelFileType.FILE_NAME: @@ -240,7 +241,7 @@ class FaceLandmarkerTest(parameterized.TestCase): base_options=base_options, output_face_blendshapes=True if expected_face_blendshapes else False, output_facial_transformation_matrixes=True - if expected_facial_transformation_matrix else False) + if expected_facial_transformation_matrixes else False) landmarker = _FaceLandmarker.create_from_options(options) # Performs face landmarks detection on the input. @@ -252,15 +253,317 @@ class FaceLandmarkerTest(parameterized.TestCase): if expected_face_blendshapes is not None: self._expect_blendshapes_correct(detection_result.face_blendshapes[0], expected_face_blendshapes) - if expected_facial_transformation_matrix is not None: + if expected_facial_transformation_matrixes is not None: self._expect_facial_transformation_matrix_correct( - detection_result.facial_transformation_matrixes[0], - expected_facial_transformation_matrix) + detection_result.facial_transformation_matrixes, + expected_facial_transformation_matrixes) # Closes the face landmarker explicitly when the face landmarker is not used # in a context. landmarker.close() + @parameterized.parameters( + (ModelFileType.FILE_NAME, _FACE_LANDMARKER_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), + (ModelFileType.FILE_CONTENT, _FACE_LANDMARKER_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), + (ModelFileType.FILE_NAME, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), + (ModelFileType.FILE_CONTENT, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), + (ModelFileType.FILE_NAME, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), None), + (ModelFileType.FILE_CONTENT, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), None), + (ModelFileType.FILE_NAME, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), + _make_expected_facial_transformation_matrixes()), + (ModelFileType.FILE_CONTENT, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), + _make_expected_facial_transformation_matrixes())) + def test_detect_in_context( + self, model_file_type, model_name, expected_face_landmarks, + expected_face_blendshapes, expected_facial_transformation_matrixes): + # Creates face landmarker. + model_path = test_utils.get_test_data_path(model_name) + if model_file_type is ModelFileType.FILE_NAME: + base_options = _BaseOptions(model_asset_path=model_path) + elif model_file_type is ModelFileType.FILE_CONTENT: + with open(model_path, 'rb') as f: + model_content = f.read() + base_options = _BaseOptions(model_asset_buffer=model_content) + else: + # Should never happen + raise ValueError('model_file_type is invalid.') + + options = _FaceLandmarkerOptions( + base_options=base_options, + output_face_blendshapes=True if expected_face_blendshapes else False, + output_facial_transformation_matrixes=True + if expected_facial_transformation_matrixes else False) + + with _FaceLandmarker.create_from_options(options) as landmarker: + # Performs face landmarks detection on the input. + detection_result = landmarker.detect(self.test_image) + # Comparing results. + if expected_face_landmarks is not None: + self._expect_landmarks_correct(detection_result.face_landmarks[0], + expected_face_landmarks) + if expected_face_blendshapes is not None: + self._expect_blendshapes_correct(detection_result.face_blendshapes[0], + expected_face_blendshapes) + if expected_facial_transformation_matrixes is not None: + self._expect_facial_transformation_matrix_correct( + detection_result.facial_transformation_matrixes, + expected_facial_transformation_matrixes) + + def test_detect_succeeds_with_num_faces(self): + # Creates face landmarker. + model_path = test_utils.get_test_data_path( + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE) + base_options = _BaseOptions(model_asset_path=model_path) + options = _FaceLandmarkerOptions(base_options=base_options, num_faces=1, + output_face_blendshapes=True) + with _FaceLandmarker.create_from_options(options) as landmarker: + # Load the portrait image. + test_image = _Image.create_from_file( + test_utils.get_test_data_path(_PORTRAIT_IMAGE)) + # Performs face landmarks detection on the input. + detection_result = landmarker.detect(test_image) + # Comparing results. + self.assertLen(detection_result.face_blendshapes, 1) + + def test_empty_detection_outputs(self): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path)) + with _FaceLandmarker.create_from_options(options) as landmarker: + # Load the image with no faces. + no_faces_test_image = _Image.create_from_file( + test_utils.get_test_data_path(_CAT_IMAGE)) + # Performs face landmarks detection on the input. + detection_result = landmarker.detect(no_faces_test_image) + self.assertEmpty(detection_result.face_landmarks) + self.assertEmpty(detection_result.face_blendshapes) + self.assertEmpty(detection_result.facial_transformation_matrixes) + + def test_missing_result_callback(self): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM) + with self.assertRaisesRegex(ValueError, + r'result callback must be provided'): + with _FaceLandmarker.create_from_options(options) as unused_landmarker: + pass + + @parameterized.parameters((_RUNNING_MODE.IMAGE), (_RUNNING_MODE.VIDEO)) + def test_illegal_result_callback(self, running_mode): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=running_mode, + result_callback=mock.MagicMock()) + with self.assertRaisesRegex(ValueError, + r'result callback should not be provided'): + with _FaceLandmarker.create_from_options(options) as unused_landmarker: + pass + + def test_calling_detect_for_video_in_image_mode(self): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.IMAGE) + with _FaceLandmarker.create_from_options(options) as landmarker: + with self.assertRaisesRegex(ValueError, + r'not initialized with the video mode'): + landmarker.detect_for_video(self.test_image, 0) + + def test_calling_detect_async_in_image_mode(self): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.IMAGE) + with _FaceLandmarker.create_from_options(options) as landmarker: + with self.assertRaisesRegex(ValueError, + r'not initialized with the live stream mode'): + landmarker.detect_async(self.test_image, 0) + + def test_calling_detect_in_video_mode(self): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _FaceLandmarker.create_from_options(options) as landmarker: + with self.assertRaisesRegex(ValueError, + r'not initialized with the image mode'): + landmarker.detect(self.test_image) + + def test_calling_detect_async_in_video_mode(self): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _FaceLandmarker.create_from_options(options) as landmarker: + with self.assertRaisesRegex(ValueError, + r'not initialized with the live stream mode'): + landmarker.detect_async(self.test_image, 0) + + def test_detect_for_video_with_out_of_order_timestamp(self): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _FaceLandmarker.create_from_options(options) as landmarker: + unused_result = landmarker.detect_for_video(self.test_image, 1) + with self.assertRaisesRegex( + ValueError, r'Input timestamp must be monotonically increasing'): + landmarker.detect_for_video(self.test_image, 0) + + @parameterized.parameters( + (_FACE_LANDMARKER_BUNDLE_ASSET_FILE, _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), + (_FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), + (_FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes(_PORTRAIT_EXPECTED_BLENDSHAPES), None), + (_FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes(_PORTRAIT_EXPECTED_BLENDSHAPES), + _make_expected_facial_transformation_matrixes())) + def test_detect_for_video( + self, model_name, expected_face_landmarks, expected_face_blendshapes, + expected_facial_transformation_matrixes): + # Creates face landmarker. + model_path = test_utils.get_test_data_path(model_name) + base_options = _BaseOptions(model_asset_path=model_path) + + options = _FaceLandmarkerOptions( + base_options=base_options, + running_mode=_RUNNING_MODE.VIDEO, + output_face_blendshapes=True if expected_face_blendshapes else False, + output_facial_transformation_matrixes=True + if expected_facial_transformation_matrixes else False) + + with _FaceLandmarker.create_from_options(options) as landmarker: + for timestamp in range(0, 300, 30): + # Performs face landmarks detection on the input. + detection_result = landmarker.detect_for_video(self.test_image, + timestamp) + # Comparing results. + if expected_face_landmarks is not None: + self._expect_landmarks_correct(detection_result.face_landmarks[0], + expected_face_landmarks) + if expected_face_blendshapes is not None: + self._expect_blendshapes_correct(detection_result.face_blendshapes[0], + expected_face_blendshapes) + if expected_facial_transformation_matrixes is not None: + self._expect_facial_transformation_matrix_correct( + detection_result.facial_transformation_matrixes, + expected_facial_transformation_matrixes) + + def test_calling_detect_in_live_stream_mode(self): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=mock.MagicMock()) + with _FaceLandmarker.create_from_options(options) as landmarker: + with self.assertRaisesRegex(ValueError, + r'not initialized with the image mode'): + landmarker.detect(self.test_image) + + def test_calling_detect_for_video_in_live_stream_mode(self): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=mock.MagicMock()) + with _FaceLandmarker.create_from_options(options) as landmarker: + with self.assertRaisesRegex(ValueError, + r'not initialized with the video mode'): + landmarker.detect_for_video(self.test_image, 0) + + def test_detect_async_calls_with_illegal_timestamp(self): + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=mock.MagicMock()) + with _FaceLandmarker.create_from_options(options) as landmarker: + landmarker.detect_async(self.test_image, 100) + with self.assertRaisesRegex( + ValueError, r'Input timestamp must be monotonically increasing'): + landmarker.detect_async(self.test_image, 0) + + @parameterized.parameters( + (_PORTRAIT_IMAGE, _FACE_LANDMARKER_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), + (_PORTRAIT_IMAGE, _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), + (_PORTRAIT_IMAGE, _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes(_PORTRAIT_EXPECTED_BLENDSHAPES), None), + (_PORTRAIT_IMAGE, _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes(_PORTRAIT_EXPECTED_BLENDSHAPES), + _make_expected_facial_transformation_matrixes())) + def test_detect_async_calls( + self, image_path, model_name, expected_face_landmarks, + expected_face_blendshapes, expected_facial_transformation_matrixes): + test_image = _Image.create_from_file( + test_utils.get_test_data_path(image_path)) + observed_timestamp_ms = -1 + + def check_result(result: FaceLandmarkerResult, output_image: _Image, + timestamp_ms: int): + # Comparing results. + if expected_face_landmarks is not None: + self._expect_landmarks_correct(result.face_landmarks[0], + expected_face_landmarks) + if expected_face_blendshapes is not None: + self._expect_blendshapes_correct(result.face_blendshapes[0], + expected_face_blendshapes) + if expected_facial_transformation_matrixes is not None: + self._expect_facial_transformation_matrix_correct( + result.facial_transformation_matrixes, + expected_facial_transformation_matrixes) + self.assertTrue( + np.array_equal(output_image.numpy_view(), test_image.numpy_view())) + self.assertLess(observed_timestamp_ms, timestamp_ms) + self.observed_timestamp_ms = timestamp_ms + + model_path = test_utils.get_test_data_path(model_name) + options = _FaceLandmarkerOptions( + base_options=_BaseOptions(model_asset_path=model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + output_face_blendshapes=True if expected_face_blendshapes else False, + output_facial_transformation_matrixes=True + if expected_facial_transformation_matrixes else False, + result_callback=check_result) + with _FaceLandmarker.create_from_options(options) as landmarker: + for timestamp in range(0, 300, 30): + landmarker.detect_async(test_image, timestamp) + if __name__ == '__main__': absltest.main() diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 62b76056..e488bbb7 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -166,6 +166,7 @@ py_library( "//mediapipe/python:packet_creator", "//mediapipe/python:packet_getter", "//mediapipe/tasks/cc/vision/face_landmarker/proto:face_landmarker_graph_options_py_pb2", + "//mediapipe/tasks/cc/vision/face_geometry/proto:face_geometry_py_pb2", "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/components/containers:landmark", "//mediapipe/tasks/python/components/containers:matrix_data", diff --git a/mediapipe/tasks/python/vision/face_landmarker.py b/mediapipe/tasks/python/vision/face_landmarker.py index c109c646..a053d936 100644 --- a/mediapipe/tasks/python/vision/face_landmarker.py +++ b/mediapipe/tasks/python/vision/face_landmarker.py @@ -25,6 +25,8 @@ from mediapipe.python import packet_getter from mediapipe.python._framework_bindings import image as image_module from mediapipe.python._framework_bindings import packet as packet_module from mediapipe.tasks.cc.vision.face_landmarker.proto import face_landmarker_graph_options_pb2 +# TODO: Remove later. +from mediapipe.tasks.cc.vision.face_geometry.proto import face_geometry_pb2 from mediapipe.tasks.python.components.containers import category as category_module from mediapipe.tasks.python.components.containers import landmark as landmark_module from mediapipe.tasks.python.components.containers import matrix_data as matrix_data_module @@ -160,15 +162,22 @@ def _build_landmarker_result( category_name=face_blendshapes.label)) face_blendshapes_results.append(face_blendshapes_categories) + # Creates a dummy FaceGeometry packet to initialize the symbol database. + # TODO: Remove later. + face_geometry_in = face_geometry_pb2.FaceGeometry() + p = packet_creator.create_proto(face_geometry_in).at(100) + face_geometry_out = packet_getter.get_proto(p) + facial_transformation_matrixes_results = [] if _FACE_GEOMETRY_STREAM_NAME in output_packets: facial_transformation_matrixes_proto_list = packet_getter.get_proto_list( output_packets[_FACE_GEOMETRY_STREAM_NAME]) for proto in facial_transformation_matrixes_proto_list: - matrix_data = matrix_data_pb2.MatrixData() - matrix_data.MergeFrom(proto) - matrix = matrix_data_module.MatrixData.create_from_pb2(matrix_data) - facial_transformation_matrixes_results.append(matrix) + if proto.pose_transform_matrix: + matrix_data = matrix_data_pb2.MatrixData() + matrix_data.MergeFrom(proto.pose_transform_matrix) + matrix = matrix_data_module.MatrixData.create_from_pb2(matrix_data) + facial_transformation_matrixes_results.append(matrix) return FaceLandmarkerResult(face_landmarks_results, face_blendshapes_results, facial_transformation_matrixes_results) From 80dd764605d3ffb48edc30d70fe127a08394043e Mon Sep 17 00:00:00 2001 From: kinaryml Date: Wed, 15 Mar 2023 10:52:16 -0700 Subject: [PATCH 07/12] Removed dummy packet creation and preserved face_geometry protobuf import --- mediapipe/tasks/python/vision/face_landmarker.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/mediapipe/tasks/python/vision/face_landmarker.py b/mediapipe/tasks/python/vision/face_landmarker.py index a053d936..6862818c 100644 --- a/mediapipe/tasks/python/vision/face_landmarker.py +++ b/mediapipe/tasks/python/vision/face_landmarker.py @@ -25,7 +25,7 @@ from mediapipe.python import packet_getter from mediapipe.python._framework_bindings import image as image_module from mediapipe.python._framework_bindings import packet as packet_module from mediapipe.tasks.cc.vision.face_landmarker.proto import face_landmarker_graph_options_pb2 -# TODO: Remove later. +# TODO: Remove this later. from mediapipe.tasks.cc.vision.face_geometry.proto import face_geometry_pb2 from mediapipe.tasks.python.components.containers import category as category_module from mediapipe.tasks.python.components.containers import landmark as landmark_module @@ -162,12 +162,6 @@ def _build_landmarker_result( category_name=face_blendshapes.label)) face_blendshapes_results.append(face_blendshapes_categories) - # Creates a dummy FaceGeometry packet to initialize the symbol database. - # TODO: Remove later. - face_geometry_in = face_geometry_pb2.FaceGeometry() - p = packet_creator.create_proto(face_geometry_in).at(100) - face_geometry_out = packet_getter.get_proto(p) - facial_transformation_matrixes_results = [] if _FACE_GEOMETRY_STREAM_NAME in output_packets: facial_transformation_matrixes_proto_list = packet_getter.get_proto_list( From 9aea1be6f973675c495d14efeeae239760fcd98c Mon Sep 17 00:00:00 2001 From: kinaryml Date: Wed, 15 Mar 2023 23:51:12 -0700 Subject: [PATCH 08/12] Removed geometry pipeline calculator --- mediapipe/python/BUILD | 1 - 1 file changed, 1 deletion(-) diff --git a/mediapipe/python/BUILD b/mediapipe/python/BUILD index 6755f281..a5b52a53 100644 --- a/mediapipe/python/BUILD +++ b/mediapipe/python/BUILD @@ -37,7 +37,6 @@ pybind_extension( deps = [ ":builtin_calculators", ":builtin_task_graphs", - "//mediapipe/tasks/cc/vision/face_geometry/calculators:geometry_pipeline_calculator", "//mediapipe/python/pybind:calculator_graph", "//mediapipe/python/pybind:image", "//mediapipe/python/pybind:image_frame", From 2753c79fdeb92c26a707568901e8054fdcf0e240 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Thu, 16 Mar 2023 11:50:07 -0700 Subject: [PATCH 09/12] Removed MatrixData dataclass and used NumPy to represent Matrix --- .../tasks/python/components/containers/BUILD | 9 -- .../components/containers/matrix_data.py | 81 ------------ mediapipe/tasks/python/test/vision/BUILD | 1 - .../test/vision/face_landmarker_test.py | 120 +++++++++--------- mediapipe/tasks/python/vision/BUILD | 1 - .../tasks/python/vision/face_landmarker.py | 9 +- 6 files changed, 65 insertions(+), 156 deletions(-) delete mode 100644 mediapipe/tasks/python/components/containers/matrix_data.py diff --git a/mediapipe/tasks/python/components/containers/BUILD b/mediapipe/tasks/python/components/containers/BUILD index 07c31dc0..b84ab744 100644 --- a/mediapipe/tasks/python/components/containers/BUILD +++ b/mediapipe/tasks/python/components/containers/BUILD @@ -82,15 +82,6 @@ py_library( ], ) -py_library( - name = "matrix_data", - srcs = ["matrix_data.py"], - deps = [ - "//mediapipe/framework/formats:matrix_data_py_pb2", - "//mediapipe/tasks/python/core:optional_dependencies", - ], -) - py_library( name = "detections", srcs = ["detections.py"], diff --git a/mediapipe/tasks/python/components/containers/matrix_data.py b/mediapipe/tasks/python/components/containers/matrix_data.py deleted file mode 100644 index ded3a9b4..00000000 --- a/mediapipe/tasks/python/components/containers/matrix_data.py +++ /dev/null @@ -1,81 +0,0 @@ -# Copyright 2022 The MediaPipe Authors. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Matrix data data class.""" - -import dataclasses -import enum -from typing import Any, Optional - -import numpy as np -from mediapipe.framework.formats import matrix_data_pb2 -from mediapipe.tasks.python.core.optional_dependencies import doc_controls - -_MatrixDataProto = matrix_data_pb2.MatrixData - - -class Layout(enum.Enum): - COLUMN_MAJOR = 0 - ROW_MAJOR = 1 - - -@dataclasses.dataclass -class MatrixData: - """This stores the Matrix data. - - Here the data is stored in column-major order by default. - - Attributes: - rows: The number of rows in the matrix. - cols: The number of columns in the matrix. - data: The data stored in the matrix as a NumPy array. - layout: The order in which the data are stored. Defaults to COLUMN_MAJOR. - """ - - rows: int = None - cols: int = None - data: np.ndarray = None - layout: Optional[Layout] = Layout.COLUMN_MAJOR - - @doc_controls.do_not_generate_docs - def to_pb2(self) -> _MatrixDataProto: - """Generates a MatrixData protobuf object.""" - return _MatrixDataProto( - rows=self.rows, - cols=self.cols, - packed_data=self.data, - layout=self.layout.value) - - @classmethod - @doc_controls.do_not_generate_docs - def create_from_pb2(cls, pb2_obj: _MatrixDataProto) -> 'MatrixData': - """Creates a `MatrixData` object from the given protobuf object.""" - return MatrixData( - rows=pb2_obj.rows, - cols=pb2_obj.cols, - data=np.array(pb2_obj.packed_data), - layout=Layout(pb2_obj.layout)) - - def __eq__(self, other: Any) -> bool: - """Checks if this object is equal to the given object. - - Args: - other: The object to be compared with. - - Returns: - True if the objects are equal. - """ - if not isinstance(other, MatrixData): - return False - - return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index fcff54d8..978dc127 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -153,7 +153,6 @@ py_test( "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/components/containers:landmark", "//mediapipe/tasks/python/components/containers:rect", - "//mediapipe/tasks/python/components/containers:matrix_data", "//mediapipe/tasks/python/core:base_options", "//mediapipe/tasks/python/test:test_utils", "//mediapipe/tasks/python/vision:face_landmarker", diff --git a/mediapipe/tasks/python/test/vision/face_landmarker_test.py b/mediapipe/tasks/python/test/vision/face_landmarker_test.py index a6b6e02f..34d1e0b0 100644 --- a/mediapipe/tasks/python/test/vision/face_landmarker_test.py +++ b/mediapipe/tasks/python/test/vision/face_landmarker_test.py @@ -26,7 +26,6 @@ from mediapipe.framework.formats import classification_pb2 from mediapipe.python._framework_bindings import image as image_module from mediapipe.tasks.python.components.containers import category as category_module from mediapipe.tasks.python.components.containers import landmark as landmark_module -from mediapipe.tasks.python.components.containers import matrix_data as matrix_data_module from mediapipe.tasks.python.components.containers import rect as rect_module from mediapipe.tasks.python.core import base_options as base_options_module from mediapipe.tasks.python.test import test_utils @@ -39,7 +38,6 @@ _BaseOptions = base_options_module.BaseOptions _Category = category_module.Category _Rect = rect_module.Rect _Landmark = landmark_module.Landmark -_MatrixData = matrix_data_module.MatrixData _NormalizedLandmark = landmark_module.NormalizedLandmark _Image = image_module.Image _FaceLandmarker = face_landmarker.FaceLandmarker @@ -90,14 +88,12 @@ def _get_expected_face_blendshapes(file_path: str): def _make_expected_facial_transformation_matrixes(): - data = np.array([[0.9995292, -0.005092691, 0.030254554, -0.37340546], + matrix = np.array([[0.9995292, -0.005092691, 0.030254554, -0.37340546], [0.0072318087, 0.99744856, -0.07102106, 22.212194], [-0.029815676, 0.07120642, 0.9970159, -64.76358], [0, 0, 0, 1]]) - rows, cols = len(data), len(data[0]) facial_transformation_matrixes_results = [] - facial_transformation_matrix = _MatrixData(rows, cols, data.flatten()) - facial_transformation_matrixes_results.append(facial_transformation_matrix) + facial_transformation_matrixes_results.append(matrix) return facial_transformation_matrixes_results @@ -111,9 +107,9 @@ class FaceLandmarkerTest(parameterized.TestCase): def setUp(self): super().setUp() self.test_image = _Image.create_from_file( - test_utils.get_test_data_path(_PORTRAIT_IMAGE)) + test_utils.get_test_data_path(_PORTRAIT_IMAGE)) self.model_path = test_utils.get_test_data_path( - _FACE_LANDMARKER_BUNDLE_ASSET_FILE) + _FACE_LANDMARKER_BUNDLE_ASSET_FILE) def _expect_landmarks_correct(self, actual_landmarks, expected_landmarks): # Expects to have the same number of faces detected. @@ -145,11 +141,13 @@ class FaceLandmarkerTest(parameterized.TestCase): self.assertLen(actual_matrix_list, len(expected_matrix_list)) for i, rename_me in enumerate(actual_matrix_list): - self.assertEqual(rename_me.rows, expected_matrix_list[i].rows) - self.assertEqual(rename_me.cols, expected_matrix_list[i].cols) + self.assertEqual(rename_me.shape[0], + expected_matrix_list[i].shape[0]) + self.assertEqual(rename_me.shape[1], + expected_matrix_list[i].shape[1]) self.assertAlmostEqual( - rename_me.data.all(), - expected_matrix_list[i].data.all(), + rename_me.all(), + expected_matrix_list[i].all(), delta=_FACIAL_TRANSFORMATION_MATRIX_DIFF_MARGIN) def test_create_from_file_succeeds_with_valid_model_path(self): @@ -169,7 +167,7 @@ class FaceLandmarkerTest(parameterized.TestCase): with self.assertRaisesRegex( RuntimeError, 'Unable to open file at /path/to/invalid/model.tflite'): base_options = _BaseOptions( - model_asset_path='/path/to/invalid/model.tflite') + model_asset_path='/path/to/invalid/model.tflite') options = _FaceLandmarkerOptions(base_options=base_options) _FaceLandmarker.create_from_options(options) @@ -182,46 +180,46 @@ class FaceLandmarkerTest(parameterized.TestCase): self.assertIsInstance(landmarker, _FaceLandmarker) @parameterized.parameters( - (ModelFileType.FILE_NAME, _FACE_LANDMARKER_BUNDLE_ASSET_FILE, - _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), - (ModelFileType.FILE_CONTENT, _FACE_LANDMARKER_BUNDLE_ASSET_FILE, - _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), - (ModelFileType.FILE_NAME, - _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, - _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), - (ModelFileType.FILE_CONTENT, - _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, - _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), - (ModelFileType.FILE_NAME, - _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, - _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), - _get_expected_face_blendshapes( - _PORTRAIT_EXPECTED_BLENDSHAPES), None), - (ModelFileType.FILE_CONTENT, - _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, - _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), - _get_expected_face_blendshapes( - _PORTRAIT_EXPECTED_BLENDSHAPES), None), - (ModelFileType.FILE_NAME, - _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, - _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), - _get_expected_face_blendshapes( - _PORTRAIT_EXPECTED_BLENDSHAPES), - _make_expected_facial_transformation_matrixes()), - (ModelFileType.FILE_CONTENT, - _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, - _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), - _get_expected_face_blendshapes( - _PORTRAIT_EXPECTED_BLENDSHAPES), - _make_expected_facial_transformation_matrixes())) + (ModelFileType.FILE_NAME, _FACE_LANDMARKER_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), + (ModelFileType.FILE_CONTENT, _FACE_LANDMARKER_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), + (ModelFileType.FILE_NAME, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), + (ModelFileType.FILE_CONTENT, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), + (ModelFileType.FILE_NAME, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), None), + (ModelFileType.FILE_CONTENT, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), None), + (ModelFileType.FILE_NAME, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), + _make_expected_facial_transformation_matrixes()), + (ModelFileType.FILE_CONTENT, + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, + _get_expected_face_landmarks( + _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), + _get_expected_face_blendshapes( + _PORTRAIT_EXPECTED_BLENDSHAPES), + _make_expected_facial_transformation_matrixes())) def test_detect( self, model_file_type, model_name, expected_face_landmarks, expected_face_blendshapes, expected_facial_transformation_matrixes): @@ -238,10 +236,10 @@ class FaceLandmarkerTest(parameterized.TestCase): raise ValueError('model_file_type is invalid.') options = _FaceLandmarkerOptions( - base_options=base_options, - output_face_blendshapes=True if expected_face_blendshapes else False, - output_facial_transformation_matrixes=True - if expected_facial_transformation_matrixes else False) + base_options=base_options, + output_face_blendshapes=True if expected_face_blendshapes else False, + output_facial_transformation_matrixes=True + if expected_facial_transformation_matrixes else False) landmarker = _FaceLandmarker.create_from_options(options) # Performs face landmarks detection on the input. @@ -255,8 +253,8 @@ class FaceLandmarkerTest(parameterized.TestCase): expected_face_blendshapes) if expected_facial_transformation_matrixes is not None: self._expect_facial_transformation_matrix_correct( - detection_result.facial_transformation_matrixes, - expected_facial_transformation_matrixes) + detection_result.facial_transformation_matrixes, + expected_facial_transformation_matrixes) # Closes the face landmarker explicitly when the face landmarker is not used # in a context. @@ -342,7 +340,7 @@ class FaceLandmarkerTest(parameterized.TestCase): def test_detect_succeeds_with_num_faces(self): # Creates face landmarker. model_path = test_utils.get_test_data_path( - _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE) + _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE) base_options = _BaseOptions(model_asset_path=model_path) options = _FaceLandmarkerOptions(base_options=base_options, num_faces=1, output_face_blendshapes=True) @@ -436,7 +434,7 @@ class FaceLandmarkerTest(parameterized.TestCase): @parameterized.parameters( (_FACE_LANDMARKER_BUNDLE_ASSET_FILE, _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), + _PORTRAIT_EXPECTED_FACE_LANDMARKS), None, None), (_FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, _get_expected_face_landmarks( _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), None, None), diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 83763c1a..ae02e277 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -189,7 +189,6 @@ py_library( "//mediapipe/tasks/cc/vision/face_geometry/proto:face_geometry_py_pb2", "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/components/containers:landmark", - "//mediapipe/tasks/python/components/containers:matrix_data", "//mediapipe/tasks/python/core:base_options", "//mediapipe/tasks/python/core:optional_dependencies", "//mediapipe/tasks/python/core:task_info", diff --git a/mediapipe/tasks/python/vision/face_landmarker.py b/mediapipe/tasks/python/vision/face_landmarker.py index 6862818c..7d53b820 100644 --- a/mediapipe/tasks/python/vision/face_landmarker.py +++ b/mediapipe/tasks/python/vision/face_landmarker.py @@ -17,6 +17,7 @@ import dataclasses import enum from typing import Callable, Mapping, Optional, List +import numpy as np from mediapipe.framework.formats import classification_pb2 from mediapipe.framework.formats import landmark_pb2 from mediapipe.framework.formats import matrix_data_pb2 @@ -29,7 +30,6 @@ from mediapipe.tasks.cc.vision.face_landmarker.proto import face_landmarker_grap from mediapipe.tasks.cc.vision.face_geometry.proto import face_geometry_pb2 from mediapipe.tasks.python.components.containers import category as category_module from mediapipe.tasks.python.components.containers import landmark as landmark_module -from mediapipe.tasks.python.components.containers import matrix_data as matrix_data_module from mediapipe.tasks.python.core import base_options as base_options_module from mediapipe.tasks.python.core import task_info as task_info_module from mediapipe.tasks.python.core.optional_dependencies import doc_controls @@ -39,6 +39,7 @@ from mediapipe.tasks.python.vision.core import vision_task_running_mode as runni _BaseOptions = base_options_module.BaseOptions _FaceLandmarkerGraphOptionsProto = face_landmarker_graph_options_pb2.FaceLandmarkerGraphOptions +_LayoutEnum = matrix_data_pb2.MatrixData.Layout _RunningMode = running_mode_module.VisionTaskRunningMode _ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _TaskInfo = task_info_module.TaskInfo @@ -126,7 +127,7 @@ class FaceLandmarkerResult: face_landmarks: List[List[landmark_module.NormalizedLandmark]] face_blendshapes: List[List[category_module.Category]] - facial_transformation_matrixes: List[matrix_data_module.MatrixData] + facial_transformation_matrixes: List[np.ndarray] def _build_landmarker_result( @@ -170,7 +171,9 @@ def _build_landmarker_result( if proto.pose_transform_matrix: matrix_data = matrix_data_pb2.MatrixData() matrix_data.MergeFrom(proto.pose_transform_matrix) - matrix = matrix_data_module.MatrixData.create_from_pb2(matrix_data) + order = 'C' if matrix_data.layout == _LayoutEnum.ROW_MAJOR else 'F' + data = np.array(matrix_data.packed_data, order=order) + matrix = data.reshape((matrix_data.rows, matrix_data.cols)) facial_transformation_matrixes_results.append(matrix) return FaceLandmarkerResult(face_landmarks_results, face_blendshapes_results, From b36b0bb3e84298c66d5d0578b5965c6b6607bfc3 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Thu, 16 Mar 2023 12:51:19 -0700 Subject: [PATCH 10/12] Updated API and tests --- .../test/vision/face_landmarker_test.py | 28 ++++++------------- .../tasks/python/vision/face_landmarker.py | 6 ++-- 2 files changed, 12 insertions(+), 22 deletions(-) diff --git a/mediapipe/tasks/python/test/vision/face_landmarker_test.py b/mediapipe/tasks/python/test/vision/face_landmarker_test.py index 34d1e0b0..0a1d8705 100644 --- a/mediapipe/tasks/python/test/vision/face_landmarker_test.py +++ b/mediapipe/tasks/python/test/vision/face_landmarker_test.py @@ -89,9 +89,9 @@ def _get_expected_face_blendshapes(file_path: str): def _make_expected_facial_transformation_matrixes(): matrix = np.array([[0.9995292, -0.005092691, 0.030254554, -0.37340546], - [0.0072318087, 0.99744856, -0.07102106, 22.212194], - [-0.029815676, 0.07120642, 0.9970159, -64.76358], - [0, 0, 0, 1]]) + [0.0072318087, 0.99744856, -0.07102106, 22.212194], + [-0.029815676, 0.07120642, 0.9970159, -64.76358], + [0, 0, 0, 1]]) facial_transformation_matrixes_results = [] facial_transformation_matrixes_results.append(matrix) return facial_transformation_matrixes_results @@ -145,10 +145,10 @@ class FaceLandmarkerTest(parameterized.TestCase): expected_matrix_list[i].shape[0]) self.assertEqual(rename_me.shape[1], expected_matrix_list[i].shape[1]) - self.assertAlmostEqual( - rename_me.all(), - expected_matrix_list[i].all(), - delta=_FACIAL_TRANSFORMATION_MATRIX_DIFF_MARGIN) + self.assertSequenceAlmostEqual( + rename_me.flatten(), + expected_matrix_list[i].flatten(), + delta=_FACIAL_TRANSFORMATION_MATRIX_DIFF_MARGIN) def test_create_from_file_succeeds_with_valid_model_path(self): # Creates with default option and valid model file successfully. @@ -441,12 +441,7 @@ class FaceLandmarkerTest(parameterized.TestCase): (_FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, _get_expected_face_landmarks( _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), - _get_expected_face_blendshapes(_PORTRAIT_EXPECTED_BLENDSHAPES), None), - (_FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, - _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), - _get_expected_face_blendshapes(_PORTRAIT_EXPECTED_BLENDSHAPES), - _make_expected_facial_transformation_matrixes())) + _get_expected_face_blendshapes(_PORTRAIT_EXPECTED_BLENDSHAPES), None)) def test_detect_for_video( self, model_name, expected_face_landmarks, expected_face_blendshapes, expected_facial_transformation_matrixes): @@ -519,12 +514,7 @@ class FaceLandmarkerTest(parameterized.TestCase): (_PORTRAIT_IMAGE, _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, _get_expected_face_landmarks( _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), - _get_expected_face_blendshapes(_PORTRAIT_EXPECTED_BLENDSHAPES), None), - (_PORTRAIT_IMAGE, _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, - _get_expected_face_landmarks( - _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), - _get_expected_face_blendshapes(_PORTRAIT_EXPECTED_BLENDSHAPES), - _make_expected_facial_transformation_matrixes())) + _get_expected_face_blendshapes(_PORTRAIT_EXPECTED_BLENDSHAPES), None)) def test_detect_async_calls( self, image_path, model_name, expected_face_landmarks, expected_face_blendshapes, expected_facial_transformation_matrixes): diff --git a/mediapipe/tasks/python/vision/face_landmarker.py b/mediapipe/tasks/python/vision/face_landmarker.py index 7d53b820..b8854d29 100644 --- a/mediapipe/tasks/python/vision/face_landmarker.py +++ b/mediapipe/tasks/python/vision/face_landmarker.py @@ -171,9 +171,9 @@ def _build_landmarker_result( if proto.pose_transform_matrix: matrix_data = matrix_data_pb2.MatrixData() matrix_data.MergeFrom(proto.pose_transform_matrix) - order = 'C' if matrix_data.layout == _LayoutEnum.ROW_MAJOR else 'F' - data = np.array(matrix_data.packed_data, order=order) - matrix = data.reshape((matrix_data.rows, matrix_data.cols)) + matrix = np.array(matrix_data.packed_data) + matrix = matrix.reshape((matrix_data.rows, matrix_data.cols)) + matrix = matrix if matrix_data.layout == _LayoutEnum.ROW_MAJOR else matrix.T facial_transformation_matrixes_results.append(matrix) return FaceLandmarkerResult(face_landmarks_results, face_blendshapes_results, From 94dba82284710fa567002c1038fae95622fa92c1 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Thu, 16 Mar 2023 12:54:38 -0700 Subject: [PATCH 11/12] Renamed a test method to use the plural form --- .../tasks/python/test/vision/face_landmarker_test.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/mediapipe/tasks/python/test/vision/face_landmarker_test.py b/mediapipe/tasks/python/test/vision/face_landmarker_test.py index 0a1d8705..de6dc82a 100644 --- a/mediapipe/tasks/python/test/vision/face_landmarker_test.py +++ b/mediapipe/tasks/python/test/vision/face_landmarker_test.py @@ -136,8 +136,8 @@ class FaceLandmarkerTest(parameterized.TestCase): expected_blendshapes[i].score, delta=_BLENDSHAPES_DIFF_MARGIN) - def _expect_facial_transformation_matrix_correct(self, actual_matrix_list, - expected_matrix_list): + def _expect_facial_transformation_matrixes_correct(self, actual_matrix_list, + expected_matrix_list): self.assertLen(actual_matrix_list, len(expected_matrix_list)) for i, rename_me in enumerate(actual_matrix_list): @@ -252,7 +252,7 @@ class FaceLandmarkerTest(parameterized.TestCase): self._expect_blendshapes_correct(detection_result.face_blendshapes[0], expected_face_blendshapes) if expected_facial_transformation_matrixes is not None: - self._expect_facial_transformation_matrix_correct( + self._expect_facial_transformation_matrixes_correct( detection_result.facial_transformation_matrixes, expected_facial_transformation_matrixes) @@ -333,7 +333,7 @@ class FaceLandmarkerTest(parameterized.TestCase): self._expect_blendshapes_correct(detection_result.face_blendshapes[0], expected_face_blendshapes) if expected_facial_transformation_matrixes is not None: - self._expect_facial_transformation_matrix_correct( + self._expect_facial_transformation_matrixes_correct( detection_result.facial_transformation_matrixes, expected_facial_transformation_matrixes) @@ -469,7 +469,7 @@ class FaceLandmarkerTest(parameterized.TestCase): self._expect_blendshapes_correct(detection_result.face_blendshapes[0], expected_face_blendshapes) if expected_facial_transformation_matrixes is not None: - self._expect_facial_transformation_matrix_correct( + self._expect_facial_transformation_matrixes_correct( detection_result.facial_transformation_matrixes, expected_facial_transformation_matrixes) @@ -532,7 +532,7 @@ class FaceLandmarkerTest(parameterized.TestCase): self._expect_blendshapes_correct(result.face_blendshapes[0], expected_face_blendshapes) if expected_facial_transformation_matrixes is not None: - self._expect_facial_transformation_matrix_correct( + self._expect_facial_transformation_matrixes_correct( result.facial_transformation_matrixes, expected_facial_transformation_matrixes) self.assertTrue( From 1ba285d9164036e60031ed167d69565fd8cf8446 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Thu, 16 Mar 2023 15:10:39 -0700 Subject: [PATCH 12/12] Updated a method name in face_landmarker_test.py --- .../tasks/python/test/vision/face_landmarker_test.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/mediapipe/tasks/python/test/vision/face_landmarker_test.py b/mediapipe/tasks/python/test/vision/face_landmarker_test.py index de6dc82a..d156da04 100644 --- a/mediapipe/tasks/python/test/vision/face_landmarker_test.py +++ b/mediapipe/tasks/python/test/vision/face_landmarker_test.py @@ -87,7 +87,7 @@ def _get_expected_face_blendshapes(file_path: str): return face_blendshapes_categories -def _make_expected_facial_transformation_matrixes(): +def _get_expected_facial_transformation_matrixes(): matrix = np.array([[0.9995292, -0.005092691, 0.030254554, -0.37340546], [0.0072318087, 0.99744856, -0.07102106, 22.212194], [-0.029815676, 0.07120642, 0.9970159, -64.76358], @@ -212,14 +212,14 @@ class FaceLandmarkerTest(parameterized.TestCase): _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), _get_expected_face_blendshapes( _PORTRAIT_EXPECTED_BLENDSHAPES), - _make_expected_facial_transformation_matrixes()), + _get_expected_facial_transformation_matrixes()), (ModelFileType.FILE_CONTENT, _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, _get_expected_face_landmarks( _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), _get_expected_face_blendshapes( _PORTRAIT_EXPECTED_BLENDSHAPES), - _make_expected_facial_transformation_matrixes())) + _get_expected_facial_transformation_matrixes())) def test_detect( self, model_file_type, model_name, expected_face_landmarks, expected_face_blendshapes, expected_facial_transformation_matrixes): @@ -293,14 +293,14 @@ class FaceLandmarkerTest(parameterized.TestCase): _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), _get_expected_face_blendshapes( _PORTRAIT_EXPECTED_BLENDSHAPES), - _make_expected_facial_transformation_matrixes()), + _get_expected_facial_transformation_matrixes()), (ModelFileType.FILE_CONTENT, _FACE_LANDMARKER_WITH_BLENDSHAPES_BUNDLE_ASSET_FILE, _get_expected_face_landmarks( _PORTRAIT_EXPECTED_FACE_LANDMARKS_WITH_ATTENTION), _get_expected_face_blendshapes( _PORTRAIT_EXPECTED_BLENDSHAPES), - _make_expected_facial_transformation_matrixes())) + _get_expected_facial_transformation_matrixes())) def test_detect_in_context( self, model_file_type, model_name, expected_face_landmarks, expected_face_blendshapes, expected_facial_transformation_matrixes):