From 9a1a9d4c136685962afc0a6bc81e4b458d57d2e0 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Mon, 24 Oct 2022 06:08:27 -0700 Subject: [PATCH 01/16] Added files needed for the GestureRecognizer API implementation --- mediapipe/python/BUILD | 1 + .../tasks/python/components/containers/BUILD | 37 ++ .../components/containers/classification.py | 128 ++++++ .../python/components/containers/gesture.py | 138 ++++++ .../python/components/containers/landmark.py | 250 ++++++++++ .../python/components/containers/rect.py | 141 ++++++ .../tasks/python/components/processors/BUILD | 28 ++ .../processors/classifier_options.py | 92 ++++ mediapipe/tasks/python/test/vision/BUILD | 19 + .../test/vision/gesture_recognizer_test.py | 91 ++++ mediapipe/tasks/python/vision/BUILD | 27 ++ .../tasks/python/vision/gesture_recognizer.py | 434 ++++++++++++++++++ 12 files changed, 1386 insertions(+) create mode 100644 mediapipe/tasks/python/components/containers/classification.py create mode 100644 mediapipe/tasks/python/components/containers/gesture.py create mode 100644 mediapipe/tasks/python/components/containers/landmark.py create mode 100644 mediapipe/tasks/python/components/containers/rect.py create mode 100644 mediapipe/tasks/python/components/processors/BUILD create mode 100644 mediapipe/tasks/python/components/processors/classifier_options.py create mode 100644 mediapipe/tasks/python/test/vision/gesture_recognizer_test.py create mode 100644 mediapipe/tasks/python/vision/gesture_recognizer.py diff --git a/mediapipe/python/BUILD b/mediapipe/python/BUILD index 2911e2fd..50a1f579 100644 --- a/mediapipe/python/BUILD +++ b/mediapipe/python/BUILD @@ -88,6 +88,7 @@ cc_library( name = "builtin_task_graphs", deps = [ "//mediapipe/tasks/cc/vision/object_detector:object_detector_graph", + "//mediapipe/tasks/cc/vision/gesture_recognizer:gesture_recognizer_graph", ], ) diff --git a/mediapipe/tasks/python/components/containers/BUILD b/mediapipe/tasks/python/components/containers/BUILD index fd25401f..325dff5f 100644 --- a/mediapipe/tasks/python/components/containers/BUILD +++ b/mediapipe/tasks/python/components/containers/BUILD @@ -27,6 +27,43 @@ py_library( ], ) +py_library( + name = "rect", + srcs = ["rect.py"], + deps = [ + "//mediapipe/framework/formats:rect_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) + +py_library( + name = "classification", + srcs = ["classification.py"], + deps = [ + "//mediapipe/framework/formats:classification_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) + +py_library( + name = "landmark", + srcs = ["landmark.py"], + deps = [ + "//mediapipe/framework/formats:landmark_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) + +py_library( + name = "gesture", + srcs = ["gesture.py"], + deps = [ + ":classification", + ":landmark", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) + py_library( name = "category", srcs = ["category.py"], diff --git a/mediapipe/tasks/python/components/containers/classification.py b/mediapipe/tasks/python/components/containers/classification.py new file mode 100644 index 00000000..157c3452 --- /dev/null +++ b/mediapipe/tasks/python/components/containers/classification.py @@ -0,0 +1,128 @@ +# 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. +"""Classification data class.""" + +import dataclasses +from typing import Any, List + +from mediapipe.framework.formats import classification_pb2 +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_ClassificationProto = classification_pb2.Classification +_ClassificationListProto = classification_pb2.ClassificationList +_ClassificationListCollectionProto = classification_pb2.ClassificationListCollection + + +@dataclasses.dataclass +class Classification: + """A classification. + + Attributes: + index: The index of the class in the corresponding label map. + score: The probability score for this class. + label_name: Label or name of the class. + display_name: Optional human-readable string for display purposes. + """ + + index: int + score: float + label_name: str + display_name: str + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _ClassificationProto: + """Generates a Classification protobuf object.""" + return _ClassificationProto( + index=self.index, + score=self.score, + label_name=self.label_name, + display_name=self.display_name) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _ClassificationProto) -> 'Classification': + """Creates a `Classification` object from the given protobuf object.""" + return Classification( + index=pb2_obj.index, + score=pb2_obj.score, + label_name=pb2_obj.label_name, + display_name=pb2_obj.display_name) + + 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, Classification): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class ClassificationList: + """Represents the classifications for a given classifier. + Attributes: + classification : A list of `Classification` objects. + tensor_index: Optional index of the tensor that produced these + classifications. + tensor_name: Optional name of the tensor that produced these + classifications tensor metadata name. + """ + + classifications: List[Classification] + tensor_index: int + tensor_name: str + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _ClassificationListProto: + """Generates a ClassificationList protobuf object.""" + return _ClassificationListProto( + classification=[ + classification.to_pb2() + for classification in self.classifications + ], + tensor_index=self.tensor_index, + tensor_name=self.tensor_name) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, + pb2_obj: _ClassificationListProto + ) -> 'ClassificationList': + """Creates a `ClassificationList` object from the given protobuf object.""" + return ClassificationList( + classifications=[ + Classification.create_from_pb2(classification) + for classification in pb2_obj.classification + ], + tensor_index=pb2_obj.tensor_index, + tensor_name=pb2_obj.tensor_name) + + 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, ClassificationList): + return False + + return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/components/containers/gesture.py b/mediapipe/tasks/python/components/containers/gesture.py new file mode 100644 index 00000000..f314d18b --- /dev/null +++ b/mediapipe/tasks/python/components/containers/gesture.py @@ -0,0 +1,138 @@ +# 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. +"""Gesture data class.""" + +import dataclasses +from typing import Any, List + +from mediapipe.tasks.python.components.containers import classification +from mediapipe.tasks.python.components.containers import landmark +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + + +@dataclasses.dataclass +class GestureRecognitionResult: + """ The gesture recognition result from GestureRecognizer, where each vector + element represents a single hand detected in the image. + + Attributes: + gestures: Recognized hand gestures with sorted order such that the + winning label is the first item in the list. + handedness: Classification of handedness. + hand_landmarks: Detected hand landmarks in normalized image coordinates. + hand_world_landmarks: Detected hand landmarks in world coordinates. + """ + + gestures: List[classification.ClassificationList] + handedness: List[classification.ClassificationList] + hand_landmarks: List[landmark.NormalizedLandmarkList] + hand_world_landmarks: List[landmark.LandmarkList] + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _DetectionProto: + """Generates a Detection protobuf object.""" + labels = [] + label_ids = [] + scores = [] + display_names = [] + for category in self.categories: + scores.append(category.score) + if category.index: + label_ids.append(category.index) + if category.category_name: + labels.append(category.category_name) + if category.display_name: + display_names.append(category.display_name) + return _DetectionProto( + label=labels, + label_id=label_ids, + score=scores, + display_name=display_names, + location_data=_LocationDataProto( + format=_LocationDataProto.Format.BOUNDING_BOX, + bounding_box=self.bounding_box.to_pb2())) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _DetectionProto) -> 'Detection': + """Creates a `Detection` object from the given protobuf object.""" + categories = [] + for idx, score in enumerate(pb2_obj.score): + categories.append( + category_module.Category( + score=score, + index=pb2_obj.label_id[idx] + if idx < len(pb2_obj.label_id) else None, + category_name=pb2_obj.label[idx] + if idx < len(pb2_obj.label) else None, + display_name=pb2_obj.display_name[idx] + if idx < len(pb2_obj.display_name) else None)) + + return Detection( + bounding_box=bounding_box_module.BoundingBox.create_from_pb2( + pb2_obj.location_data.bounding_box), + categories=categories) + + 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, Detection): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class DetectionResult: + """Represents the list of detected objects. + + Attributes: + detections: A list of `Detection` objects. + """ + + detections: List[Detection] + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _DetectionListProto: + """Generates a DetectionList protobuf object.""" + return _DetectionListProto( + detection=[detection.to_pb2() for detection in self.detections]) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _DetectionListProto) -> 'DetectionResult': + """Creates a `DetectionResult` object from the given protobuf object.""" + return DetectionResult(detections=[ + Detection.create_from_pb2(detection) for detection in pb2_obj.detection + ]) + + 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, DetectionResult): + return False + + return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/components/containers/landmark.py b/mediapipe/tasks/python/components/containers/landmark.py new file mode 100644 index 00000000..a86c17f2 --- /dev/null +++ b/mediapipe/tasks/python/components/containers/landmark.py @@ -0,0 +1,250 @@ +# 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. +"""Landmark data class.""" + +import dataclasses +from typing import Any, Optional, List + +from mediapipe.framework.formats import landmark_pb2 +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_LandmarkProto = landmark_pb2.Landmark +_LandmarkListProto = landmark_pb2.LandmarkList +_NormalizedLandmarkProto = landmark_pb2.NormalizedLandmark +_NormalizedLandmarkListProto = landmark_pb2.NormalizedLandmarkList + + +@dataclasses.dataclass +class Landmark: + """A landmark that can have 1 to 3 dimensions. + + Use x for 1D points, (x, y) for 2D points and (x, y, z) for 3D points. + + Attributes: + x: The x coordinate of the 3D point. + y: The y coordinate of the 3D point. + z: The z coordinate of the 3D point. + visibility: Landmark visibility. Should stay unset if not supported. + Float score of whether landmark is visible or occluded by other objects. + Landmark considered as invisible also if it is not present on the screen + (out of scene bounds). Depending on the model, visibility value is either + a sigmoid or an argument of sigmoid. + presence: Landmark presence. Should stay unset if not supported. + Float score of whether landmark is present on the scene (located within + scene bounds). Depending on the model, presence value is either a result + of sigmoid or an argument of sigmoid function to get landmark presence + probability. + """ + + x: Optional[float] = None + y: Optional[float] = None + z: Optional[float] = None + visibility: Optional[float] = None + presence: Optional[float] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _LandmarkProto: + """Generates a Landmark protobuf object.""" + return _LandmarkProto( + x=self.x, + y=self.y, + z=self.z, + visibility=self.visibility, + presence=self.presence) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _LandmarkProto) -> 'Landmark': + """Creates a `Landmark` object from the given protobuf object.""" + return Landmark( + x=pb2_obj.x, + y=pb2_obj.y, + z=pb2_obj.z, + visibility=pb2_obj.visibility, + presence=pb2_obj.presence) + + 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, Landmark): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class LandmarkList: + """Represents the list of landmarks. + + Attributes: + landmarks : A list of `Landmark` objects. + """ + + landmarks: List[Landmark] + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _LandmarkListProto: + """Generates a LandmarkList protobuf object.""" + return _LandmarkListProto( + landmark=[ + landmark.to_pb2() + for landmark in self.landmarks + ] + ) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, + pb2_obj: _LandmarkListProto + ) -> 'LandmarkList': + """Creates a `LandmarkList` object from the given protobuf object.""" + return LandmarkList( + landmarks=[ + Landmark.create_from_pb2(landmark) + for landmark in pb2_obj.landmark + ] + ) + + 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, LandmarkList): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class NormalizedLandmark: + """A normalized version of above Landmark proto. + + All coordinates should be within [0, 1]. + + Attributes: + x: The normalized x coordinate of the 3D point. + y: The normalized y coordinate of the 3D point. + z: The normalized z coordinate of the 3D point. + visibility: Landmark visibility. Should stay unset if not supported. + Float score of whether landmark is visible or occluded by other objects. + Landmark considered as invisible also if it is not present on the screen + (out of scene bounds). Depending on the model, visibility value is either + a sigmoid or an argument of sigmoid. + presence: Landmark presence. Should stay unset if not supported. + Float score of whether landmark is present on the scene (located within + scene bounds). Depending on the model, presence value is either a result + of sigmoid or an argument of sigmoid function to get landmark presence + probability. + """ + + x: Optional[float] = None + y: Optional[float] = None + z: Optional[float] = None + visibility: Optional[float] = None + presence: Optional[float] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _NormalizedLandmarkProto: + """Generates a NormalizedLandmark protobuf object.""" + return _NormalizedLandmarkProto( + x=self.x, + y=self.y, + z=self.z, + visibility=self.visibility, + presence=self.presence) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, + pb2_obj: _NormalizedLandmarkProto + ) -> 'NormalizedLandmark': + """Creates a `NormalizedLandmark` object from the given protobuf object.""" + return NormalizedLandmark( + x=pb2_obj.x, + y=pb2_obj.y, + z=pb2_obj.z, + visibility=pb2_obj.visibility, + presence=pb2_obj.presence) + + 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, NormalizedLandmark): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class NormalizedLandmarkList: + """Represents the list of normalized landmarks. + + Attributes: + landmarks : A list of `Landmark` objects. + """ + + landmarks: List[NormalizedLandmark] + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _NormalizedLandmarkListProto: + """Generates a NormalizedLandmarkList protobuf object.""" + return _NormalizedLandmarkListProto( + landmark=[ + landmark.to_pb2() + for landmark in self.landmarks + ] + ) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, + pb2_obj: _NormalizedLandmarkListProto + ) -> 'NormalizedLandmarkList': + """Creates a `NormalizedLandmarkList` object from the given protobuf object.""" + return NormalizedLandmarkList( + landmarks=[ + NormalizedLandmark.create_from_pb2(landmark) + for landmark in pb2_obj.landmark + ] + ) + + 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, NormalizedLandmarkList): + return False + + return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/components/containers/rect.py b/mediapipe/tasks/python/components/containers/rect.py new file mode 100644 index 00000000..aadb404d --- /dev/null +++ b/mediapipe/tasks/python/components/containers/rect.py @@ -0,0 +1,141 @@ +# 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. +"""Rect data class.""" + +import dataclasses +from typing import Any, Optional + +from mediapipe.framework.formats import rect_pb2 +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_RectProto = rect_pb2.Rect +_NormalizedRectProto = rect_pb2.NormalizedRect + + +@dataclasses.dataclass +class Rect: + """A rectangle with rotation in image coordinates. + + Attributes: + x_center : The X coordinate of the top-left corner, in pixels. + y_center : The Y coordinate of the top-left corner, in pixels. + width: The width of the rectangle, in pixels. + height: The height of the rectangle, in pixels. + rotation: Rotation angle is clockwise in radians. + rect_id: Optional unique id to help associate different rectangles to each + other. + """ + + x_center: int + y_center: int + width: int + height: int + rotation: Optional[float] = 0.0 + rect_id: Optional[int] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _RectProto: + """Generates a Rect protobuf object.""" + return _RectProto( + x_center=self.x_center, + y_center=self.y_center, + width=self.width, + height=self.height, + ) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _RectProto) -> 'Rect': + """Creates a `Rect` object from the given protobuf object.""" + return Rect( + x_center=pb2_obj.x_center, + y_center=pb2_obj.y_center, + width=pb2_obj.width, + height=pb2_obj.height) + + 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, Rect): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class NormalizedRect: + """A rectangle with rotation in normalized coordinates. The values of box + center location and size are within [0, 1]. + + Attributes: + x_center : The X normalized coordinate of the top-left corner. + y_center : The Y normalized coordinate of the top-left corner. + width: The width of the rectangle. + height: The height of the rectangle. + rotation: Rotation angle is clockwise in radians. + rect_id: Optional unique id to help associate different rectangles to each + other. + """ + + x_center: float + y_center: float + width: float + height: float + rotation: Optional[float] = 0.0 + rect_id: Optional[int] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _NormalizedRectProto: + """Generates a NormalizedRect protobuf object.""" + return _NormalizedRectProto( + x_center=self.x_center, + y_center=self.y_center, + width=self.width, + height=self.height, + rotation=self.rotation, + rect_id=self.rect_id + ) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _NormalizedRectProto) -> 'NormalizedRect': + """Creates a `NormalizedRect` object from the given protobuf object.""" + return NormalizedRect( + x_center=pb2_obj.x_center, + y_center=pb2_obj.y_center, + width=pb2_obj.width, + height=pb2_obj.height, + rotation=pb2_obj.rotation, + rect_id=pb2_obj.rect_id + ) + + 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, NormalizedRect): + return False + + return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/components/processors/BUILD b/mediapipe/tasks/python/components/processors/BUILD new file mode 100644 index 00000000..814e15d1 --- /dev/null +++ b/mediapipe/tasks/python/components/processors/BUILD @@ -0,0 +1,28 @@ +# 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. + +# Placeholder for internal Python strict library compatibility macro. + +package(default_visibility = ["//mediapipe/tasks:internal"]) + +licenses(["notice"]) + +py_library( + name = "classifier_options", + srcs = ["classifier_options.py"], + deps = [ + "//mediapipe/tasks/cc/components/processors/proto:classifier_options_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) diff --git a/mediapipe/tasks/python/components/processors/classifier_options.py b/mediapipe/tasks/python/components/processors/classifier_options.py new file mode 100644 index 00000000..b4597e57 --- /dev/null +++ b/mediapipe/tasks/python/components/processors/classifier_options.py @@ -0,0 +1,92 @@ +# Copyright 2022 The TensorFlow 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. +"""Classifier options data class.""" + +import dataclasses +from typing import Any, List, Optional + +from mediapipe.tasks.cc.components.processors.proto import classifier_options_pb2 +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_ClassifierOptionsProto = classifier_options_pb2.ClassifierOptions + + +@dataclasses.dataclass +class ClassifierOptions: + """Options for classification processor. + + Attributes: + display_names_locale: The locale to use for display names specified through + the TFLite Model Metadata. + max_results: The maximum number of top-scored classification results to + return. + score_threshold: Overrides the ones provided in the model metadata. Results + below this value are rejected. + category_allowlist: Allowlist of category names. If non-empty, detection + results whose category name is not in this set will be filtered out. + Duplicate or unknown category names are ignored. Mutually exclusive with + `category_denylist`. + category_denylist: Denylist of category names. If non-empty, detection + results whose category name is in this set will be filtered out. Duplicate + or unknown category names are ignored. Mutually exclusive with + `category_allowlist`. + """ + + display_names_locale: Optional[str] = None + max_results: Optional[int] = None + score_threshold: Optional[float] = None + category_allowlist: Optional[List[str]] = None + category_denylist: Optional[List[str]] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _ClassifierOptionsProto: + """Generates a ClassifierOptions protobuf object.""" + return _ClassifierOptionsProto( + score_threshold=self.score_threshold, + category_allowlist=self.category_allowlist, + category_denylist=self.category_denylist, + display_names_locale=self.display_names_locale, + max_results=self.max_results) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, + pb2_obj: _ClassifierOptionsProto + ) -> 'ClassifierOptions': + """Creates a `ClassifierOptions` object from the given protobuf object.""" + return ClassifierOptions( + score_threshold=pb2_obj.score_threshold, + category_allowlist=[ + str(name) for name in pb2_obj.class_name_allowlist + ], + category_denylist=[ + str(name) for name in pb2_obj.class_name_denylist + ], + display_names_locale=pb2_obj.display_names_locale, + max_results=pb2_obj.max_results) + + 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, ClassifierOptions): + 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 290b665e..0dd83edc 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -36,3 +36,22 @@ py_test( "//mediapipe/tasks/python/vision/core:vision_task_running_mode", ], ) + +py_test( + name = "gesture_recognizer_test", + srcs = ["gesture_recognizer_test.py"], + data = [ + "//mediapipe/tasks/testdata/vision:test_images", + "//mediapipe/tasks/testdata/vision:test_models", + ], + deps = [ + "//mediapipe/python:_framework_bindings", + "//mediapipe/tasks/python/components/containers:classification", + "//mediapipe/tasks/python/components/containers:landmark", + "//mediapipe/tasks/python/components/containers:rect", + "//mediapipe/tasks/python/core:base_options", + "//mediapipe/tasks/python/test:test_utils", + "//mediapipe/tasks/python/vision:gesture_recognizer", + "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + ], +) diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py new file mode 100644 index 00000000..288cfd1f --- /dev/null +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -0,0 +1,91 @@ +# 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 gesture recognizer.""" + +import enum + +from absl.testing import absltest +from absl.testing import parameterized + +from mediapipe.python._framework_bindings import image as image_module +from mediapipe.tasks.python.components.containers import rect as rect_module +from mediapipe.tasks.python.components.containers import classification as classification_module +from mediapipe.tasks.python.components.containers import landmark as landmark_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 gesture_recognizer +from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module + +_BaseOptions = base_options_module.BaseOptions +_NormalizedRect = rect_module.NormalizedRect +_ClassificationList = classification_module.ClassificationList +_LandmarkList = landmark_module.LandmarkList +_NormalizedLandmarkList = landmark_module.NormalizedLandmarkList +_Image = image_module.Image +_GestureRecognizer = gesture_recognizer.GestureRecognizer +_GestureRecognizerOptions = gesture_recognizer.GestureRecognizerOptions +_GestureRecognitionResult = gesture_recognizer.GestureRecognitionResult +_RUNNING_MODE = running_mode_module.VisionTaskRunningMode + +_GESTURE_RECOGNIZER_MODEL_FILE = 'gesture_recognizer.task' +_IMAGE_FILE = 'right_hands.jpg' +_EXPECTED_DETECTION_RESULT = _GestureRecognitionResult([], [], [], []) + + +class ModelFileType(enum.Enum): + FILE_CONTENT = 1 + FILE_NAME = 2 + + +class GestureRecognizerTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self.test_image = _Image.create_from_file( + test_utils.get_test_data_path(_IMAGE_FILE)) + self.gesture_recognizer_model_path = test_utils.get_test_data_path( + _GESTURE_RECOGNIZER_MODEL_FILE) + + @parameterized.parameters( + (ModelFileType.FILE_NAME, _EXPECTED_DETECTION_RESULT), + (ModelFileType.FILE_CONTENT, _EXPECTED_DETECTION_RESULT)) + def test_recognize(self, model_file_type, expected_recognition_result): + # Creates gesture recognizer. + if model_file_type is ModelFileType.FILE_NAME: + gesture_recognizer_base_options = _BaseOptions( + model_asset_path=self.gesture_recognizer_model_path) + elif model_file_type is ModelFileType.FILE_CONTENT: + with open(self.gesture_recognizer_model_path, 'rb') as f: + model_content = f.read() + gesture_recognizer_base_options = _BaseOptions( + model_asset_buffer=model_content) + else: + # Should never happen + raise ValueError('model_file_type is invalid.') + + options = _GestureRecognizerOptions( + base_options=gesture_recognizer_base_options) + recognizer = _GestureRecognizer.create_from_options(options) + + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(self.test_image) + # Comparing results. + self.assertEqual(recognition_result, expected_recognition_result) + # Closes the gesture recognizer explicitly when the detector is not used in + # a context. + recognizer.close() + + +if __name__ == '__main__': + absltest.main() diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index e7be51c8..9a9ca342 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -36,3 +36,30 @@ py_library( "//mediapipe/tasks/python/vision/core:vision_task_running_mode", ], ) + +py_library( + name = "gesture_recognizer", + srcs = [ + "gesture_recognizer.py", + ], + deps = [ + "//mediapipe/python:_framework_bindings", + "//mediapipe/python:packet_creator", + "//mediapipe/python:packet_getter", + "//mediapipe/tasks/cc/vision/gesture_recognizer/proto:gesture_classifier_graph_options_py_pb2", + "//mediapipe/tasks/cc/vision/gesture_recognizer/proto:gesture_recognizer_graph_options_py_pb2", + "//mediapipe/tasks/cc/vision/gesture_recognizer/proto:hand_gesture_recognizer_graph_options_py_pb2", + "//mediapipe/tasks/cc/vision/hand_detector/proto:hand_detector_graph_options_py_pb2", + "//mediapipe/tasks/cc/vision/hand_landmarker/proto:hand_landmarker_graph_options_py_pb2", + "//mediapipe/tasks/cc/vision/hand_landmarker/proto:hand_landmarks_detector_graph_options_py_pb2", + "//mediapipe/tasks/python/components/containers:rect", + "//mediapipe/tasks/python/components/containers:classification", + "//mediapipe/tasks/python/components/containers:landmark", + "//mediapipe/tasks/python/components/processors:classifier_options", + "//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:vision_task_running_mode", + ], +) diff --git a/mediapipe/tasks/python/vision/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py new file mode 100644 index 00000000..aca7a527 --- /dev/null +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -0,0 +1,434 @@ +# 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 gesture recognizer task.""" + +import dataclasses +from typing import Callable, Mapping, Optional, List + +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.python._framework_bindings import task_runner as task_runner_module +from mediapipe.tasks.cc.vision.gesture_recognizer.proto import gesture_classifier_graph_options_pb2 +from mediapipe.tasks.cc.vision.gesture_recognizer.proto import gesture_recognizer_graph_options_pb2 +from mediapipe.tasks.cc.vision.gesture_recognizer.proto import hand_gesture_recognizer_graph_options_pb2 +from mediapipe.tasks.cc.vision.hand_detector.proto import hand_detector_graph_options_pb2 +from mediapipe.tasks.cc.vision.hand_landmarker.proto import hand_landmarker_graph_options_pb2 +from mediapipe.tasks.cc.vision.hand_landmarker.proto import hand_landmarks_detector_graph_options_pb2 +from mediapipe.tasks.python.components.containers import rect as rect_module +from mediapipe.tasks.python.components.containers import classification as classification_module +from mediapipe.tasks.python.components.containers import landmark as landmark_module +from mediapipe.tasks.python.components.processors import classifier_options +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 vision_task_running_mode as running_mode_module + +_NormalizedRect = rect_module.NormalizedRect +_BaseOptions = base_options_module.BaseOptions +_GestureClassifierGraphOptionsProto = gesture_classifier_graph_options_pb2.GestureClassifierGraphOptions +_GestureRecognizerGraphOptionsProto = gesture_recognizer_graph_options_pb2.GestureRecognizerGraphOptions +_HandGestureRecognizerGraphOptionsProto = hand_gesture_recognizer_graph_options_pb2.HandGestureRecognizerGraphOptions +_HandDetectorGraphOptionsProto = hand_detector_graph_options_pb2.HandDetectorGraphOptions +_HandLandmarkerGraphOptionsProto = hand_landmarker_graph_options_pb2.HandLandmarkerGraphOptions +_HandLandmarksDetectorGraphOptionsProto = hand_landmarks_detector_graph_options_pb2.HandLandmarksDetectorGraphOptions +_ClassifierOptions = classifier_options.ClassifierOptions +_RunningMode = running_mode_module.VisionTaskRunningMode +_TaskInfo = task_info_module.TaskInfo +_TaskRunner = task_runner_module.TaskRunner + +_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' +_HAND_GESTURE_STREAM_NAME = 'hand_gestures' +_HAND_GESTURE_TAG = 'HAND_GESTURES' +_HANDEDNESS_STREAM_NAME = 'handedness' +_HANDEDNESS_TAG = 'HANDEDNESS' +_HAND_LANDMARKS_STREAM_NAME = 'landmarks' +_HAND_LANDMARKS_TAG = 'LANDMARKS' +_HAND_WORLD_LANDMARKS_STREAM_NAME = 'world_landmarks' +_HAND_WORLD_LANDMARKS_TAG = 'WORLD_LANDMARKS' +_TASK_GRAPH_NAME = 'mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph' +_MICRO_SECONDS_PER_MILLISECOND = 1000 + + +def _build_full_image_norm_rect() -> _NormalizedRect: + # Builds a NormalizedRect covering the entire image. + return _NormalizedRect(x_center=0.5, y_center=0.5, width=1, height=1) + + +@dataclasses.dataclass +class GestureRecognitionResult: + """The gesture recognition result from GestureRecognizer, where each vector + element represents a single hand detected in the image. + + Attributes: + gestures: Recognized hand gestures with sorted order such that the + winning label is the first item in the list. + handedness: Classification of handedness. + hand_landmarks: Detected hand landmarks in normalized image coordinates. + hand_world_landmarks: Detected hand landmarks in world coordinates. + """ + + gestures: List[classification_module.ClassificationList] + handedness: List[classification_module.ClassificationList] + hand_landmarks: List[landmark_module.NormalizedLandmarkList] + hand_world_landmarks: List[landmark_module.LandmarkList] + + +@dataclasses.dataclass +class GestureRecognizerOptions: + """Options for the gesture recognizer task. + + Attributes: + base_options: Base options for the hand gesture recognizer task. + running_mode: The running mode of the task. Default to the image mode. + Gesture recognizer task has three running modes: + 1) The image mode for recognizing hand gestures on single image inputs. + 2) The video mode for recognizing hand gestures on the decoded frames of a + video. + 3) The live stream mode for recognizing hand gestures on a live stream of + input data, such as from camera. + num_hands: The maximum number of hands can be detected by the recognizer. + min_hand_detection_confidence: The minimum confidence score for the hand + detection to be considered successful. + min_hand_presence_confidence: The minimum confidence score of hand presence + score in the hand landmark detection. + min_tracking_confidence: The minimum confidence score for the hand tracking + to be considered successful. + min_gesture_confidence: The minimum confidence score for the gestures to be + considered successful. If < 0, the gesture confidence thresholds in the + model metadata are used. + TODO: Note this option is subject to change, after scoring merging + calculator is implemented. + 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_hands: Optional[int] = 1 + min_hand_detection_confidence: Optional[int] = 0.5 + min_hand_presence_confidence: Optional[int] = 0.5 + min_tracking_confidence: Optional[int] = 0.5 + min_gesture_confidence: Optional[int] = -1 + result_callback: Optional[ + Callable[[GestureRecognitionResult, image_module.Image, + int], None]] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _GestureRecognizerGraphOptionsProto: + """Generates an GestureRecognizerOptions 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 + # hand_landmark_detector_base_options_proto = self.hand_landmark_detector_base_options.to_pb2() + # hand_landmark_detector_base_options_proto.use_stream_mode = False if self.running_mode == _RunningMode.IMAGE else True + + # Configure hand detector options. + hand_detector_options_proto = _HandDetectorGraphOptionsProto( + num_hands=self.num_hands, + min_detection_confidence=self.min_hand_detection_confidence) + + # Configure hand landmarker options. + hand_landmarks_detector_options_proto = _HandLandmarksDetectorGraphOptionsProto( + min_detection_confidence=self.min_hand_presence_confidence) + hand_landmarker_options_proto = _HandLandmarkerGraphOptionsProto( + hand_detector_graph_options=hand_detector_options_proto, + hand_landmarks_detector_graph_options=hand_landmarks_detector_options_proto, + min_tracking_confidence=self.min_tracking_confidence) + + # Configure hand gesture recognizer options. + hand_gesture_recognizer_options_proto = _HandGestureRecognizerGraphOptionsProto() + if self.min_gesture_confidence >= 0: + classifier_options = _ClassifierOptions( + score_threshold=self.min_gesture_confidence) + hand_gesture_recognizer_options_proto.canned_gesture_classifier_graph_options = \ + _GestureClassifierGraphOptionsProto( + classifier_options=classifier_options.to_pb2()) + + return _GestureRecognizerGraphOptionsProto( + base_options=base_options_proto, + hand_landmarker_graph_options=hand_landmarker_options_proto, + hand_gesture_recognizer_graph_options=hand_gesture_recognizer_options_proto + ) + + +class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): + """Class that performs gesture recognition on images.""" + + @classmethod + def create_from_model_path(cls, model_path: str) -> 'GestureRecognizer': + """Creates an `GestureRecognizer` object from a TensorFlow Lite model and + the default `GestureRecognizerOptions`. + + Note that the created `GestureRecognizer` instance is in image mode, for + recognizing hand gestures on single image inputs. + + Args: + model_path: Path to the model. + + Returns: + `GestureRecognizer` object that's created from the model file and the + default `GestureRecognizerOptions`. + + Raises: + ValueError: If failed to create `GestureRecognizer` 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 = GestureRecognizerOptions( + base_options=base_options, running_mode=_RunningMode.IMAGE) + return cls.create_from_options(options) + + @classmethod + def create_from_options( + cls, + options: GestureRecognizerOptions + ) -> 'GestureRecognizer': + """Creates the `GestureRecognizer` object from gesture recognizer options. + + Args: + options: Options for the gesture recognizer task. + + Returns: + `GestureRecognizer` object that's created from `options`. + + Raises: + ValueError: If failed to create `GestureRecognizer` object from + `GestureRecognizerOptions` 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[_HAND_GESTURE_STREAM_NAME].is_empty(): + empty_packet = output_packets[_HAND_GESTURE_STREAM_NAME] + options.result_callback( + GestureRecognitionResult([], [], [], []), image, + empty_packet.timestamp.value // _MICRO_SECONDS_PER_MILLISECOND) + return + + gestures_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_GESTURE_STREAM_NAME]) + handedness_proto_list = packet_getter.get_proto_list( + output_packets[_HANDEDNESS_STREAM_NAME]) + hand_landmarks_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_LANDMARKS_STREAM_NAME]) + hand_world_landmarks_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_WORLD_LANDMARKS_STREAM_NAME]) + + gesture_recognition_result = GestureRecognitionResult( + [ + classification_module.ClassificationList.create_from_pb2(gestures) + for gestures in gestures_proto_list + ], [ + classification_module.ClassificationList.create_from_pb2(handedness) + for handedness in handedness_proto_list + ], [ + landmark_module.NormalizedLandmarkList.create_from_pb2(hand_landmarks) + for hand_landmarks in hand_landmarks_proto_list + ], [ + landmark_module.LandmarkList.create_from_pb2(hand_world_landmarks) + for hand_world_landmarks in hand_world_landmarks_proto_list + ] + ) + timestamp = output_packets[_HAND_GESTURE_STREAM_NAME].timestamp + options.result_callback( + gesture_recognition_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([_HAND_GESTURE_TAG, _HAND_GESTURE_STREAM_NAME]), + ':'.join([_HANDEDNESS_TAG, _HANDEDNESS_STREAM_NAME]), + ':'.join([_HAND_LANDMARKS_TAG, _HAND_LANDMARKS_STREAM_NAME]), + ':'.join([_HAND_WORLD_LANDMARKS_TAG, + _HAND_WORLD_LANDMARKS_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 recognize( + self, + image: image_module.Image, + roi: Optional[_NormalizedRect] = None + ) -> GestureRecognitionResult: + """Performs hand gesture recognition on the given image. Only use this + method when the GestureRecognizer 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. + roi: The region of interest. + + Returns: + The hand gesture recognition results. + + Raises: + ValueError: If any of the input arguments is invalid. + RuntimeError: If gesture recognition failed to run. + """ + norm_rect = roi if roi is not None else _build_full_image_norm_rect() + output_packets = self._process_image_data({ + _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image), + _NORM_RECT_STREAM_NAME: packet_creator.create_proto( + norm_rect.to_pb2())}) + gestures_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_GESTURE_STREAM_NAME]) + handedness_proto_list = packet_getter.get_proto_list( + output_packets[_HANDEDNESS_STREAM_NAME]) + hand_landmarks_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_LANDMARKS_STREAM_NAME]) + hand_world_landmarks_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_WORLD_LANDMARKS_STREAM_NAME]) + + return GestureRecognitionResult( + [ + classification_module.ClassificationList.create_from_pb2(gestures) + for gestures in gestures_proto_list + ], [ + classification_module.ClassificationList.create_from_pb2(handedness) + for handedness in handedness_proto_list + ], [ + landmark_module.NormalizedLandmarkList.create_from_pb2(hand_landmarks) + for hand_landmarks in hand_landmarks_proto_list + ], [ + landmark_module.LandmarkList.create_from_pb2(hand_world_landmarks) + for hand_world_landmarks in hand_world_landmarks_proto_list + ] + ) + + def recognize_for_video( + self, image: image_module.Image, + timestamp_ms: int, + roi: Optional[_NormalizedRect] = None + ) -> GestureRecognitionResult: + """Performs gesture recognition on the provided video frame. Only use this + method when the GestureRecognizer is created with the video running mode. + + Only use this method when the GestureRecognizer 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. + roi: The region of interest. + + Returns: + The hand gesture recognition results. + + Raises: + ValueError: If any of the input arguments is invalid. + RuntimeError: If gesture recognition failed to run. + """ + norm_rect = roi if roi is not None else _build_full_image_norm_rect() + 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( + norm_rect.to_pb2()).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) + }) + gestures_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_GESTURE_STREAM_NAME]) + handedness_proto_list = packet_getter.get_proto_list( + output_packets[_HANDEDNESS_STREAM_NAME]) + hand_landmarks_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_LANDMARKS_STREAM_NAME]) + hand_world_landmarks_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_WORLD_LANDMARKS_STREAM_NAME]) + + return GestureRecognitionResult( + [ + classification_module.ClassificationList.create_from_pb2(gestures) + for gestures in gestures_proto_list + ], [ + classification_module.ClassificationList.create_from_pb2(handedness) + for handedness in handedness_proto_list + ], [ + landmark_module.NormalizedLandmarkList.create_from_pb2(hand_landmarks) + for hand_landmarks in hand_landmarks_proto_list + ], [ + landmark_module.LandmarkList.create_from_pb2(hand_world_landmarks) + for hand_world_landmarks in hand_world_landmarks_proto_list + ] + ) + + def recognize_async( + self, + image: image_module.Image, + timestamp_ms: int, + roi: Optional[_NormalizedRect] = None + ) -> None: + """Sends live image data to perform gesture recognition, and the results + will be available via the "result_callback" provided in the + GestureRecognizerOptions. Only use this method when the GestureRecognizer + is created with the live stream running mode. + + Only use this method when the GestureRecognizer 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 `GestureRecognizerOptions`. The + `recognize_async` method is designed to process live stream data such as + camera input. To lower the overall latency, gesture recognizer 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 hand gesture recognition results. + - The input image that the image classifier runs on. + - The input timestamp in milliseconds. + + Args: + image: MediaPipe Image. + timestamp_ms: The timestamp of the input image in milliseconds. + roi: The region of interest. + + Raises: + ValueError: If the current input timestamp is smaller than what the + gesture recognizer has already processed. + """ + norm_rect = roi if roi is not None else _build_full_image_norm_rect() + 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( + norm_rect.to_pb2()).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) + }) From 18eb089d39356ade117fbc629c5e19bef35f2d22 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Tue, 25 Oct 2022 07:38:04 -0700 Subject: [PATCH 02/16] Added a simple test to verify gesture recognition results --- .../tasks/python/components/containers/BUILD | 6 +- .../components/containers/classification.py | 19 ++- .../python/components/containers/gesture.py | 138 ------------------ .../containers/landmark_detection_result.py | 82 +++++++++++ mediapipe/tasks/python/test/vision/BUILD | 6 +- .../test/vision/gesture_recognizer_test.py | 85 ++++++++++- .../tasks/python/vision/gesture_recognizer.py | 15 +- mediapipe/tasks/testdata/vision/BUILD | 1 + 8 files changed, 184 insertions(+), 168 deletions(-) delete mode 100644 mediapipe/tasks/python/components/containers/gesture.py create mode 100644 mediapipe/tasks/python/components/containers/landmark_detection_result.py diff --git a/mediapipe/tasks/python/components/containers/BUILD b/mediapipe/tasks/python/components/containers/BUILD index 325dff5f..8aaa64cc 100644 --- a/mediapipe/tasks/python/components/containers/BUILD +++ b/mediapipe/tasks/python/components/containers/BUILD @@ -55,11 +55,13 @@ py_library( ) py_library( - name = "gesture", - srcs = ["gesture.py"], + name = "landmark_detection_result", + srcs = ["landmark_detection_result.py"], deps = [ + ":rect", ":classification", ":landmark", + "//mediapipe/tasks/cc/components/containers/proto:landmarks_detection_result_py_pb2", "//mediapipe/tasks/python/core:optional_dependencies", ], ) diff --git a/mediapipe/tasks/python/components/containers/classification.py b/mediapipe/tasks/python/components/containers/classification.py index 157c3452..465e2dd2 100644 --- a/mediapipe/tasks/python/components/containers/classification.py +++ b/mediapipe/tasks/python/components/containers/classification.py @@ -14,14 +14,13 @@ """Classification data class.""" import dataclasses -from typing import Any, List +from typing import Any, List, Optional from mediapipe.framework.formats import classification_pb2 from mediapipe.tasks.python.core.optional_dependencies import doc_controls _ClassificationProto = classification_pb2.Classification _ClassificationListProto = classification_pb2.ClassificationList -_ClassificationListCollectionProto = classification_pb2.ClassificationListCollection @dataclasses.dataclass @@ -35,10 +34,10 @@ class Classification: display_name: Optional human-readable string for display purposes. """ - index: int - score: float - label_name: str - display_name: str + index: Optional[int] = None + score: Optional[float] = None + label: Optional[str] = None + display_name: Optional[str] = None @doc_controls.do_not_generate_docs def to_pb2(self) -> _ClassificationProto: @@ -46,7 +45,7 @@ class Classification: return _ClassificationProto( index=self.index, score=self.score, - label_name=self.label_name, + label=self.label, display_name=self.display_name) @classmethod @@ -56,7 +55,7 @@ class Classification: return Classification( index=pb2_obj.index, score=pb2_obj.score, - label_name=pb2_obj.label_name, + label=pb2_obj.label, display_name=pb2_obj.display_name) def __eq__(self, other: Any) -> bool: @@ -86,8 +85,8 @@ class ClassificationList: """ classifications: List[Classification] - tensor_index: int - tensor_name: str + tensor_index: Optional[int] = None + tensor_name: Optional[str] = None @doc_controls.do_not_generate_docs def to_pb2(self) -> _ClassificationListProto: diff --git a/mediapipe/tasks/python/components/containers/gesture.py b/mediapipe/tasks/python/components/containers/gesture.py deleted file mode 100644 index f314d18b..00000000 --- a/mediapipe/tasks/python/components/containers/gesture.py +++ /dev/null @@ -1,138 +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. -"""Gesture data class.""" - -import dataclasses -from typing import Any, List - -from mediapipe.tasks.python.components.containers import classification -from mediapipe.tasks.python.components.containers import landmark -from mediapipe.tasks.python.core.optional_dependencies import doc_controls - - -@dataclasses.dataclass -class GestureRecognitionResult: - """ The gesture recognition result from GestureRecognizer, where each vector - element represents a single hand detected in the image. - - Attributes: - gestures: Recognized hand gestures with sorted order such that the - winning label is the first item in the list. - handedness: Classification of handedness. - hand_landmarks: Detected hand landmarks in normalized image coordinates. - hand_world_landmarks: Detected hand landmarks in world coordinates. - """ - - gestures: List[classification.ClassificationList] - handedness: List[classification.ClassificationList] - hand_landmarks: List[landmark.NormalizedLandmarkList] - hand_world_landmarks: List[landmark.LandmarkList] - - @doc_controls.do_not_generate_docs - def to_pb2(self) -> _DetectionProto: - """Generates a Detection protobuf object.""" - labels = [] - label_ids = [] - scores = [] - display_names = [] - for category in self.categories: - scores.append(category.score) - if category.index: - label_ids.append(category.index) - if category.category_name: - labels.append(category.category_name) - if category.display_name: - display_names.append(category.display_name) - return _DetectionProto( - label=labels, - label_id=label_ids, - score=scores, - display_name=display_names, - location_data=_LocationDataProto( - format=_LocationDataProto.Format.BOUNDING_BOX, - bounding_box=self.bounding_box.to_pb2())) - - @classmethod - @doc_controls.do_not_generate_docs - def create_from_pb2(cls, pb2_obj: _DetectionProto) -> 'Detection': - """Creates a `Detection` object from the given protobuf object.""" - categories = [] - for idx, score in enumerate(pb2_obj.score): - categories.append( - category_module.Category( - score=score, - index=pb2_obj.label_id[idx] - if idx < len(pb2_obj.label_id) else None, - category_name=pb2_obj.label[idx] - if idx < len(pb2_obj.label) else None, - display_name=pb2_obj.display_name[idx] - if idx < len(pb2_obj.display_name) else None)) - - return Detection( - bounding_box=bounding_box_module.BoundingBox.create_from_pb2( - pb2_obj.location_data.bounding_box), - categories=categories) - - 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, Detection): - return False - - return self.to_pb2().__eq__(other.to_pb2()) - - -@dataclasses.dataclass -class DetectionResult: - """Represents the list of detected objects. - - Attributes: - detections: A list of `Detection` objects. - """ - - detections: List[Detection] - - @doc_controls.do_not_generate_docs - def to_pb2(self) -> _DetectionListProto: - """Generates a DetectionList protobuf object.""" - return _DetectionListProto( - detection=[detection.to_pb2() for detection in self.detections]) - - @classmethod - @doc_controls.do_not_generate_docs - def create_from_pb2(cls, pb2_obj: _DetectionListProto) -> 'DetectionResult': - """Creates a `DetectionResult` object from the given protobuf object.""" - return DetectionResult(detections=[ - Detection.create_from_pb2(detection) for detection in pb2_obj.detection - ]) - - 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, DetectionResult): - return False - - return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/components/containers/landmark_detection_result.py b/mediapipe/tasks/python/components/containers/landmark_detection_result.py new file mode 100644 index 00000000..c3d93d41 --- /dev/null +++ b/mediapipe/tasks/python/components/containers/landmark_detection_result.py @@ -0,0 +1,82 @@ +# 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. +"""Landmark Detection Result data class.""" + +import dataclasses +from typing import Any, Optional + +from mediapipe.tasks.cc.components.containers.proto import landmarks_detection_result_pb2 +from mediapipe.tasks.python.components.containers import rect as rect_module +from mediapipe.tasks.python.components.containers import classification as classification_module +from mediapipe.tasks.python.components.containers import landmark as landmark_module +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_LandmarksDetectionResultProto = landmarks_detection_result_pb2.LandmarksDetectionResult +_NormalizedRect = rect_module.NormalizedRect +_ClassificationList = classification_module.ClassificationList +_NormalizedLandmarkList = landmark_module.NormalizedLandmarkList +_LandmarkList = landmark_module.LandmarkList + + +@dataclasses.dataclass +class LandmarksDetectionResult: + """Represents the landmarks detection result. + + Attributes: + landmarks : A `NormalizedLandmarkList` object. + classifications : A `ClassificationList` object. + world_landmarks : A `LandmarkList` object. + rect : A `NormalizedRect` object. + """ + + landmarks: Optional[_NormalizedLandmarkList] + classifications: Optional[_ClassificationList] + world_landmarks: Optional[_LandmarkList] + rect: _NormalizedRect + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _LandmarksDetectionResultProto: + """Generates a LandmarksDetectionResult protobuf object.""" + return _LandmarksDetectionResultProto( + landmarks=self.landmarks.to_pb2(), + classifications=self.classifications.to_pb2(), + world_landmarks=self.world_landmarks.to_pb2(), + rect=self.rect.to_pb2()) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, + pb2_obj: _LandmarksDetectionResultProto + ) -> 'LandmarksDetectionResult': + """Creates a `LandmarksDetectionResult` object from the given protobuf + object.""" + return LandmarksDetectionResult( + landmarks=_NormalizedLandmarkList.create_from_pb2(pb2_obj.landmarks), + classifications=_ClassificationList.create_from_pb2( + pb2_obj.classifications), + world_landmarks=_LandmarkList.create_from_pb2(pb2_obj.world_landmarks), + rect=_NormalizedRect.create_from_pb2(pb2_obj.rect)) + + 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, LandmarksDetectionResult): + 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 0dd83edc..0d8b9998 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -43,15 +43,19 @@ py_test( 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/tasks/cc/components/containers/proto:landmarks_detection_result_py_pb2", + "//mediapipe/tasks/python/components/containers:rect", "//mediapipe/tasks/python/components/containers:classification", "//mediapipe/tasks/python/components/containers:landmark", - "//mediapipe/tasks/python/components/containers:rect", + "//mediapipe/tasks/python/components/containers:landmark_detection_result", "//mediapipe/tasks/python/core:base_options", "//mediapipe/tasks/python/test:test_utils", "//mediapipe/tasks/python/vision:gesture_recognizer", "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + "@com_google_protobuf//:protobuf_python" ], ) diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index 288cfd1f..7d731d80 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -15,23 +15,31 @@ import enum +from google.protobuf import text_format from absl.testing import absltest from absl.testing import parameterized from mediapipe.python._framework_bindings import image as image_module +from mediapipe.tasks.cc.components.containers.proto import landmarks_detection_result_pb2 from mediapipe.tasks.python.components.containers import rect as rect_module from mediapipe.tasks.python.components.containers import classification as classification_module from mediapipe.tasks.python.components.containers import landmark as landmark_module +from mediapipe.tasks.python.components.containers import landmark_detection_result as landmark_detection_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 gesture_recognizer from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module +_LandmarksDetectionResultProto = landmarks_detection_result_pb2.LandmarksDetectionResult _BaseOptions = base_options_module.BaseOptions _NormalizedRect = rect_module.NormalizedRect +_Classification = classification_module.Classification _ClassificationList = classification_module.ClassificationList +_Landmark = landmark_module.Landmark _LandmarkList = landmark_module.LandmarkList +_NormalizedLandmark = landmark_module.NormalizedLandmark _NormalizedLandmarkList = landmark_module.NormalizedLandmarkList +_LandmarksDetectionResult = landmark_detection_result_module.LandmarksDetectionResult _Image = image_module.Image _GestureRecognizer = gesture_recognizer.GestureRecognizer _GestureRecognizerOptions = gesture_recognizer.GestureRecognizerOptions @@ -39,8 +47,35 @@ _GestureRecognitionResult = gesture_recognizer.GestureRecognitionResult _RUNNING_MODE = running_mode_module.VisionTaskRunningMode _GESTURE_RECOGNIZER_MODEL_FILE = 'gesture_recognizer.task' -_IMAGE_FILE = 'right_hands.jpg' -_EXPECTED_DETECTION_RESULT = _GestureRecognitionResult([], [], [], []) +_THUMB_UP_IMAGE = 'thumb_up.jpg' +_THUMB_UP_LANDMARKS = "thumb_up_landmarks.pbtxt" +_THUMB_UP_LABEL = "Thumb_Up" +_THUMB_UP_INDEX = 5 +_LANDMARKS_ERROR_TOLERANCE = 0.03 + + +def _get_expected_gesture_recognition_result( + file_path: str, gesture_label: str, gesture_index: int +) -> _GestureRecognitionResult: + landmarks_detection_result_file_path = test_utils.get_test_data_path( + file_path) + with open(landmarks_detection_result_file_path, "rb") as f: + landmarks_detection_result_proto = _LandmarksDetectionResultProto() + # # Use this if a .pb file is available. + # landmarks_detection_result_proto.ParseFromString(f.read()) + text_format.Parse(f.read(), landmarks_detection_result_proto) + landmarks_detection_result = _LandmarksDetectionResult.create_from_pb2( + landmarks_detection_result_proto) + gesture = _ClassificationList( + classifications=[ + _Classification(label=gesture_label, index=gesture_index, + display_name='') + ], tensor_index=0, tensor_name='') + return _GestureRecognitionResult( + gestures=[gesture], + handedness=[landmarks_detection_result.classifications], + hand_landmarks=[landmarks_detection_result.landmarks], + hand_world_landmarks=[landmarks_detection_result.world_landmarks]) class ModelFileType(enum.Enum): @@ -53,14 +88,45 @@ class GestureRecognizerTest(parameterized.TestCase): def setUp(self): super().setUp() self.test_image = _Image.create_from_file( - test_utils.get_test_data_path(_IMAGE_FILE)) + test_utils.get_test_data_path(_THUMB_UP_IMAGE)) self.gesture_recognizer_model_path = test_utils.get_test_data_path( _GESTURE_RECOGNIZER_MODEL_FILE) + def _assert_actual_result_approximately_matches_expected_result( + self, + actual_result: _GestureRecognitionResult, + expected_result: _GestureRecognitionResult + ): + # Expects to have the same number of hands detected. + self.assertLen(actual_result.hand_landmarks, + len(expected_result.hand_landmarks)) + self.assertLen(actual_result.hand_world_landmarks, + len(expected_result.hand_world_landmarks)) + self.assertLen(actual_result.handedness, len(expected_result.handedness)) + self.assertLen(actual_result.gestures, len(expected_result.gestures)) + # Actual landmarks match expected landmarks. + self.assertEqual(actual_result.hand_landmarks, + expected_result.hand_landmarks) + # Actual handedness matches expected handedness. + actual_top_handedness = actual_result.handedness[0].classifications[0] + expected_top_handedness = expected_result.handedness[0].classifications[0] + self.assertEqual(actual_top_handedness.index, expected_top_handedness.index) + self.assertEqual(actual_top_handedness.label, expected_top_handedness.label) + # Actual gesture with top score matches expected gesture. + actual_top_gesture = actual_result.gestures[0].classifications[0] + expected_top_gesture = expected_result.gestures[0].classifications[0] + self.assertEqual(actual_top_gesture.index, expected_top_gesture.index) + self.assertEqual(actual_top_gesture.label, expected_top_gesture.label) + @parameterized.parameters( - (ModelFileType.FILE_NAME, _EXPECTED_DETECTION_RESULT), - (ModelFileType.FILE_CONTENT, _EXPECTED_DETECTION_RESULT)) - def test_recognize(self, model_file_type, expected_recognition_result): + (ModelFileType.FILE_NAME, 0.3, _get_expected_gesture_recognition_result( + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX + )), + (ModelFileType.FILE_CONTENT, 0.3, _get_expected_gesture_recognition_result( + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX + ))) + def test_recognize(self, model_file_type, min_gesture_confidence, + expected_recognition_result): # Creates gesture recognizer. if model_file_type is ModelFileType.FILE_NAME: gesture_recognizer_base_options = _BaseOptions( @@ -75,13 +141,16 @@ class GestureRecognizerTest(parameterized.TestCase): raise ValueError('model_file_type is invalid.') options = _GestureRecognizerOptions( - base_options=gesture_recognizer_base_options) + base_options=gesture_recognizer_base_options, + min_gesture_confidence=min_gesture_confidence + ) recognizer = _GestureRecognizer.create_from_options(options) # Performs hand gesture recognition on the input. recognition_result = recognizer.recognize(self.test_image) # Comparing results. - self.assertEqual(recognition_result, expected_recognition_result) + self._assert_actual_result_approximately_matches_expected_result( + recognition_result, expected_recognition_result) # Closes the gesture recognizer explicitly when the detector is not used in # a context. recognizer.close() diff --git a/mediapipe/tasks/python/vision/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py index aca7a527..c00508b3 100644 --- a/mediapipe/tasks/python/vision/gesture_recognizer.py +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -136,8 +136,6 @@ class GestureRecognizerOptions: """Generates an GestureRecognizerOptions 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 - # hand_landmark_detector_base_options_proto = self.hand_landmark_detector_base_options.to_pb2() - # hand_landmark_detector_base_options_proto.use_stream_mode = False if self.running_mode == _RunningMode.IMAGE else True # Configure hand detector options. hand_detector_options_proto = _HandDetectorGraphOptionsProto( @@ -153,13 +151,12 @@ class GestureRecognizerOptions: min_tracking_confidence=self.min_tracking_confidence) # Configure hand gesture recognizer options. - hand_gesture_recognizer_options_proto = _HandGestureRecognizerGraphOptionsProto() - if self.min_gesture_confidence >= 0: - classifier_options = _ClassifierOptions( - score_threshold=self.min_gesture_confidence) - hand_gesture_recognizer_options_proto.canned_gesture_classifier_graph_options = \ - _GestureClassifierGraphOptionsProto( - classifier_options=classifier_options.to_pb2()) + classifier_options = _ClassifierOptions( + score_threshold=self.min_gesture_confidence) + gesture_classifier_options = _GestureClassifierGraphOptionsProto( + classifier_options=classifier_options.to_pb2()) + hand_gesture_recognizer_options_proto = _HandGestureRecognizerGraphOptionsProto( + canned_gesture_classifier_graph_options=gesture_classifier_options) return _GestureRecognizerGraphOptionsProto( base_options=base_options_proto, diff --git a/mediapipe/tasks/testdata/vision/BUILD b/mediapipe/tasks/testdata/vision/BUILD index ebb8f05a..365921bc 100644 --- a/mediapipe/tasks/testdata/vision/BUILD +++ b/mediapipe/tasks/testdata/vision/BUILD @@ -121,6 +121,7 @@ filegroup( "hand_landmark_full.tflite", "hand_landmark_lite.tflite", "hand_landmarker.task", + "gesture_recognizer.task", "mobilenet_v1_0.25_192_quantized_1_default_1.tflite", "mobilenet_v1_0.25_224_1_default_1.tflite", "mobilenet_v1_0.25_224_1_metadata_1.tflite", From 8762d15c81ee201188cfc482f0bbcc8b18ec0530 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Tue, 25 Oct 2022 11:11:15 -0700 Subject: [PATCH 03/16] Added remaining tests for the GestureRecognizer Python MediaPipe Tasks API --- .../containers/landmark_detection_result.py | 2 +- mediapipe/tasks/python/test/vision/BUILD | 1 + .../test/vision/gesture_recognizer_test.py | 311 ++++++++++++++++-- mediapipe/tasks/python/vision/BUILD | 1 - mediapipe/tasks/python/vision/core/BUILD | 9 + .../vision/core/base_vision_task_api.py | 49 +++ .../vision/core/image_processing_options.py | 39 +++ .../tasks/python/vision/gesture_recognizer.py | 44 +-- 8 files changed, 414 insertions(+), 42 deletions(-) create mode 100644 mediapipe/tasks/python/vision/core/image_processing_options.py diff --git a/mediapipe/tasks/python/components/containers/landmark_detection_result.py b/mediapipe/tasks/python/components/containers/landmark_detection_result.py index c3d93d41..02ca5a91 100644 --- a/mediapipe/tasks/python/components/containers/landmark_detection_result.py +++ b/mediapipe/tasks/python/components/containers/landmark_detection_result.py @@ -11,7 +11,7 @@ # 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. -"""Landmark Detection Result data class.""" +"""Landmarks Detection Result data class.""" import dataclasses from typing import Any, Optional diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index 0d8b9998..6455d7fc 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -56,6 +56,7 @@ py_test( "//mediapipe/tasks/python/test:test_utils", "//mediapipe/tasks/python/vision:gesture_recognizer", "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + "//mediapipe/tasks/python/vision/core:image_processing_options", "@com_google_protobuf//:protobuf_python" ], ) diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index 7d731d80..a8316c52 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -14,7 +14,9 @@ """Tests for gesture recognizer.""" import enum +from unittest import mock +import numpy as np from google.protobuf import text_format from absl.testing import absltest from absl.testing import parameterized @@ -29,10 +31,11 @@ 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 gesture_recognizer from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module +from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module _LandmarksDetectionResultProto = landmarks_detection_result_pb2.LandmarksDetectionResult _BaseOptions = base_options_module.BaseOptions -_NormalizedRect = rect_module.NormalizedRect +_Rect = rect_module.Rect _Classification = classification_module.Classification _ClassificationList = classification_module.ClassificationList _Landmark = landmark_module.Landmark @@ -45,12 +48,19 @@ _GestureRecognizer = gesture_recognizer.GestureRecognizer _GestureRecognizerOptions = gesture_recognizer.GestureRecognizerOptions _GestureRecognitionResult = gesture_recognizer.GestureRecognitionResult _RUNNING_MODE = running_mode_module.VisionTaskRunningMode +_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _GESTURE_RECOGNIZER_MODEL_FILE = 'gesture_recognizer.task' +_NO_HANDS_IMAGE = 'cats_and_dogs.jpg' +_TWO_HANDS_IMAGE = 'right_hands.jpg' _THUMB_UP_IMAGE = 'thumb_up.jpg' -_THUMB_UP_LANDMARKS = "thumb_up_landmarks.pbtxt" -_THUMB_UP_LABEL = "Thumb_Up" +_THUMB_UP_LANDMARKS = 'thumb_up_landmarks.pbtxt' +_THUMB_UP_LABEL = 'Thumb_Up' _THUMB_UP_INDEX = 5 +_POINTING_UP_ROTATED_IMAGE = 'pointing_up_rotated.jpg' +_POINTING_UP_LANDMARKS = 'pointing_up_rotated_landmarks.pbtxt' +_POINTING_UP_LABEL = 'Pointing_Up' +_POINTING_UP_INDEX = 3 _LANDMARKS_ERROR_TOLERANCE = 0.03 @@ -89,7 +99,7 @@ class GestureRecognizerTest(parameterized.TestCase): super().setUp() self.test_image = _Image.create_from_file( test_utils.get_test_data_path(_THUMB_UP_IMAGE)) - self.gesture_recognizer_model_path = test_utils.get_test_data_path( + self.model_path = test_utils.get_test_data_path( _GESTURE_RECOGNIZER_MODEL_FILE) def _assert_actual_result_approximately_matches_expected_result( @@ -105,8 +115,15 @@ class GestureRecognizerTest(parameterized.TestCase): self.assertLen(actual_result.handedness, len(expected_result.handedness)) self.assertLen(actual_result.gestures, len(expected_result.gestures)) # Actual landmarks match expected landmarks. - self.assertEqual(actual_result.hand_landmarks, - expected_result.hand_landmarks) + self.assertLen(actual_result.hand_landmarks[0].landmarks, + len(expected_result.hand_landmarks[0].landmarks)) + actual_landmarks = actual_result.hand_landmarks[0].landmarks + expected_landmarks = expected_result.hand_landmarks[0].landmarks + for i in range(len(actual_landmarks)): + self.assertAlmostEqual(actual_landmarks[i].x, expected_landmarks[i].x, + delta=_LANDMARKS_ERROR_TOLERANCE) + self.assertAlmostEqual(actual_landmarks[i].y, expected_landmarks[i].y, + delta=_LANDMARKS_ERROR_TOLERANCE) # Actual handedness matches expected handedness. actual_top_handedness = actual_result.handedness[0].classifications[0] expected_top_handedness = expected_result.handedness[0].classifications[0] @@ -118,32 +135,56 @@ class GestureRecognizerTest(parameterized.TestCase): self.assertEqual(actual_top_gesture.index, expected_top_gesture.index) self.assertEqual(actual_top_gesture.label, expected_top_gesture.label) + def test_create_from_file_succeeds_with_valid_model_path(self): + # Creates with default option and valid model file successfully. + with _GestureRecognizer.create_from_model_path(self.model_path) as recognizer: + self.assertIsInstance(recognizer, _GestureRecognizer) + + 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 = _GestureRecognizerOptions(base_options=base_options) + with _GestureRecognizer.create_from_options(options) as recognizer: + self.assertIsInstance(recognizer, _GestureRecognizer) + + def test_create_from_options_fails_with_invalid_model_path(self): + # Invalid empty model path. + with self.assertRaisesRegex( + ValueError, + r"ExternalFile must specify at least one of 'file_content', " + r"'file_name', 'file_pointer_meta' or 'file_descriptor_meta'."): + base_options = _BaseOptions(model_asset_path='') + options = _GestureRecognizerOptions(base_options=base_options) + _GestureRecognizer.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 = _GestureRecognizerOptions(base_options=base_options) + recognizer = _GestureRecognizer.create_from_options(options) + self.assertIsInstance(recognizer, _GestureRecognizer) + @parameterized.parameters( - (ModelFileType.FILE_NAME, 0.3, _get_expected_gesture_recognition_result( + (ModelFileType.FILE_NAME, _get_expected_gesture_recognition_result( _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX )), - (ModelFileType.FILE_CONTENT, 0.3, _get_expected_gesture_recognition_result( + (ModelFileType.FILE_CONTENT, _get_expected_gesture_recognition_result( _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX ))) - def test_recognize(self, model_file_type, min_gesture_confidence, - expected_recognition_result): + def test_recognize(self, model_file_type, expected_recognition_result): # Creates gesture recognizer. if model_file_type is ModelFileType.FILE_NAME: - gesture_recognizer_base_options = _BaseOptions( - model_asset_path=self.gesture_recognizer_model_path) + base_options = _BaseOptions(model_asset_path=self.model_path) elif model_file_type is ModelFileType.FILE_CONTENT: - with open(self.gesture_recognizer_model_path, 'rb') as f: + with open(self.model_path, 'rb') as f: model_content = f.read() - gesture_recognizer_base_options = _BaseOptions( - model_asset_buffer=model_content) + base_options = _BaseOptions(model_asset_buffer=model_content) else: # Should never happen raise ValueError('model_file_type is invalid.') - options = _GestureRecognizerOptions( - base_options=gesture_recognizer_base_options, - min_gesture_confidence=min_gesture_confidence - ) + options = _GestureRecognizerOptions(base_options=base_options) recognizer = _GestureRecognizer.create_from_options(options) # Performs hand gesture recognition on the input. @@ -151,10 +192,238 @@ class GestureRecognizerTest(parameterized.TestCase): # Comparing results. self._assert_actual_result_approximately_matches_expected_result( recognition_result, expected_recognition_result) - # Closes the gesture recognizer explicitly when the detector is not used in - # a context. + # Closes the gesture recognizer explicitly when the gesture recognizer is + # not used in a context. recognizer.close() + @parameterized.parameters( + (ModelFileType.FILE_NAME, _get_expected_gesture_recognition_result( + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX + )), + (ModelFileType.FILE_CONTENT, _get_expected_gesture_recognition_result( + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX + ))) + def test_recognize_in_context(self, model_file_type, + expected_recognition_result): + # Creates gesture recognizer. + 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 = _GestureRecognizerOptions(base_options=base_options) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(self.test_image) + # Comparing results. + self._assert_actual_result_approximately_matches_expected_result( + recognition_result, expected_recognition_result) + + def test_recognize_succeeds_with_num_hands(self): + # Creates gesture recognizer. + base_options = _BaseOptions(model_asset_path=self.model_path) + options = _GestureRecognizerOptions(base_options=base_options, num_hands=2) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Load the pointing up rotated image. + test_image = _Image.create_from_file( + test_utils.get_test_data_path(_TWO_HANDS_IMAGE)) + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(test_image) + # Comparing results. + self.assertLen(recognition_result.handedness, 2) + + def test_recognize_succeeds_with_rotation(self): + # Creates gesture recognizer. + base_options = _BaseOptions(model_asset_path=self.model_path) + options = _GestureRecognizerOptions(base_options=base_options, num_hands=1) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Load the pointing up rotated image. + test_image = _Image.create_from_file( + test_utils.get_test_data_path(_POINTING_UP_ROTATED_IMAGE)) + # Set rotation parameters using ImageProcessingOptions. + image_processing_options = _ImageProcessingOptions(rotation_degrees=-90) + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(test_image, + image_processing_options) + expected_recognition_result = _get_expected_gesture_recognition_result( + _POINTING_UP_LANDMARKS, _POINTING_UP_LABEL, _POINTING_UP_INDEX) + # Comparing results. + self._assert_actual_result_approximately_matches_expected_result( + recognition_result, expected_recognition_result) + + def test_recognize_fails_with_region_of_interest(self): + # Creates gesture recognizer. + base_options = _BaseOptions(model_asset_path=self.model_path) + options = _GestureRecognizerOptions(base_options=base_options, num_hands=1) + with self.assertRaisesRegex( + ValueError, "This task doesn't support region-of-interest."): + with _GestureRecognizer.create_from_options(options) as recognizer: + # Set the `region_of_interest` parameter using `ImageProcessingOptions`. + image_processing_options = _ImageProcessingOptions( + region_of_interest=_Rect(0, 0, 1, 1)) + # Attempt to perform hand gesture recognition on the cropped input. + recognizer.recognize(self.test_image, image_processing_options) + + def test_empty_recognition_outputs(self): + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path)) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Load the image with no hands. + no_hands_test_image = _Image.create_from_file( + test_utils.get_test_data_path(_NO_HANDS_IMAGE)) + # Performs gesture recognition on the input. + recognition_result = recognizer.recognize(no_hands_test_image) + self.assertEmpty(recognition_result.hand_landmarks) + self.assertEmpty(recognition_result.hand_world_landmarks) + self.assertEmpty(recognition_result.handedness) + self.assertEmpty(recognition_result.gestures) + + def test_missing_result_callback(self): + options = _GestureRecognizerOptions( + 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 _GestureRecognizer.create_from_options(options) as unused_recognizer: + pass + + @parameterized.parameters((_RUNNING_MODE.IMAGE), (_RUNNING_MODE.VIDEO)) + def test_illegal_result_callback(self, running_mode): + options = _GestureRecognizerOptions( + 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 _GestureRecognizer.create_from_options(options) as unused_recognizer: + pass + + def test_calling_recognize_for_video_in_image_mode(self): + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.IMAGE) + with _GestureRecognizer.create_from_options(options) as recognizer: + with self.assertRaisesRegex(ValueError, + r'not initialized with the video mode'): + recognizer.recognize_for_video(self.test_image, 0) + + def test_calling_recognize_async_in_image_mode(self): + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.IMAGE) + with _GestureRecognizer.create_from_options(options) as recognizer: + with self.assertRaisesRegex(ValueError, + r'not initialized with the live stream mode'): + recognizer.recognize_async(self.test_image, 0) + + def test_calling_recognize_in_video_mode(self): + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _GestureRecognizer.create_from_options(options) as recognizer: + with self.assertRaisesRegex(ValueError, + r'not initialized with the image mode'): + recognizer.recognize(self.test_image) + + def test_calling_recognize_async_in_video_mode(self): + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _GestureRecognizer.create_from_options(options) as recognizer: + with self.assertRaisesRegex(ValueError, + r'not initialized with the live stream mode'): + recognizer.recognize_async(self.test_image, 0) + + def test_recognize_for_video_with_out_of_order_timestamp(self): + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _GestureRecognizer.create_from_options(options) as recognizer: + unused_result = recognizer.recognize_for_video(self.test_image, 1) + with self.assertRaisesRegex( + ValueError, r'Input timestamp must be monotonically increasing'): + recognizer.recognize_for_video(self.test_image, 0) + + def test_recognize_for_video(self): + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.VIDEO) + with _GestureRecognizer.create_from_options(options) as recognizer: + for timestamp in range(0, 300, 30): + recognition_result = recognizer.recognize_for_video(self.test_image, + timestamp) + expected_recognition_result = _get_expected_gesture_recognition_result( + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX) + self._assert_actual_result_approximately_matches_expected_result( + recognition_result, expected_recognition_result) + + def test_calling_recognize_in_live_stream_mode(self): + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=mock.MagicMock()) + with _GestureRecognizer.create_from_options(options) as recognizer: + with self.assertRaisesRegex(ValueError, + r'not initialized with the image mode'): + recognizer.recognize(self.test_image) + + def test_calling_recognize_for_video_in_live_stream_mode(self): + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=mock.MagicMock()) + with _GestureRecognizer.create_from_options(options) as recognizer: + with self.assertRaisesRegex(ValueError, + r'not initialized with the video mode'): + recognizer.recognize_for_video(self.test_image, 0) + + def test_recognize_async_calls_with_illegal_timestamp(self): + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=mock.MagicMock()) + with _GestureRecognizer.create_from_options(options) as recognizer: + recognizer.recognize_async(self.test_image, 100) + with self.assertRaisesRegex( + ValueError, r'Input timestamp must be monotonically increasing'): + recognizer.recognize_async(self.test_image, 0) + + @parameterized.parameters( + (_THUMB_UP_IMAGE, _get_expected_gesture_recognition_result( + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX)), + (_NO_HANDS_IMAGE, _GestureRecognitionResult([], [], [], []))) + def test_recognize_async_calls(self, image_path, expected_result): + test_image = _Image.create_from_file( + test_utils.get_test_data_path(image_path)) + observed_timestamp_ms = -1 + + def check_result(result: _GestureRecognitionResult, output_image: _Image, + timestamp_ms: int): + if result.hand_landmarks and result.hand_world_landmarks and \ + result.handedness and result.gestures: + self._assert_actual_result_approximately_matches_expected_result( + result, expected_result) + else: + self.assertEqual(result, expected_result) + 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 + + options = _GestureRecognizerOptions( + base_options=_BaseOptions(model_asset_path=self.model_path), + running_mode=_RUNNING_MODE.LIVE_STREAM, + result_callback=check_result) + with _GestureRecognizer.create_from_options(options) as recognizer: + for timestamp in range(0, 300, 30): + recognizer.recognize_async(test_image, timestamp) + if __name__ == '__main__': absltest.main() diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 9a9ca342..3b2a7e50 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -52,7 +52,6 @@ py_library( "//mediapipe/tasks/cc/vision/hand_detector/proto:hand_detector_graph_options_py_pb2", "//mediapipe/tasks/cc/vision/hand_landmarker/proto:hand_landmarker_graph_options_py_pb2", "//mediapipe/tasks/cc/vision/hand_landmarker/proto:hand_landmarks_detector_graph_options_py_pb2", - "//mediapipe/tasks/python/components/containers:rect", "//mediapipe/tasks/python/components/containers:classification", "//mediapipe/tasks/python/components/containers:landmark", "//mediapipe/tasks/python/components/processors:classifier_options", diff --git a/mediapipe/tasks/python/vision/core/BUILD b/mediapipe/tasks/python/vision/core/BUILD index df1b06f4..ddb7c024 100644 --- a/mediapipe/tasks/python/vision/core/BUILD +++ b/mediapipe/tasks/python/vision/core/BUILD @@ -23,6 +23,14 @@ py_library( srcs = ["vision_task_running_mode.py"], ) +py_library( + name = "image_processing_options", + srcs = ["image_processing_options.py"], + deps = [ + "//mediapipe/tasks/python/components/containers:rect", + ], +) + py_library( name = "base_vision_task_api", srcs = [ @@ -30,6 +38,7 @@ py_library( ], deps = [ ":vision_task_running_mode", + ":image_processing_options", "//mediapipe/framework:calculator_py_pb2", "//mediapipe/python:_framework_bindings", "//mediapipe/tasks/python/core:optional_dependencies", diff --git a/mediapipe/tasks/python/vision/core/base_vision_task_api.py b/mediapipe/tasks/python/vision/core/base_vision_task_api.py index b2f8a366..be290c83 100644 --- a/mediapipe/tasks/python/vision/core/base_vision_task_api.py +++ b/mediapipe/tasks/python/vision/core/base_vision_task_api.py @@ -13,17 +13,22 @@ # limitations under the License. """MediaPipe vision task base api.""" +import math from typing import Callable, Mapping, Optional from mediapipe.framework import calculator_pb2 from mediapipe.python._framework_bindings import packet as packet_module from mediapipe.python._framework_bindings import task_runner as task_runner_module from mediapipe.tasks.python.core.optional_dependencies import doc_controls +from mediapipe.tasks.python.components.containers import rect as rect_module from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module +from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module _TaskRunner = task_runner_module.TaskRunner _Packet = packet_module.Packet +_NormalizedRect = rect_module.NormalizedRect _RunningMode = running_mode_module.VisionTaskRunningMode +_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions class BaseVisionTaskApi(object): @@ -122,6 +127,50 @@ class BaseVisionTaskApi(object): + self._running_mode.name) self._runner.send(inputs) + @staticmethod + def convert_to_normalized_rect( + options: _ImageProcessingOptions, + roi_allowed: bool = True + ) -> _NormalizedRect: + """ + Convert from ImageProcessingOptions to NormalizedRect, performing sanity + checks on-the-fly. If the input ImageProcessingOptions is not present, + returns a default NormalizedRect covering the whole image with rotation set + to 0. If 'roi_allowed' is false, an error will be returned if the input + ImageProcessingOptions has its 'region_of_interest' field set. + + Args: + options: Options for image processing. + roi_allowed: Indicates if the `region_of_interest` field is allowed to be + set. By default, it's set to True. + + """ + normalized_rect = _NormalizedRect(rotation=0, x_center=0.5, y_center=0.5, + width=1, height=1) + if options is None: + return normalized_rect + + if options.rotation_degrees % 90 != 0: + raise ValueError("Expected rotation to be a multiple of 90°.") + + # Convert to radians counter-clockwise. + normalized_rect.rotation = -options.rotation_degrees * math.pi / 180.0 + + if options.region_of_interest: + if not roi_allowed: + raise ValueError("This task doesn't support region-of-interest.") + roi = options.region_of_interest + if roi.x_center >= roi.width or roi.y_center >= roi.height: + raise ValueError( + "Expected Rect with x_center < width and y_center < height.") + if roi.x_center < 0 or roi.y_center < 0 or roi.width > 1 or roi.height > 1: + raise ValueError("Expected Rect values to be in [0,1].") + normalized_rect.x_center = roi.x_center + roi.width / 2.0 + normalized_rect.y_center = roi.y_center + roi.height / 2.0 + normalized_rect.width = roi.width - roi.x_center + normalized_rect.height = roi.height - roi.y_center + return normalized_rect + def close(self) -> None: """Shuts down the mediapipe vision task instance. diff --git a/mediapipe/tasks/python/vision/core/image_processing_options.py b/mediapipe/tasks/python/vision/core/image_processing_options.py new file mode 100644 index 00000000..2a3a1308 --- /dev/null +++ b/mediapipe/tasks/python/vision/core/image_processing_options.py @@ -0,0 +1,39 @@ +# 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 vision options for image processing.""" + +import dataclasses +from typing import Optional + +from mediapipe.tasks.python.components.containers import rect as rect_module + + +@dataclasses.dataclass +class ImageProcessingOptions: + """Options for image processing. + + If both region-of-interest and rotation are specified, the crop around the + region-of-interest is extracted first, then the specified rotation is applied + to the crop. + + Attributes: + region_of_interest: The optional region-of-interest to crop from the image. + If not specified, the full image is used. Coordinates must be in [0,1] + with 'left' < 'right' and 'top' < bottom. + rotation_degress: The rotation to apply to the image (or cropped + region-of-interest), in degrees clockwise. The rotation must be a + multiple (positive or negative) of 90°. + """ + region_of_interest: Optional[rect_module.Rect] = None + rotation_degrees: int = 0 diff --git a/mediapipe/tasks/python/vision/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py index c00508b3..0036aa87 100644 --- a/mediapipe/tasks/python/vision/gesture_recognizer.py +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -27,7 +27,6 @@ from mediapipe.tasks.cc.vision.gesture_recognizer.proto import hand_gesture_reco from mediapipe.tasks.cc.vision.hand_detector.proto import hand_detector_graph_options_pb2 from mediapipe.tasks.cc.vision.hand_landmarker.proto import hand_landmarker_graph_options_pb2 from mediapipe.tasks.cc.vision.hand_landmarker.proto import hand_landmarks_detector_graph_options_pb2 -from mediapipe.tasks.python.components.containers import rect as rect_module from mediapipe.tasks.python.components.containers import classification as classification_module from mediapipe.tasks.python.components.containers import landmark as landmark_module from mediapipe.tasks.python.components.processors import classifier_options @@ -36,8 +35,8 @@ 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 vision_task_running_mode as running_mode_module +from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module -_NormalizedRect = rect_module.NormalizedRect _BaseOptions = base_options_module.BaseOptions _GestureClassifierGraphOptionsProto = gesture_classifier_graph_options_pb2.GestureClassifierGraphOptions _GestureRecognizerGraphOptionsProto = gesture_recognizer_graph_options_pb2.GestureRecognizerGraphOptions @@ -47,6 +46,7 @@ _HandLandmarkerGraphOptionsProto = hand_landmarker_graph_options_pb2.HandLandmar _HandLandmarksDetectorGraphOptionsProto = hand_landmarks_detector_graph_options_pb2.HandLandmarksDetectorGraphOptions _ClassifierOptions = classifier_options.ClassifierOptions _RunningMode = running_mode_module.VisionTaskRunningMode +_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _TaskInfo = task_info_module.TaskInfo _TaskRunner = task_runner_module.TaskRunner @@ -67,11 +67,6 @@ _TASK_GRAPH_NAME = 'mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerG _MICRO_SECONDS_PER_MILLISECOND = 1000 -def _build_full_image_norm_rect() -> _NormalizedRect: - # Builds a NormalizedRect covering the entire image. - return _NormalizedRect(x_center=0.5, y_center=0.5, width=1, height=1) - - @dataclasses.dataclass class GestureRecognitionResult: """The gesture recognition result from GestureRecognizer, where each vector @@ -278,7 +273,7 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): def recognize( self, image: image_module.Image, - roi: Optional[_NormalizedRect] = None + image_processing_options: Optional[_ImageProcessingOptions] = None ) -> GestureRecognitionResult: """Performs hand gesture recognition on the given image. Only use this method when the GestureRecognizer is created with the image running mode. @@ -289,7 +284,7 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): Args: image: MediaPipe Image. - roi: The region of interest. + image_processing_options: Options for image processing. Returns: The hand gesture recognition results. @@ -298,11 +293,16 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): ValueError: If any of the input arguments is invalid. RuntimeError: If gesture recognition failed to run. """ - norm_rect = roi if roi is not None else _build_full_image_norm_rect() + 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( - norm_rect.to_pb2())}) + normalized_rect.to_pb2())}) + + if output_packets[_HAND_GESTURE_STREAM_NAME].is_empty(): + return GestureRecognitionResult([], [], [], []) + gestures_proto_list = packet_getter.get_proto_list( output_packets[_HAND_GESTURE_STREAM_NAME]) handedness_proto_list = packet_getter.get_proto_list( @@ -331,7 +331,7 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): def recognize_for_video( self, image: image_module.Image, timestamp_ms: int, - roi: Optional[_NormalizedRect] = None + image_processing_options: Optional[_ImageProcessingOptions] = None ) -> GestureRecognitionResult: """Performs gesture recognition on the provided video frame. Only use this method when the GestureRecognizer is created with the video running mode. @@ -344,7 +344,7 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): Args: image: MediaPipe Image. timestamp_ms: The timestamp of the input video frame in milliseconds. - roi: The region of interest. + image_processing_options: Options for image processing. Returns: The hand gesture recognition results. @@ -353,14 +353,19 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): ValueError: If any of the input arguments is invalid. RuntimeError: If gesture recognition failed to run. """ - norm_rect = roi if roi is not None else _build_full_image_norm_rect() + 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( - norm_rect.to_pb2()).at( + normalized_rect.to_pb2()).at( timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) }) + + if output_packets[_HAND_GESTURE_STREAM_NAME].is_empty(): + return GestureRecognitionResult([], [], [], []) + gestures_proto_list = packet_getter.get_proto_list( output_packets[_HAND_GESTURE_STREAM_NAME]) handedness_proto_list = packet_getter.get_proto_list( @@ -390,7 +395,7 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): self, image: image_module.Image, timestamp_ms: int, - roi: Optional[_NormalizedRect] = None + image_processing_options: Optional[_ImageProcessingOptions] = None ) -> None: """Sends live image data to perform gesture recognition, and the results will be available via the "result_callback" provided in the @@ -415,17 +420,18 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): Args: image: MediaPipe Image. timestamp_ms: The timestamp of the input image in milliseconds. - roi: The region of interest. + image_processing_options: Options for image processing. Raises: ValueError: If the current input timestamp is smaller than what the gesture recognizer has already processed. """ - norm_rect = roi if roi is not None else _build_full_image_norm_rect() + 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( - norm_rect.to_pb2()).at( + normalized_rect.to_pb2()).at( timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) }) From 75af46d2739245bb46de9fd30e541e2b6de3b077 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Tue, 25 Oct 2022 23:13:12 -0700 Subject: [PATCH 04/16] Revised API to align with recent changes --- .../python/components/containers/classification.py | 10 ++-------- .../python/test/vision/gesture_recognizer_test.py | 2 +- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/mediapipe/tasks/python/components/containers/classification.py b/mediapipe/tasks/python/components/containers/classification.py index 465e2dd2..a9225e80 100644 --- a/mediapipe/tasks/python/components/containers/classification.py +++ b/mediapipe/tasks/python/components/containers/classification.py @@ -85,8 +85,6 @@ class ClassificationList: """ classifications: List[Classification] - tensor_index: Optional[int] = None - tensor_name: Optional[str] = None @doc_controls.do_not_generate_docs def to_pb2(self) -> _ClassificationListProto: @@ -95,9 +93,7 @@ class ClassificationList: classification=[ classification.to_pb2() for classification in self.classifications - ], - tensor_index=self.tensor_index, - tensor_name=self.tensor_name) + ]) @classmethod @doc_controls.do_not_generate_docs @@ -110,9 +106,7 @@ class ClassificationList: classifications=[ Classification.create_from_pb2(classification) for classification in pb2_obj.classification - ], - tensor_index=pb2_obj.tensor_index, - tensor_name=pb2_obj.tensor_name) + ]) def __eq__(self, other: Any) -> bool: """Checks if this object is equal to the given object. diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index a8316c52..3bf994a1 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -80,7 +80,7 @@ def _get_expected_gesture_recognition_result( classifications=[ _Classification(label=gesture_label, index=gesture_index, display_name='') - ], tensor_index=0, tensor_name='') + ]) return _GestureRecognitionResult( gestures=[gesture], handedness=[landmarks_detection_result.classifications], From fbf7ba6f1a5259c93ff3b32a968643e2f7b4b454 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Tue, 25 Oct 2022 23:15:16 -0700 Subject: [PATCH 05/16] Reverted some changes to rect --- mediapipe/tasks/python/components/containers/rect.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/mediapipe/tasks/python/components/containers/rect.py b/mediapipe/tasks/python/components/containers/rect.py index 4b943a55..51056159 100644 --- a/mediapipe/tasks/python/components/containers/rect.py +++ b/mediapipe/tasks/python/components/containers/rect.py @@ -26,6 +26,7 @@ _NormalizedRectProto = rect_pb2.NormalizedRect @dataclasses.dataclass class Rect: """A rectangle with rotation in image coordinates. + Attributes: x_center : The X coordinate of the top-left corner, in pixels. y_center : The Y coordinate of the top-left corner, in pixels. width: The width of the rectangle, in pixels. @@ -80,8 +81,11 @@ class Rect: @dataclasses.dataclass class NormalizedRect: """A rectangle with rotation in normalized coordinates. + The values of box + center location and size are within [0, 1]. + Attributes: x_center : The X normalized coordinate of the top-left corner. y_center : The Y normalized coordinate of the top-left corner. width: The width of the rectangle. From b81b5a90354b079fd564aa23d31008e43377a2d3 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Fri, 28 Oct 2022 01:38:15 -0700 Subject: [PATCH 06/16] Added a test for min_gesture_confidence --- .../test/vision/gesture_recognizer_test.py | 18 ++++++++++++++++++ .../vision/core/image_processing_options.py | 2 +- .../tasks/python/vision/gesture_recognizer.py | 8 ++++---- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index 3bf994a1..cbee1817 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -224,6 +224,24 @@ class GestureRecognizerTest(parameterized.TestCase): self._assert_actual_result_approximately_matches_expected_result( recognition_result, expected_recognition_result) + def test_recognize_succeeds_with_min_gesture_confidence(self): + # Creates gesture recognizer. + base_options = _BaseOptions(model_asset_path=self.model_path) + options = _GestureRecognizerOptions(base_options=base_options, + min_gesture_confidence=2) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(self.test_image) + expected_result = _get_expected_gesture_recognition_result( + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX) + # Only contains one top scoring gesture. + self.assertLen(recognition_result.gestures[0].classifications, 1) + # Actual gesture with top score matches expected gesture. + actual_top_gesture = recognition_result.gestures[0].classifications[0] + expected_top_gesture = expected_result.gestures[0].classifications[0] + self.assertEqual(actual_top_gesture.index, expected_top_gesture.index) + self.assertEqual(actual_top_gesture.label, expected_top_gesture.label) + def test_recognize_succeeds_with_num_hands(self): # Creates gesture recognizer. base_options = _BaseOptions(model_asset_path=self.model_path) diff --git a/mediapipe/tasks/python/vision/core/image_processing_options.py b/mediapipe/tasks/python/vision/core/image_processing_options.py index 2a3a1308..1a519809 100644 --- a/mediapipe/tasks/python/vision/core/image_processing_options.py +++ b/mediapipe/tasks/python/vision/core/image_processing_options.py @@ -30,7 +30,7 @@ class ImageProcessingOptions: Attributes: region_of_interest: The optional region-of-interest to crop from the image. If not specified, the full image is used. Coordinates must be in [0,1] - with 'left' < 'right' and 'top' < bottom. + with 'x_center' < 'width' and 'y_center' < height. rotation_degress: The rotation to apply to the image (or cropped region-of-interest), in degrees clockwise. The rotation must be a multiple (positive or negative) of 90°. diff --git a/mediapipe/tasks/python/vision/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py index 0036aa87..11cb5c7b 100644 --- a/mediapipe/tasks/python/vision/gesture_recognizer.py +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -118,10 +118,10 @@ class GestureRecognizerOptions: base_options: _BaseOptions running_mode: _RunningMode = _RunningMode.IMAGE num_hands: Optional[int] = 1 - min_hand_detection_confidence: Optional[int] = 0.5 - min_hand_presence_confidence: Optional[int] = 0.5 - min_tracking_confidence: Optional[int] = 0.5 - min_gesture_confidence: Optional[int] = -1 + min_hand_detection_confidence: Optional[float] = 0.5 + min_hand_presence_confidence: Optional[float] = 0.5 + min_tracking_confidence: Optional[float] = 0.5 + min_gesture_confidence: Optional[float] = -1 result_callback: Optional[ Callable[[GestureRecognitionResult, image_module.Image, int], None]] = None From f62cfd169005a37362a8d177a3e36372b14aa791 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Sun, 30 Oct 2022 08:23:14 -0700 Subject: [PATCH 07/16] Removed classification proto to use the existing category dataclass instead and removed NormalizedLandmarkList and LandmarkList dataclasses --- .../tasks/python/components/containers/BUILD | 13 +- .../python/components/containers/category.py | 10 +- .../components/containers/classification.py | 121 ------------------ .../python/components/containers/landmark.py | 96 -------------- .../containers/landmark_detection_result.py | 61 ++++++--- mediapipe/tasks/python/test/vision/BUILD | 2 +- .../test/vision/gesture_recognizer_test.py | 49 ++++--- mediapipe/tasks/python/vision/BUILD | 2 +- .../tasks/python/vision/gesture_recognizer.py | 76 +++++++---- 9 files changed, 127 insertions(+), 303 deletions(-) delete mode 100644 mediapipe/tasks/python/components/containers/classification.py diff --git a/mediapipe/tasks/python/components/containers/BUILD b/mediapipe/tasks/python/components/containers/BUILD index 85f5b61c..de3b7352 100644 --- a/mediapipe/tasks/python/components/containers/BUILD +++ b/mediapipe/tasks/python/components/containers/BUILD @@ -36,15 +36,6 @@ py_library( ], ) -py_library( - name = "classification", - srcs = ["classification.py"], - deps = [ - "//mediapipe/framework/formats:classification_py_pb2", - "//mediapipe/tasks/python/core:optional_dependencies", - ], -) - py_library( name = "landmark", srcs = ["landmark.py"], @@ -59,9 +50,11 @@ py_library( srcs = ["landmark_detection_result.py"], deps = [ ":rect", - ":classification", ":landmark", + "//mediapipe/framework/formats:classification_py_pb2", + "//mediapipe/framework/formats:landmark_py_pb2", "//mediapipe/tasks/cc/components/containers/proto:landmarks_detection_result_py_pb2", + "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/core:optional_dependencies", ], ) diff --git a/mediapipe/tasks/python/components/containers/category.py b/mediapipe/tasks/python/components/containers/category.py index 0b347fc1..cfdb8374 100644 --- a/mediapipe/tasks/python/components/containers/category.py +++ b/mediapipe/tasks/python/components/containers/category.py @@ -14,7 +14,7 @@ """Category data class.""" import dataclasses -from typing import Any +from typing import Any, Optional from mediapipe.tasks.cc.components.containers.proto import category_pb2 from mediapipe.tasks.python.core.optional_dependencies import doc_controls @@ -39,10 +39,10 @@ class Category: category_name: The label of this category object. """ - index: int - score: float - display_name: str - category_name: str + index: Optional[int] = None + score: Optional[float] = None + display_name: Optional[str] = None + category_name: Optional[str] = None @doc_controls.do_not_generate_docs def to_pb2(self) -> _CategoryProto: diff --git a/mediapipe/tasks/python/components/containers/classification.py b/mediapipe/tasks/python/components/containers/classification.py deleted file mode 100644 index a9225e80..00000000 --- a/mediapipe/tasks/python/components/containers/classification.py +++ /dev/null @@ -1,121 +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. -"""Classification data class.""" - -import dataclasses -from typing import Any, List, Optional - -from mediapipe.framework.formats import classification_pb2 -from mediapipe.tasks.python.core.optional_dependencies import doc_controls - -_ClassificationProto = classification_pb2.Classification -_ClassificationListProto = classification_pb2.ClassificationList - - -@dataclasses.dataclass -class Classification: - """A classification. - - Attributes: - index: The index of the class in the corresponding label map. - score: The probability score for this class. - label_name: Label or name of the class. - display_name: Optional human-readable string for display purposes. - """ - - index: Optional[int] = None - score: Optional[float] = None - label: Optional[str] = None - display_name: Optional[str] = None - - @doc_controls.do_not_generate_docs - def to_pb2(self) -> _ClassificationProto: - """Generates a Classification protobuf object.""" - return _ClassificationProto( - index=self.index, - score=self.score, - label=self.label, - display_name=self.display_name) - - @classmethod - @doc_controls.do_not_generate_docs - def create_from_pb2(cls, pb2_obj: _ClassificationProto) -> 'Classification': - """Creates a `Classification` object from the given protobuf object.""" - return Classification( - index=pb2_obj.index, - score=pb2_obj.score, - label=pb2_obj.label, - display_name=pb2_obj.display_name) - - 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, Classification): - return False - - return self.to_pb2().__eq__(other.to_pb2()) - - -@dataclasses.dataclass -class ClassificationList: - """Represents the classifications for a given classifier. - Attributes: - classification : A list of `Classification` objects. - tensor_index: Optional index of the tensor that produced these - classifications. - tensor_name: Optional name of the tensor that produced these - classifications tensor metadata name. - """ - - classifications: List[Classification] - - @doc_controls.do_not_generate_docs - def to_pb2(self) -> _ClassificationListProto: - """Generates a ClassificationList protobuf object.""" - return _ClassificationListProto( - classification=[ - classification.to_pb2() - for classification in self.classifications - ]) - - @classmethod - @doc_controls.do_not_generate_docs - def create_from_pb2( - cls, - pb2_obj: _ClassificationListProto - ) -> 'ClassificationList': - """Creates a `ClassificationList` object from the given protobuf object.""" - return ClassificationList( - classifications=[ - Classification.create_from_pb2(classification) - for classification in pb2_obj.classification - ]) - - 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, ClassificationList): - return False - - return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/components/containers/landmark.py b/mediapipe/tasks/python/components/containers/landmark.py index a86c17f2..2c87ee67 100644 --- a/mediapipe/tasks/python/components/containers/landmark.py +++ b/mediapipe/tasks/python/components/containers/landmark.py @@ -20,9 +20,7 @@ from mediapipe.framework.formats import landmark_pb2 from mediapipe.tasks.python.core.optional_dependencies import doc_controls _LandmarkProto = landmark_pb2.Landmark -_LandmarkListProto = landmark_pb2.LandmarkList _NormalizedLandmarkProto = landmark_pb2.NormalizedLandmark -_NormalizedLandmarkListProto = landmark_pb2.NormalizedLandmarkList @dataclasses.dataclass @@ -89,53 +87,6 @@ class Landmark: return self.to_pb2().__eq__(other.to_pb2()) -@dataclasses.dataclass -class LandmarkList: - """Represents the list of landmarks. - - Attributes: - landmarks : A list of `Landmark` objects. - """ - - landmarks: List[Landmark] - - @doc_controls.do_not_generate_docs - def to_pb2(self) -> _LandmarkListProto: - """Generates a LandmarkList protobuf object.""" - return _LandmarkListProto( - landmark=[ - landmark.to_pb2() - for landmark in self.landmarks - ] - ) - - @classmethod - @doc_controls.do_not_generate_docs - def create_from_pb2( - cls, - pb2_obj: _LandmarkListProto - ) -> 'LandmarkList': - """Creates a `LandmarkList` object from the given protobuf object.""" - return LandmarkList( - landmarks=[ - Landmark.create_from_pb2(landmark) - for landmark in pb2_obj.landmark - ] - ) - - 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, LandmarkList): - return False - - return self.to_pb2().__eq__(other.to_pb2()) - - @dataclasses.dataclass class NormalizedLandmark: """A normalized version of above Landmark proto. @@ -201,50 +152,3 @@ class NormalizedLandmark: return False return self.to_pb2().__eq__(other.to_pb2()) - - -@dataclasses.dataclass -class NormalizedLandmarkList: - """Represents the list of normalized landmarks. - - Attributes: - landmarks : A list of `Landmark` objects. - """ - - landmarks: List[NormalizedLandmark] - - @doc_controls.do_not_generate_docs - def to_pb2(self) -> _NormalizedLandmarkListProto: - """Generates a NormalizedLandmarkList protobuf object.""" - return _NormalizedLandmarkListProto( - landmark=[ - landmark.to_pb2() - for landmark in self.landmarks - ] - ) - - @classmethod - @doc_controls.do_not_generate_docs - def create_from_pb2( - cls, - pb2_obj: _NormalizedLandmarkListProto - ) -> 'NormalizedLandmarkList': - """Creates a `NormalizedLandmarkList` object from the given protobuf object.""" - return NormalizedLandmarkList( - landmarks=[ - NormalizedLandmark.create_from_pb2(landmark) - for landmark in pb2_obj.landmark - ] - ) - - 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, NormalizedLandmarkList): - return False - - return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/components/containers/landmark_detection_result.py b/mediapipe/tasks/python/components/containers/landmark_detection_result.py index 02ca5a91..ad21812c 100644 --- a/mediapipe/tasks/python/components/containers/landmark_detection_result.py +++ b/mediapipe/tasks/python/components/containers/landmark_detection_result.py @@ -14,19 +14,25 @@ """Landmarks Detection Result data class.""" import dataclasses -from typing import Any, Optional +from typing import Any, Optional, List from mediapipe.tasks.cc.components.containers.proto import landmarks_detection_result_pb2 +from mediapipe.framework.formats import classification_pb2 +from mediapipe.framework.formats import landmark_pb2 from mediapipe.tasks.python.components.containers import rect as rect_module -from mediapipe.tasks.python.components.containers import classification as classification_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.core.optional_dependencies import doc_controls _LandmarksDetectionResultProto = landmarks_detection_result_pb2.LandmarksDetectionResult +_ClassificationProto = classification_pb2.Classification +_ClassificationListProto = classification_pb2.ClassificationList +_LandmarkListProto = landmark_pb2.LandmarkList +_NormalizedLandmarkListProto = landmark_pb2.NormalizedLandmarkList _NormalizedRect = rect_module.NormalizedRect -_ClassificationList = classification_module.ClassificationList -_NormalizedLandmarkList = landmark_module.NormalizedLandmarkList -_LandmarkList = landmark_module.LandmarkList +_Category = category_module.Category +_NormalizedLandmark = landmark_module.NormalizedLandmark +_Landmark = landmark_module.Landmark @dataclasses.dataclass @@ -34,25 +40,32 @@ class LandmarksDetectionResult: """Represents the landmarks detection result. Attributes: - landmarks : A `NormalizedLandmarkList` object. - classifications : A `ClassificationList` object. - world_landmarks : A `LandmarkList` object. + landmarks : A list of `NormalizedLandmark` objects. + categories : A list of `Category` objects. + world_landmarks : A list of `Landmark` objects. rect : A `NormalizedRect` object. """ - landmarks: Optional[_NormalizedLandmarkList] - classifications: Optional[_ClassificationList] - world_landmarks: Optional[_LandmarkList] + landmarks: Optional[List[_NormalizedLandmark]] + categories: Optional[List[_Category]] + world_landmarks: Optional[List[_Landmark]] rect: _NormalizedRect @doc_controls.do_not_generate_docs def to_pb2(self) -> _LandmarksDetectionResultProto: """Generates a LandmarksDetectionResult protobuf object.""" return _LandmarksDetectionResultProto( - landmarks=self.landmarks.to_pb2(), - classifications=self.classifications.to_pb2(), - world_landmarks=self.world_landmarks.to_pb2(), - rect=self.rect.to_pb2()) + landmarks=_NormalizedLandmarkListProto(landmarks=self.landmarks), + classifications=_ClassificationListProto( + classification=[ + _ClassificationProto( + index=category.index, + score=category.score, + label=category.category_name, + display_name=category.display_name) + for category in self.categories]), + world_landmarks=_LandmarkListProto(landmarks=self.world_landmarks), + rect=self.rect.to_pb2()) @classmethod @doc_controls.do_not_generate_docs @@ -63,11 +76,19 @@ class LandmarksDetectionResult: """Creates a `LandmarksDetectionResult` object from the given protobuf object.""" return LandmarksDetectionResult( - landmarks=_NormalizedLandmarkList.create_from_pb2(pb2_obj.landmarks), - classifications=_ClassificationList.create_from_pb2( - pb2_obj.classifications), - world_landmarks=_LandmarkList.create_from_pb2(pb2_obj.world_landmarks), - rect=_NormalizedRect.create_from_pb2(pb2_obj.rect)) + landmarks=[ + _NormalizedLandmark.create_from_pb2(landmark) + for landmark in pb2_obj.landmarks.landmark], + categories=[category_module.Category( + score=classification.score, + index=classification.index, + category_name=classification.label, + display_name=classification.display_name) + for classification in pb2_obj.classifications.classification], + world_landmarks=[ + _Landmark.create_from_pb2(landmark) + for landmark in pb2_obj.world_landmarks.landmark], + rect=_NormalizedRect.create_from_pb2(pb2_obj.rect)) def __eq__(self, other: Any) -> bool: """Checks if this object is equal to the given object. diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index 5ba91e6a..9b0fab6c 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -69,7 +69,7 @@ py_test( "//mediapipe/python:_framework_bindings", "//mediapipe/tasks/cc/components/containers/proto:landmarks_detection_result_py_pb2", "//mediapipe/tasks/python/components/containers:rect", - "//mediapipe/tasks/python/components/containers:classification", + "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/components/containers:landmark", "//mediapipe/tasks/python/components/containers:landmark_detection_result", "//mediapipe/tasks/python/core:base_options", diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index cbee1817..8f7c6651 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -24,7 +24,7 @@ from absl.testing import parameterized from mediapipe.python._framework_bindings import image as image_module from mediapipe.tasks.cc.components.containers.proto import landmarks_detection_result_pb2 from mediapipe.tasks.python.components.containers import rect as rect_module -from mediapipe.tasks.python.components.containers import classification as classification_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 landmark_detection_result as landmark_detection_result_module from mediapipe.tasks.python.core import base_options as base_options_module @@ -36,12 +36,9 @@ from mediapipe.tasks.python.vision.core import image_processing_options as image _LandmarksDetectionResultProto = landmarks_detection_result_pb2.LandmarksDetectionResult _BaseOptions = base_options_module.BaseOptions _Rect = rect_module.Rect -_Classification = classification_module.Classification -_ClassificationList = classification_module.ClassificationList +_Category = category_module.Category _Landmark = landmark_module.Landmark -_LandmarkList = landmark_module.LandmarkList _NormalizedLandmark = landmark_module.NormalizedLandmark -_NormalizedLandmarkList = landmark_module.NormalizedLandmarkList _LandmarksDetectionResult = landmark_detection_result_module.LandmarksDetectionResult _Image = image_module.Image _GestureRecognizer = gesture_recognizer.GestureRecognizer @@ -76,14 +73,11 @@ def _get_expected_gesture_recognition_result( text_format.Parse(f.read(), landmarks_detection_result_proto) landmarks_detection_result = _LandmarksDetectionResult.create_from_pb2( landmarks_detection_result_proto) - gesture = _ClassificationList( - classifications=[ - _Classification(label=gesture_label, index=gesture_index, - display_name='') - ]) + gesture = _Category(category_name=gesture_label, index=gesture_index, + display_name='') return _GestureRecognitionResult( - gestures=[gesture], - handedness=[landmarks_detection_result.classifications], + gestures=[[gesture]], + handedness=[landmarks_detection_result.categories], hand_landmarks=[landmarks_detection_result.landmarks], hand_world_landmarks=[landmarks_detection_result.world_landmarks]) @@ -115,25 +109,27 @@ class GestureRecognizerTest(parameterized.TestCase): self.assertLen(actual_result.handedness, len(expected_result.handedness)) self.assertLen(actual_result.gestures, len(expected_result.gestures)) # Actual landmarks match expected landmarks. - self.assertLen(actual_result.hand_landmarks[0].landmarks, - len(expected_result.hand_landmarks[0].landmarks)) - actual_landmarks = actual_result.hand_landmarks[0].landmarks - expected_landmarks = expected_result.hand_landmarks[0].landmarks + self.assertLen(actual_result.hand_landmarks[0], + len(expected_result.hand_landmarks[0])) + actual_landmarks = actual_result.hand_landmarks[0] + expected_landmarks = expected_result.hand_landmarks[0] for i in range(len(actual_landmarks)): self.assertAlmostEqual(actual_landmarks[i].x, expected_landmarks[i].x, delta=_LANDMARKS_ERROR_TOLERANCE) self.assertAlmostEqual(actual_landmarks[i].y, expected_landmarks[i].y, delta=_LANDMARKS_ERROR_TOLERANCE) # Actual handedness matches expected handedness. - actual_top_handedness = actual_result.handedness[0].classifications[0] - expected_top_handedness = expected_result.handedness[0].classifications[0] + actual_top_handedness = actual_result.handedness[0][0] + expected_top_handedness = expected_result.handedness[0][0] self.assertEqual(actual_top_handedness.index, expected_top_handedness.index) - self.assertEqual(actual_top_handedness.label, expected_top_handedness.label) + self.assertEqual(actual_top_handedness.category_name, + expected_top_handedness.category_name) # Actual gesture with top score matches expected gesture. - actual_top_gesture = actual_result.gestures[0].classifications[0] - expected_top_gesture = expected_result.gestures[0].classifications[0] + actual_top_gesture = actual_result.gestures[0][0] + expected_top_gesture = expected_result.gestures[0][0] self.assertEqual(actual_top_gesture.index, expected_top_gesture.index) - self.assertEqual(actual_top_gesture.label, expected_top_gesture.label) + self.assertEqual(actual_top_gesture.category_name, + expected_top_gesture.category_name) def test_create_from_file_succeeds_with_valid_model_path(self): # Creates with default option and valid model file successfully. @@ -235,12 +231,13 @@ class GestureRecognizerTest(parameterized.TestCase): expected_result = _get_expected_gesture_recognition_result( _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX) # Only contains one top scoring gesture. - self.assertLen(recognition_result.gestures[0].classifications, 1) + self.assertLen(recognition_result.gestures[0], 1) # Actual gesture with top score matches expected gesture. - actual_top_gesture = recognition_result.gestures[0].classifications[0] - expected_top_gesture = expected_result.gestures[0].classifications[0] + actual_top_gesture = recognition_result.gestures[0][0] + expected_top_gesture = expected_result.gestures[0][0] self.assertEqual(actual_top_gesture.index, expected_top_gesture.index) - self.assertEqual(actual_top_gesture.label, expected_top_gesture.label) + self.assertEqual(actual_top_gesture.category_name, + expected_top_gesture.category_name) def test_recognize_succeeds_with_num_hands(self): # Creates gesture recognizer. diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index fc74911e..f0b3c9f5 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -74,7 +74,7 @@ py_library( "//mediapipe/tasks/cc/vision/hand_detector/proto:hand_detector_graph_options_py_pb2", "//mediapipe/tasks/cc/vision/hand_landmarker/proto:hand_landmarker_graph_options_py_pb2", "//mediapipe/tasks/cc/vision/hand_landmarker/proto:hand_landmarks_detector_graph_options_py_pb2", - "//mediapipe/tasks/python/components/containers:classification", + "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/components/containers:landmark", "//mediapipe/tasks/python/components/processors:classifier_options", "//mediapipe/tasks/python/core:base_options", diff --git a/mediapipe/tasks/python/vision/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py index 11cb5c7b..142eb1dc 100644 --- a/mediapipe/tasks/python/vision/gesture_recognizer.py +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -27,7 +27,7 @@ from mediapipe.tasks.cc.vision.gesture_recognizer.proto import hand_gesture_reco from mediapipe.tasks.cc.vision.hand_detector.proto import hand_detector_graph_options_pb2 from mediapipe.tasks.cc.vision.hand_landmarker.proto import hand_landmarker_graph_options_pb2 from mediapipe.tasks.cc.vision.hand_landmarker.proto import hand_landmarks_detector_graph_options_pb2 -from mediapipe.tasks.python.components.containers import classification as classification_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.processors import classifier_options from mediapipe.tasks.python.core import base_options as base_options_module @@ -80,10 +80,10 @@ class GestureRecognitionResult: hand_world_landmarks: Detected hand landmarks in world coordinates. """ - gestures: List[classification_module.ClassificationList] - handedness: List[classification_module.ClassificationList] - hand_landmarks: List[landmark_module.NormalizedLandmarkList] - hand_world_landmarks: List[landmark_module.LandmarkList] + gestures: List[List[category_module.Category]] + handedness: List[List[category_module.Category]] + hand_landmarks: List[List[landmark_module.NormalizedLandmark]] + hand_world_landmarks: List[List[landmark_module.Landmark]] @dataclasses.dataclass @@ -231,16 +231,26 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): gesture_recognition_result = GestureRecognitionResult( [ - classification_module.ClassificationList.create_from_pb2(gestures) - for gestures in gestures_proto_list + [ + category_module.Category( + index=gesture.index, score=gesture.score, + display_name=gesture.display_name, category_name=gesture.label) + for gesture in gesture_classifications.classification] + for gesture_classifications in gestures_proto_list ], [ - classification_module.ClassificationList.create_from_pb2(handedness) - for handedness in handedness_proto_list + [ + category_module.Category( + index=gesture.index, score=gesture.score, + display_name=gesture.display_name, category_name=gesture.label) + for gesture in handedness_classifications.classification] + for handedness_classifications in handedness_proto_list ], [ - landmark_module.NormalizedLandmarkList.create_from_pb2(hand_landmarks) + [landmark_module.NormalizedLandmark.create_from_pb2(hand_landmark) + for hand_landmark in hand_landmarks.landmark] for hand_landmarks in hand_landmarks_proto_list ], [ - landmark_module.LandmarkList.create_from_pb2(hand_world_landmarks) + [landmark_module.Landmark.create_from_pb2(hand_world_landmark) + for hand_world_landmark in hand_world_landmarks.landmark] for hand_world_landmarks in hand_world_landmarks_proto_list ] ) @@ -314,16 +324,26 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): return GestureRecognitionResult( [ - classification_module.ClassificationList.create_from_pb2(gestures) - for gestures in gestures_proto_list + [ + category_module.Category( + index=gesture.index, score=gesture.score, + display_name=gesture.display_name, category_name=gesture.label) + for gesture in gesture_classifications.classification] + for gesture_classifications in gestures_proto_list ], [ - classification_module.ClassificationList.create_from_pb2(handedness) - for handedness in handedness_proto_list + [ + category_module.Category( + index=gesture.index, score=gesture.score, + display_name=gesture.display_name, category_name=gesture.label) + for gesture in handedness_classifications.classification] + for handedness_classifications in handedness_proto_list ], [ - landmark_module.NormalizedLandmarkList.create_from_pb2(hand_landmarks) + [landmark_module.NormalizedLandmark.create_from_pb2(hand_landmark) + for hand_landmark in hand_landmarks.landmark] for hand_landmarks in hand_landmarks_proto_list ], [ - landmark_module.LandmarkList.create_from_pb2(hand_world_landmarks) + [landmark_module.Landmark.create_from_pb2(hand_world_landmark) + for hand_world_landmark in hand_world_landmarks.landmark] for hand_world_landmarks in hand_world_landmarks_proto_list ] ) @@ -377,16 +397,26 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): return GestureRecognitionResult( [ - classification_module.ClassificationList.create_from_pb2(gestures) - for gestures in gestures_proto_list + [ + category_module.Category( + index=gesture.index, score=gesture.score, + display_name=gesture.display_name, category_name=gesture.label) + for gesture in gesture_classifications.classification] + for gesture_classifications in gestures_proto_list ], [ - classification_module.ClassificationList.create_from_pb2(handedness) - for handedness in handedness_proto_list + [ + category_module.Category( + index=gesture.index, score=gesture.score, + display_name=gesture.display_name, category_name=gesture.label) + for gesture in handedness_classifications.classification] + for handedness_classifications in handedness_proto_list ], [ - landmark_module.NormalizedLandmarkList.create_from_pb2(hand_landmarks) + [landmark_module.NormalizedLandmark.create_from_pb2(hand_landmark) + for hand_landmark in hand_landmarks.landmark] for hand_landmarks in hand_landmarks_proto_list ], [ - landmark_module.LandmarkList.create_from_pb2(hand_world_landmarks) + [landmark_module.Landmark.create_from_pb2(hand_world_landmark) + for hand_world_landmark in hand_world_landmarks.landmark] for hand_world_landmarks in hand_world_landmarks_proto_list ] ) From 4b66599419bd7ffe8bb90db7c7a5533a43004801 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Sun, 30 Oct 2022 09:10:15 -0700 Subject: [PATCH 08/16] Updated docstring in gesture_recognizer --- mediapipe/tasks/python/vision/gesture_recognizer.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mediapipe/tasks/python/vision/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py index 142eb1dc..e8d9ef34 100644 --- a/mediapipe/tasks/python/vision/gesture_recognizer.py +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -444,7 +444,7 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): The `result_callback` provides: - The hand gesture recognition results. - - The input image that the image classifier runs on. + - The input image that the gesture recognizer runs on. - The input timestamp in milliseconds. Args: From fb4872b068b9d34d63997779f3b746d389852fa5 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Sun, 30 Oct 2022 15:42:26 -0700 Subject: [PATCH 09/16] Refactored code and removed some issues --- .../python/components/containers/landmark.py | 40 +---- .../containers/landmark_detection_result.py | 14 +- .../tasks/python/vision/gesture_recognizer.py | 145 +++++------------- 3 files changed, 49 insertions(+), 150 deletions(-) diff --git a/mediapipe/tasks/python/components/containers/landmark.py b/mediapipe/tasks/python/components/containers/landmark.py index 2c87ee67..7eb7d8e9 100644 --- a/mediapipe/tasks/python/components/containers/landmark.py +++ b/mediapipe/tasks/python/components/containers/landmark.py @@ -30,9 +30,9 @@ class Landmark: Use x for 1D points, (x, y) for 2D points and (x, y, z) for 3D points. Attributes: - x: The x coordinate of the 3D point. - y: The y coordinate of the 3D point. - z: The z coordinate of the 3D point. + x: The x coordinate. + y: The y coordinate. + z: The z coordinate. visibility: Landmark visibility. Should stay unset if not supported. Float score of whether landmark is visible or occluded by other objects. Landmark considered as invisible also if it is not present on the screen @@ -72,20 +72,6 @@ class Landmark: visibility=pb2_obj.visibility, presence=pb2_obj.presence) - 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, Landmark): - return False - - return self.to_pb2().__eq__(other.to_pb2()) - @dataclasses.dataclass class NormalizedLandmark: @@ -94,9 +80,9 @@ class NormalizedLandmark: All coordinates should be within [0, 1]. Attributes: - x: The normalized x coordinate of the 3D point. - y: The normalized y coordinate of the 3D point. - z: The normalized z coordinate of the 3D point. + x: The normalized x coordinate. + y: The normalized y coordinate. + z: The normalized z coordinate. visibility: Landmark visibility. Should stay unset if not supported. Float score of whether landmark is visible or occluded by other objects. Landmark considered as invisible also if it is not present on the screen @@ -138,17 +124,3 @@ class NormalizedLandmark: z=pb2_obj.z, visibility=pb2_obj.visibility, presence=pb2_obj.presence) - - 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, NormalizedLandmark): - return False - - return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/components/containers/landmark_detection_result.py b/mediapipe/tasks/python/components/containers/landmark_detection_result.py index ad21812c..7c21733e 100644 --- a/mediapipe/tasks/python/components/containers/landmark_detection_result.py +++ b/mediapipe/tasks/python/components/containers/landmark_detection_result.py @@ -14,7 +14,7 @@ """Landmarks Detection Result data class.""" import dataclasses -from typing import Any, Optional, List +from typing import Optional, List from mediapipe.tasks.cc.components.containers.proto import landmarks_detection_result_pb2 from mediapipe.framework.formats import classification_pb2 @@ -89,15 +89,3 @@ class LandmarksDetectionResult: _Landmark.create_from_pb2(landmark) for landmark in pb2_obj.world_landmarks.landmark], rect=_NormalizedRect.create_from_pb2(pb2_obj.rect)) - - 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, LandmarksDetectionResult): - return False - - return self.to_pb2().__eq__(other.to_pb2()) diff --git a/mediapipe/tasks/python/vision/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py index e8d9ef34..c6d30dc4 100644 --- a/mediapipe/tasks/python/vision/gesture_recognizer.py +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -48,7 +48,6 @@ _ClassifierOptions = classifier_options.ClassifierOptions _RunningMode = running_mode_module.VisionTaskRunningMode _ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _TaskInfo = task_info_module.TaskInfo -_TaskRunner = task_runner_module.TaskRunner _IMAGE_IN_STREAM_NAME = 'image_in' _IMAGE_OUT_STREAM_NAME = 'image_out' @@ -86,6 +85,45 @@ class GestureRecognitionResult: hand_world_landmarks: List[List[landmark_module.Landmark]] +def _build_recognition_result( + output_packets: Mapping[str, packet_module.Packet] +) -> GestureRecognitionResult: + gestures_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_GESTURE_STREAM_NAME]) + handedness_proto_list = packet_getter.get_proto_list( + output_packets[_HANDEDNESS_STREAM_NAME]) + hand_landmarks_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_LANDMARKS_STREAM_NAME]) + hand_world_landmarks_proto_list = packet_getter.get_proto_list( + output_packets[_HAND_WORLD_LANDMARKS_STREAM_NAME]) + + return GestureRecognitionResult( + [ + [ + category_module.Category( + index=gesture.index, score=gesture.score, + display_name=gesture.display_name, category_name=gesture.label) + for gesture in gesture_classifications.classification] + for gesture_classifications in gestures_proto_list + ], [ + [ + category_module.Category( + index=gesture.index, score=gesture.score, + display_name=gesture.display_name, category_name=gesture.label) + for gesture in handedness_classifications.classification] + for handedness_classifications in handedness_proto_list + ], [ + [landmark_module.NormalizedLandmark.create_from_pb2(hand_landmark) + for hand_landmark in hand_landmarks.landmark] + for hand_landmarks in hand_landmarks_proto_list + ], [ + [landmark_module.Landmark.create_from_pb2(hand_world_landmark) + for hand_world_landmark in hand_world_landmarks.landmark] + for hand_world_landmarks in hand_world_landmarks_proto_list + ] + ) + + @dataclasses.dataclass class GestureRecognizerOptions: """Options for the gesture recognizer task. @@ -220,40 +258,7 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): empty_packet.timestamp.value // _MICRO_SECONDS_PER_MILLISECOND) return - gestures_proto_list = packet_getter.get_proto_list( - output_packets[_HAND_GESTURE_STREAM_NAME]) - handedness_proto_list = packet_getter.get_proto_list( - output_packets[_HANDEDNESS_STREAM_NAME]) - hand_landmarks_proto_list = packet_getter.get_proto_list( - output_packets[_HAND_LANDMARKS_STREAM_NAME]) - hand_world_landmarks_proto_list = packet_getter.get_proto_list( - output_packets[_HAND_WORLD_LANDMARKS_STREAM_NAME]) - - gesture_recognition_result = GestureRecognitionResult( - [ - [ - category_module.Category( - index=gesture.index, score=gesture.score, - display_name=gesture.display_name, category_name=gesture.label) - for gesture in gesture_classifications.classification] - for gesture_classifications in gestures_proto_list - ], [ - [ - category_module.Category( - index=gesture.index, score=gesture.score, - display_name=gesture.display_name, category_name=gesture.label) - for gesture in handedness_classifications.classification] - for handedness_classifications in handedness_proto_list - ], [ - [landmark_module.NormalizedLandmark.create_from_pb2(hand_landmark) - for hand_landmark in hand_landmarks.landmark] - for hand_landmarks in hand_landmarks_proto_list - ], [ - [landmark_module.Landmark.create_from_pb2(hand_world_landmark) - for hand_world_landmark in hand_world_landmarks.landmark] - for hand_world_landmarks in hand_world_landmarks_proto_list - ] - ) + gesture_recognition_result = _build_recognition_result(output_packets) timestamp = output_packets[_HAND_GESTURE_STREAM_NAME].timestamp options.result_callback( gesture_recognition_result, image, @@ -313,40 +318,7 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): if output_packets[_HAND_GESTURE_STREAM_NAME].is_empty(): return GestureRecognitionResult([], [], [], []) - gestures_proto_list = packet_getter.get_proto_list( - output_packets[_HAND_GESTURE_STREAM_NAME]) - handedness_proto_list = packet_getter.get_proto_list( - output_packets[_HANDEDNESS_STREAM_NAME]) - hand_landmarks_proto_list = packet_getter.get_proto_list( - output_packets[_HAND_LANDMARKS_STREAM_NAME]) - hand_world_landmarks_proto_list = packet_getter.get_proto_list( - output_packets[_HAND_WORLD_LANDMARKS_STREAM_NAME]) - - return GestureRecognitionResult( - [ - [ - category_module.Category( - index=gesture.index, score=gesture.score, - display_name=gesture.display_name, category_name=gesture.label) - for gesture in gesture_classifications.classification] - for gesture_classifications in gestures_proto_list - ], [ - [ - category_module.Category( - index=gesture.index, score=gesture.score, - display_name=gesture.display_name, category_name=gesture.label) - for gesture in handedness_classifications.classification] - for handedness_classifications in handedness_proto_list - ], [ - [landmark_module.NormalizedLandmark.create_from_pb2(hand_landmark) - for hand_landmark in hand_landmarks.landmark] - for hand_landmarks in hand_landmarks_proto_list - ], [ - [landmark_module.Landmark.create_from_pb2(hand_world_landmark) - for hand_world_landmark in hand_world_landmarks.landmark] - for hand_world_landmarks in hand_world_landmarks_proto_list - ] - ) + return _build_recognition_result(output_packets) def recognize_for_video( self, image: image_module.Image, @@ -386,40 +358,7 @@ class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): if output_packets[_HAND_GESTURE_STREAM_NAME].is_empty(): return GestureRecognitionResult([], [], [], []) - gestures_proto_list = packet_getter.get_proto_list( - output_packets[_HAND_GESTURE_STREAM_NAME]) - handedness_proto_list = packet_getter.get_proto_list( - output_packets[_HANDEDNESS_STREAM_NAME]) - hand_landmarks_proto_list = packet_getter.get_proto_list( - output_packets[_HAND_LANDMARKS_STREAM_NAME]) - hand_world_landmarks_proto_list = packet_getter.get_proto_list( - output_packets[_HAND_WORLD_LANDMARKS_STREAM_NAME]) - - return GestureRecognitionResult( - [ - [ - category_module.Category( - index=gesture.index, score=gesture.score, - display_name=gesture.display_name, category_name=gesture.label) - for gesture in gesture_classifications.classification] - for gesture_classifications in gestures_proto_list - ], [ - [ - category_module.Category( - index=gesture.index, score=gesture.score, - display_name=gesture.display_name, category_name=gesture.label) - for gesture in handedness_classifications.classification] - for handedness_classifications in handedness_proto_list - ], [ - [landmark_module.NormalizedLandmark.create_from_pb2(hand_landmark) - for hand_landmark in hand_landmarks.landmark] - for hand_landmarks in hand_landmarks_proto_list - ], [ - [landmark_module.Landmark.create_from_pb2(hand_world_landmark) - for hand_world_landmark in hand_world_landmarks.landmark] - for hand_world_landmarks in hand_world_landmarks_proto_list - ] - ) + return _build_recognition_result(output_packets) def recognize_async( self, From 19be9e90123f1905a1d0fc1b7fbbe33b9047d0e6 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Mon, 31 Oct 2022 05:34:31 -0700 Subject: [PATCH 10/16] Revised gesture recognizer implementation --- .../test/vision/gesture_recognizer_test.py | 55 +++++++++++++------ mediapipe/tasks/python/vision/BUILD | 3 - .../tasks/python/vision/gesture_recognizer.py | 48 ++++++---------- mediapipe/tasks/testdata/vision/BUILD | 1 + 4 files changed, 57 insertions(+), 50 deletions(-) diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index 8f7c6651..916bd3e0 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -47,22 +47,26 @@ _GestureRecognitionResult = gesture_recognizer.GestureRecognitionResult _RUNNING_MODE = running_mode_module.VisionTaskRunningMode _ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions -_GESTURE_RECOGNIZER_MODEL_FILE = 'gesture_recognizer.task' +_GESTURE_RECOGNIZER_BUNDLE_ASSET_FILE = 'gesture_recognizer.task' +_GESTURE_RECOGNIZER_WITH_CUSTOM_CLASSIFIER_BUNDLE_ASSET_FILE = 'gesture_recognizer_with_custom_classifier.task' _NO_HANDS_IMAGE = 'cats_and_dogs.jpg' _TWO_HANDS_IMAGE = 'right_hands.jpg' +_FIST_IMAGE = 'fist.jpg' +_FIST_LANDMARKS = 'fist_landmarks.pbtxt' +_FIST_LABEL = 'Closed_Fist' _THUMB_UP_IMAGE = 'thumb_up.jpg' _THUMB_UP_LANDMARKS = 'thumb_up_landmarks.pbtxt' _THUMB_UP_LABEL = 'Thumb_Up' -_THUMB_UP_INDEX = 5 _POINTING_UP_ROTATED_IMAGE = 'pointing_up_rotated.jpg' _POINTING_UP_LANDMARKS = 'pointing_up_rotated_landmarks.pbtxt' _POINTING_UP_LABEL = 'Pointing_Up' -_POINTING_UP_INDEX = 3 +_ROCK_LABEL = "Rock" _LANDMARKS_ERROR_TOLERANCE = 0.03 +_GESTURE_EXPECTED_INDEX = -1 def _get_expected_gesture_recognition_result( - file_path: str, gesture_label: str, gesture_index: int + file_path: str, gesture_label: str ) -> _GestureRecognitionResult: landmarks_detection_result_file_path = test_utils.get_test_data_path( file_path) @@ -73,7 +77,8 @@ def _get_expected_gesture_recognition_result( text_format.Parse(f.read(), landmarks_detection_result_proto) landmarks_detection_result = _LandmarksDetectionResult.create_from_pb2( landmarks_detection_result_proto) - gesture = _Category(category_name=gesture_label, index=gesture_index, + gesture = _Category(category_name=gesture_label, + index=_GESTURE_EXPECTED_INDEX, display_name='') return _GestureRecognitionResult( gestures=[[gesture]], @@ -94,7 +99,7 @@ class GestureRecognizerTest(parameterized.TestCase): self.test_image = _Image.create_from_file( test_utils.get_test_data_path(_THUMB_UP_IMAGE)) self.model_path = test_utils.get_test_data_path( - _GESTURE_RECOGNIZER_MODEL_FILE) + _GESTURE_RECOGNIZER_BUNDLE_ASSET_FILE) def _assert_actual_result_approximately_matches_expected_result( self, @@ -127,7 +132,7 @@ class GestureRecognizerTest(parameterized.TestCase): # Actual gesture with top score matches expected gesture. actual_top_gesture = actual_result.gestures[0][0] expected_top_gesture = expected_result.gestures[0][0] - self.assertEqual(actual_top_gesture.index, expected_top_gesture.index) + self.assertEqual(actual_top_gesture.index, _GESTURE_EXPECTED_INDEX) self.assertEqual(actual_top_gesture.category_name, expected_top_gesture.category_name) @@ -163,10 +168,10 @@ class GestureRecognizerTest(parameterized.TestCase): @parameterized.parameters( (ModelFileType.FILE_NAME, _get_expected_gesture_recognition_result( - _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL )), (ModelFileType.FILE_CONTENT, _get_expected_gesture_recognition_result( - _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL ))) def test_recognize(self, model_file_type, expected_recognition_result): # Creates gesture recognizer. @@ -194,10 +199,10 @@ class GestureRecognizerTest(parameterized.TestCase): @parameterized.parameters( (ModelFileType.FILE_NAME, _get_expected_gesture_recognition_result( - _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL )), (ModelFileType.FILE_CONTENT, _get_expected_gesture_recognition_result( - _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL ))) def test_recognize_in_context(self, model_file_type, expected_recognition_result): @@ -224,12 +229,12 @@ class GestureRecognizerTest(parameterized.TestCase): # Creates gesture recognizer. base_options = _BaseOptions(model_asset_path=self.model_path) options = _GestureRecognizerOptions(base_options=base_options, - min_gesture_confidence=2) + min_gesture_confidence=0.5) with _GestureRecognizer.create_from_options(options) as recognizer: # Performs hand gesture recognition on the input. recognition_result = recognizer.recognize(self.test_image) expected_result = _get_expected_gesture_recognition_result( - _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX) + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL) # Only contains one top scoring gesture. self.assertLen(recognition_result.gestures[0], 1) # Actual gesture with top score matches expected gesture. @@ -266,11 +271,29 @@ class GestureRecognizerTest(parameterized.TestCase): recognition_result = recognizer.recognize(test_image, image_processing_options) expected_recognition_result = _get_expected_gesture_recognition_result( - _POINTING_UP_LANDMARKS, _POINTING_UP_LABEL, _POINTING_UP_INDEX) + _POINTING_UP_LANDMARKS, _POINTING_UP_LABEL) # Comparing results. self._assert_actual_result_approximately_matches_expected_result( recognition_result, expected_recognition_result) + def test_recognize_succeeds_with_custom_gesture_fist(self): + # Creates gesture recognizer. + model_path = test_utils.get_test_data_path( + _GESTURE_RECOGNIZER_WITH_CUSTOM_CLASSIFIER_BUNDLE_ASSET_FILE) + base_options = _BaseOptions(model_asset_path=model_path) + options = _GestureRecognizerOptions(base_options=base_options, num_hands=1) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Load the fist image. + test_image = _Image.create_from_file( + test_utils.get_test_data_path(_FIST_IMAGE)) + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(test_image) + expected_recognition_result = _get_expected_gesture_recognition_result( + _FIST_LANDMARKS, _ROCK_LABEL) + # Comparing results. + self._assert_actual_result_approximately_matches_expected_result( + recognition_result, expected_recognition_result) + def test_recognize_fails_with_region_of_interest(self): # Creates gesture recognizer. base_options = _BaseOptions(model_asset_path=self.model_path) @@ -373,7 +396,7 @@ class GestureRecognizerTest(parameterized.TestCase): recognition_result = recognizer.recognize_for_video(self.test_image, timestamp) expected_recognition_result = _get_expected_gesture_recognition_result( - _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX) + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL) self._assert_actual_result_approximately_matches_expected_result( recognition_result, expected_recognition_result) @@ -410,7 +433,7 @@ class GestureRecognizerTest(parameterized.TestCase): @parameterized.parameters( (_THUMB_UP_IMAGE, _get_expected_gesture_recognition_result( - _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL, _THUMB_UP_INDEX)), + _THUMB_UP_LANDMARKS, _THUMB_UP_LABEL)), (_NO_HANDS_IMAGE, _GestureRecognitionResult([], [], [], []))) def test_recognize_async_calls(self, image_path, expected_result): test_image = _Image.create_from_file( diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 87de5b98..66c9ece6 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -87,12 +87,9 @@ py_library( "//mediapipe/python:_framework_bindings", "//mediapipe/python:packet_creator", "//mediapipe/python:packet_getter", - "//mediapipe/tasks/cc/vision/gesture_recognizer/proto:gesture_classifier_graph_options_py_pb2", "//mediapipe/tasks/cc/vision/gesture_recognizer/proto:gesture_recognizer_graph_options_py_pb2", "//mediapipe/tasks/cc/vision/gesture_recognizer/proto:hand_gesture_recognizer_graph_options_py_pb2", - "//mediapipe/tasks/cc/vision/hand_detector/proto:hand_detector_graph_options_py_pb2", "//mediapipe/tasks/cc/vision/hand_landmarker/proto:hand_landmarker_graph_options_py_pb2", - "//mediapipe/tasks/cc/vision/hand_landmarker/proto:hand_landmarks_detector_graph_options_py_pb2", "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/components/containers:landmark", "//mediapipe/tasks/python/components/processors:classifier_options", diff --git a/mediapipe/tasks/python/vision/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py index c6d30dc4..9a2e3ba2 100644 --- a/mediapipe/tasks/python/vision/gesture_recognizer.py +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -20,13 +20,9 @@ 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.python._framework_bindings import task_runner as task_runner_module -from mediapipe.tasks.cc.vision.gesture_recognizer.proto import gesture_classifier_graph_options_pb2 from mediapipe.tasks.cc.vision.gesture_recognizer.proto import gesture_recognizer_graph_options_pb2 from mediapipe.tasks.cc.vision.gesture_recognizer.proto import hand_gesture_recognizer_graph_options_pb2 -from mediapipe.tasks.cc.vision.hand_detector.proto import hand_detector_graph_options_pb2 from mediapipe.tasks.cc.vision.hand_landmarker.proto import hand_landmarker_graph_options_pb2 -from mediapipe.tasks.cc.vision.hand_landmarker.proto import hand_landmarks_detector_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.processors import classifier_options @@ -38,12 +34,9 @@ from mediapipe.tasks.python.vision.core import vision_task_running_mode as runni from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module _BaseOptions = base_options_module.BaseOptions -_GestureClassifierGraphOptionsProto = gesture_classifier_graph_options_pb2.GestureClassifierGraphOptions _GestureRecognizerGraphOptionsProto = gesture_recognizer_graph_options_pb2.GestureRecognizerGraphOptions _HandGestureRecognizerGraphOptionsProto = hand_gesture_recognizer_graph_options_pb2.HandGestureRecognizerGraphOptions -_HandDetectorGraphOptionsProto = hand_detector_graph_options_pb2.HandDetectorGraphOptions _HandLandmarkerGraphOptionsProto = hand_landmarker_graph_options_pb2.HandLandmarkerGraphOptions -_HandLandmarksDetectorGraphOptionsProto = hand_landmarks_detector_graph_options_pb2.HandLandmarksDetectorGraphOptions _ClassifierOptions = classifier_options.ClassifierOptions _RunningMode = running_mode_module.VisionTaskRunningMode _ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions @@ -64,6 +57,7 @@ _HAND_WORLD_LANDMARKS_STREAM_NAME = 'world_landmarks' _HAND_WORLD_LANDMARKS_TAG = 'WORLD_LANDMARKS' _TASK_GRAPH_NAME = 'mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph' _MICRO_SECONDS_PER_MILLISECOND = 1000 +_GESTURE_DEFAULT_INDEX = -1 @dataclasses.dataclass @@ -72,8 +66,9 @@ class GestureRecognitionResult: element represents a single hand detected in the image. Attributes: - gestures: Recognized hand gestures with sorted order such that the - winning label is the first item in the list. + gestures: Recognized hand gestures of detected hands. Note that the index + of the gesture is always 0, because the raw indices from multiple gesture + classifiers cannot consolidate to a meaningful index. handedness: Classification of handedness. hand_landmarks: Detected hand landmarks in normalized image coordinates. hand_world_landmarks: Detected hand landmarks in world coordinates. @@ -101,16 +96,16 @@ def _build_recognition_result( [ [ category_module.Category( - index=gesture.index, score=gesture.score, + index=_GESTURE_DEFAULT_INDEX, score=gesture.score, display_name=gesture.display_name, category_name=gesture.label) for gesture in gesture_classifications.classification] for gesture_classifications in gestures_proto_list ], [ [ category_module.Category( - index=gesture.index, score=gesture.score, - display_name=gesture.display_name, category_name=gesture.label) - for gesture in handedness_classifications.classification] + index=handedness.index, score=handedness.score, + display_name=handedness.display_name, category_name=handedness.label) + for handedness in handedness_classifications.classification] for handedness_classifications in handedness_proto_list ], [ [landmark_module.NormalizedLandmark.create_from_pb2(hand_landmark) @@ -170,26 +165,17 @@ class GestureRecognizerOptions: base_options_proto = self.base_options.to_pb2() base_options_proto.use_stream_mode = False if self.running_mode == _RunningMode.IMAGE else True - # Configure hand detector options. - hand_detector_options_proto = _HandDetectorGraphOptionsProto( - num_hands=self.num_hands, - min_detection_confidence=self.min_hand_detection_confidence) - - # Configure hand landmarker options. - hand_landmarks_detector_options_proto = _HandLandmarksDetectorGraphOptionsProto( - min_detection_confidence=self.min_hand_presence_confidence) - hand_landmarker_options_proto = _HandLandmarkerGraphOptionsProto( - hand_detector_graph_options=hand_detector_options_proto, - hand_landmarks_detector_graph_options=hand_landmarks_detector_options_proto, - min_tracking_confidence=self.min_tracking_confidence) + # Configure hand detector and hand landmarker options. + hand_landmarker_options_proto = _HandLandmarkerGraphOptionsProto() + hand_landmarker_options_proto.min_tracking_confidence = self.min_tracking_confidence + hand_landmarker_options_proto.hand_detector_graph_options.num_hands = self.num_hands + hand_landmarker_options_proto.hand_detector_graph_options.min_detection_confidence = self.min_hand_detection_confidence + hand_landmarker_options_proto.hand_landmarks_detector_graph_options.min_detection_confidence = self.min_hand_presence_confidence # Configure hand gesture recognizer options. - classifier_options = _ClassifierOptions( - score_threshold=self.min_gesture_confidence) - gesture_classifier_options = _GestureClassifierGraphOptionsProto( - classifier_options=classifier_options.to_pb2()) - hand_gesture_recognizer_options_proto = _HandGestureRecognizerGraphOptionsProto( - canned_gesture_classifier_graph_options=gesture_classifier_options) + hand_gesture_recognizer_options_proto = _HandGestureRecognizerGraphOptionsProto() + hand_gesture_recognizer_options_proto.canned_gesture_classifier_graph_options.classifier_options.score_threshold = self.min_gesture_confidence + hand_gesture_recognizer_options_proto.custom_gesture_classifier_graph_options.classifier_options.score_threshold = self.min_gesture_confidence return _GestureRecognizerGraphOptionsProto( base_options=base_options_proto, diff --git a/mediapipe/tasks/testdata/vision/BUILD b/mediapipe/tasks/testdata/vision/BUILD index 0545c5cc..c7265f5c 100644 --- a/mediapipe/tasks/testdata/vision/BUILD +++ b/mediapipe/tasks/testdata/vision/BUILD @@ -130,6 +130,7 @@ filegroup( "hand_landmark_lite.tflite", "hand_landmarker.task", "gesture_recognizer.task", + "gesture_recognizer_with_custom_classifier.task", "mobilenet_v1_0.25_192_quantized_1_default_1.tflite", "mobilenet_v1_0.25_224_1_default_1.tflite", "mobilenet_v1_0.25_224_1_metadata_1.tflite", From 888ddd4b74dd1965d386a2e6b34cf7ced99d4a3c Mon Sep 17 00:00:00 2001 From: kinaryml Date: Mon, 31 Oct 2022 05:37:24 -0700 Subject: [PATCH 11/16] Removed unused classifier options proto --- mediapipe/tasks/python/vision/BUILD | 1 - mediapipe/tasks/python/vision/gesture_recognizer.py | 2 -- 2 files changed, 3 deletions(-) diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 66c9ece6..0505471e 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -92,7 +92,6 @@ py_library( "//mediapipe/tasks/cc/vision/hand_landmarker/proto:hand_landmarker_graph_options_py_pb2", "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/components/containers:landmark", - "//mediapipe/tasks/python/components/processors:classifier_options", "//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/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py index 9a2e3ba2..82dc00f1 100644 --- a/mediapipe/tasks/python/vision/gesture_recognizer.py +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -25,7 +25,6 @@ from mediapipe.tasks.cc.vision.gesture_recognizer.proto import hand_gesture_reco from mediapipe.tasks.cc.vision.hand_landmarker.proto import hand_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.processors import classifier_options 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 @@ -37,7 +36,6 @@ _BaseOptions = base_options_module.BaseOptions _GestureRecognizerGraphOptionsProto = gesture_recognizer_graph_options_pb2.GestureRecognizerGraphOptions _HandGestureRecognizerGraphOptionsProto = hand_gesture_recognizer_graph_options_pb2.HandGestureRecognizerGraphOptions _HandLandmarkerGraphOptionsProto = hand_landmarker_graph_options_pb2.HandLandmarkerGraphOptions -_ClassifierOptions = classifier_options.ClassifierOptions _RunningMode = running_mode_module.VisionTaskRunningMode _ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _TaskInfo = task_info_module.TaskInfo From d635b4281e7b7defa9a722162e76e59cebc5e6c9 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Mon, 31 Oct 2022 05:47:28 -0700 Subject: [PATCH 12/16] Added a test for the canned classification of the gesture victory --- .../test/vision/gesture_recognizer_test.py | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index 916bd3e0..9e1b4735 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -53,7 +53,9 @@ _NO_HANDS_IMAGE = 'cats_and_dogs.jpg' _TWO_HANDS_IMAGE = 'right_hands.jpg' _FIST_IMAGE = 'fist.jpg' _FIST_LANDMARKS = 'fist_landmarks.pbtxt' -_FIST_LABEL = 'Closed_Fist' +_VICTORY_IMAGE = 'victory.jpg' +_VICTORY_LANDMARKS = 'victory_landmarks.pbtxt' +_VICTORY_LABEL = 'Victory' _THUMB_UP_IMAGE = 'thumb_up.jpg' _THUMB_UP_LANDMARKS = 'thumb_up_landmarks.pbtxt' _THUMB_UP_LABEL = 'Thumb_Up' @@ -276,6 +278,22 @@ class GestureRecognizerTest(parameterized.TestCase): self._assert_actual_result_approximately_matches_expected_result( recognition_result, expected_recognition_result) + def test_recognize_succeeds_with_canned_gesture_victory(self): + # Creates gesture recognizer. + base_options = _BaseOptions(model_asset_path=self.model_path) + options = _GestureRecognizerOptions(base_options=base_options, num_hands=1) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Load the fist image. + test_image = _Image.create_from_file( + test_utils.get_test_data_path(_VICTORY_IMAGE)) + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(test_image) + expected_recognition_result = _get_expected_gesture_recognition_result( + _VICTORY_LANDMARKS, _VICTORY_LABEL) + # Comparing results. + self._assert_actual_result_approximately_matches_expected_result( + recognition_result, expected_recognition_result) + def test_recognize_succeeds_with_custom_gesture_fist(self): # Creates gesture recognizer. model_path = test_utils.get_test_data_path( From 2b5a07757997cdf85916d0aa023325023418e9bc Mon Sep 17 00:00:00 2001 From: kinaryml Date: Mon, 31 Oct 2022 05:48:45 -0700 Subject: [PATCH 13/16] Updated comments --- mediapipe/tasks/python/test/vision/gesture_recognizer_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index 9e1b4735..e8aa6188 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -283,7 +283,7 @@ class GestureRecognizerTest(parameterized.TestCase): base_options = _BaseOptions(model_asset_path=self.model_path) options = _GestureRecognizerOptions(base_options=base_options, num_hands=1) with _GestureRecognizer.create_from_options(options) as recognizer: - # Load the fist image. + # Load the victory image. test_image = _Image.create_from_file( test_utils.get_test_data_path(_VICTORY_IMAGE)) # Performs hand gesture recognition on the input. From d3b472e888ae7b62b7dd921949b3e9db71c37303 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Mon, 31 Oct 2022 22:16:37 -0700 Subject: [PATCH 14/16] Add allow_list/deny_list support --- mediapipe/tasks/python/test/vision/BUILD | 1 + .../test/vision/gesture_recognizer_test.py | 111 ++++++++++++++++-- mediapipe/tasks/python/vision/BUILD | 3 +- .../tasks/python/vision/gesture_recognizer.py | 41 ++++--- 4 files changed, 127 insertions(+), 29 deletions(-) diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index 40afe22b..da8ad3f8 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -88,6 +88,7 @@ py_test( "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/components/containers:landmark", "//mediapipe/tasks/python/components/containers:landmark_detection_result", + "//mediapipe/tasks/python/components/processors:classifier_options", "//mediapipe/tasks/python/core:base_options", "//mediapipe/tasks/python/test:test_utils", "//mediapipe/tasks/python/vision:gesture_recognizer", diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index e8aa6188..d5cd72cd 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -27,6 +27,7 @@ from mediapipe.tasks.python.components.containers import rect as rect_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 landmark_detection_result as landmark_detection_result_module +from mediapipe.tasks.python.components.processors import classifier_options 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 gesture_recognizer @@ -40,6 +41,7 @@ _Category = category_module.Category _Landmark = landmark_module.Landmark _NormalizedLandmark = landmark_module.NormalizedLandmark _LandmarksDetectionResult = landmark_detection_result_module.LandmarksDetectionResult +_ClassifierOptions = classifier_options.ClassifierOptions _Image = image_module.Image _GestureRecognizer = gesture_recognizer.GestureRecognizer _GestureRecognizerOptions = gesture_recognizer.GestureRecognizerOptions @@ -59,10 +61,12 @@ _VICTORY_LABEL = 'Victory' _THUMB_UP_IMAGE = 'thumb_up.jpg' _THUMB_UP_LANDMARKS = 'thumb_up_landmarks.pbtxt' _THUMB_UP_LABEL = 'Thumb_Up' +_POINTING_UP_IMAGE = 'pointing_up.jpg' +_POINTING_UP_LANDMARKS = 'pointing_up_landmarks.pbtxt' _POINTING_UP_ROTATED_IMAGE = 'pointing_up_rotated.jpg' -_POINTING_UP_LANDMARKS = 'pointing_up_rotated_landmarks.pbtxt' +_POINTING_UP_ROTATED_LANDMARKS = 'pointing_up_rotated_landmarks.pbtxt' _POINTING_UP_LABEL = 'Pointing_Up' -_ROCK_LABEL = "Rock" +_ROCK_LABEL = 'Rock' _LANDMARKS_ERROR_TOLERANCE = 0.03 _GESTURE_EXPECTED_INDEX = -1 @@ -227,11 +231,13 @@ class GestureRecognizerTest(parameterized.TestCase): self._assert_actual_result_approximately_matches_expected_result( recognition_result, expected_recognition_result) - def test_recognize_succeeds_with_min_gesture_confidence(self): + def test_recognize_succeeds_with_score_threshold(self): # Creates gesture recognizer. base_options = _BaseOptions(model_asset_path=self.model_path) - options = _GestureRecognizerOptions(base_options=base_options, - min_gesture_confidence=0.5) + canned_gesture_classifier_options = _ClassifierOptions(score_threshold=.5) + options = _GestureRecognizerOptions( + base_options=base_options, + canned_gesture_classifier_options=canned_gesture_classifier_options) with _GestureRecognizer.create_from_options(options) as recognizer: # Performs hand gesture recognition on the input. recognition_result = recognizer.recognize(self.test_image) @@ -273,7 +279,7 @@ class GestureRecognizerTest(parameterized.TestCase): recognition_result = recognizer.recognize(test_image, image_processing_options) expected_recognition_result = _get_expected_gesture_recognition_result( - _POINTING_UP_LANDMARKS, _POINTING_UP_LABEL) + _POINTING_UP_ROTATED_LANDMARKS, _POINTING_UP_LABEL) # Comparing results. self._assert_actual_result_approximately_matches_expected_result( recognition_result, expected_recognition_result) @@ -294,14 +300,14 @@ class GestureRecognizerTest(parameterized.TestCase): self._assert_actual_result_approximately_matches_expected_result( recognition_result, expected_recognition_result) - def test_recognize_succeeds_with_custom_gesture_fist(self): + def test_recognize_succeeds_with_custom_gesture_rock(self): # Creates gesture recognizer. model_path = test_utils.get_test_data_path( _GESTURE_RECOGNIZER_WITH_CUSTOM_CLASSIFIER_BUNDLE_ASSET_FILE) base_options = _BaseOptions(model_asset_path=model_path) options = _GestureRecognizerOptions(base_options=base_options, num_hands=1) with _GestureRecognizer.create_from_options(options) as recognizer: - # Load the fist image. + # Load the rock image. test_image = _Image.create_from_file( test_utils.get_test_data_path(_FIST_IMAGE)) # Performs hand gesture recognition on the input. @@ -312,6 +318,95 @@ class GestureRecognizerTest(parameterized.TestCase): self._assert_actual_result_approximately_matches_expected_result( recognition_result, expected_recognition_result) + def test_recognize_succeeds_with_allow_gesture_pointing_up(self): + # Creates gesture recognizer. + model_path = test_utils.get_test_data_path( + _GESTURE_RECOGNIZER_WITH_CUSTOM_CLASSIFIER_BUNDLE_ASSET_FILE) + base_options = _BaseOptions(model_asset_path=model_path) + canned_gesture_classifier_options = _ClassifierOptions( + category_allowlist=['Pointing_Up']) + options = _GestureRecognizerOptions( + base_options=base_options, + num_hands=1, + canned_gesture_classifier_options=canned_gesture_classifier_options) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Load the pointing up image. + test_image = _Image.create_from_file( + test_utils.get_test_data_path(_POINTING_UP_IMAGE)) + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(test_image) + expected_recognition_result = _get_expected_gesture_recognition_result( + _POINTING_UP_LANDMARKS, _POINTING_UP_LABEL) + # Comparing results. + self._assert_actual_result_approximately_matches_expected_result( + recognition_result, expected_recognition_result) + + def test_recognize_succeeds_with_deny_gesture_pointing_up(self): + # Creates gesture recognizer. + model_path = test_utils.get_test_data_path( + _GESTURE_RECOGNIZER_WITH_CUSTOM_CLASSIFIER_BUNDLE_ASSET_FILE) + base_options = _BaseOptions(model_asset_path=model_path) + canned_gesture_classifier_options = _ClassifierOptions( + category_denylist=['Pointing_Up']) + options = _GestureRecognizerOptions( + base_options=base_options, + num_hands=1, + canned_gesture_classifier_options=canned_gesture_classifier_options) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Load the pointing up image. + test_image = _Image.create_from_file( + test_utils.get_test_data_path(_POINTING_UP_IMAGE)) + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(test_image) + actual_top_gesture = recognition_result.gestures[0][0] + self.assertEqual(actual_top_gesture.category_name, 'None') + + def test_recognize_succeeds_with_allow_all_gestures_except_pointing_up(self): + # Creates gesture recognizer. + model_path = test_utils.get_test_data_path( + _GESTURE_RECOGNIZER_WITH_CUSTOM_CLASSIFIER_BUNDLE_ASSET_FILE) + base_options = _BaseOptions(model_asset_path=model_path) + canned_gesture_classifier_options = _ClassifierOptions( + score_threshold=.5, category_allowlist=[ + 'None', 'Open_Palm', 'Victory', 'Thumb_Down', 'Thumb_Up', + 'ILoveYou', 'Closed_Fist']) + options = _GestureRecognizerOptions( + base_options=base_options, + num_hands=1, + canned_gesture_classifier_options=canned_gesture_classifier_options) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Load the pointing up image. + test_image = _Image.create_from_file( + test_utils.get_test_data_path(_POINTING_UP_IMAGE)) + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(test_image) + actual_top_gesture = recognition_result.gestures[0][0] + self.assertEqual(actual_top_gesture.category_name, 'None') + + def test_recognize_succeeds_with_prefer_allow_list_than_deny_list(self): + # Creates gesture recognizer. + model_path = test_utils.get_test_data_path( + _GESTURE_RECOGNIZER_WITH_CUSTOM_CLASSIFIER_BUNDLE_ASSET_FILE) + base_options = _BaseOptions(model_asset_path=model_path) + canned_gesture_classifier_options = _ClassifierOptions( + score_threshold=.5, category_allowlist=['Pointing_Up'], + category_denylist=['Pointing_Up']) + options = _GestureRecognizerOptions( + base_options=base_options, + num_hands=1, + canned_gesture_classifier_options=canned_gesture_classifier_options) + with _GestureRecognizer.create_from_options(options) as recognizer: + # Load the pointing up image. + test_image = _Image.create_from_file( + test_utils.get_test_data_path(_POINTING_UP_IMAGE)) + # Performs hand gesture recognition on the input. + recognition_result = recognizer.recognize(test_image) + expected_recognition_result = _get_expected_gesture_recognition_result( + _POINTING_UP_LANDMARKS, _POINTING_UP_LABEL) + # Comparing results. + self._assert_actual_result_approximately_matches_expected_result( + recognition_result, expected_recognition_result) + def test_recognize_fails_with_region_of_interest(self): # Creates gesture recognizer. base_options = _BaseOptions(model_asset_path=self.model_path) diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 0505471e..dec14990 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -88,10 +88,9 @@ py_library( "//mediapipe/python:packet_creator", "//mediapipe/python:packet_getter", "//mediapipe/tasks/cc/vision/gesture_recognizer/proto:gesture_recognizer_graph_options_py_pb2", - "//mediapipe/tasks/cc/vision/gesture_recognizer/proto:hand_gesture_recognizer_graph_options_py_pb2", - "//mediapipe/tasks/cc/vision/hand_landmarker/proto:hand_landmarker_graph_options_py_pb2", "//mediapipe/tasks/python/components/containers:category", "//mediapipe/tasks/python/components/containers:landmark", + "//mediapipe/tasks/python/components/processors:classifier_options", "//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/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py index 82dc00f1..2659f9a0 100644 --- a/mediapipe/tasks/python/vision/gesture_recognizer.py +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -21,10 +21,9 @@ 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.gesture_recognizer.proto import gesture_recognizer_graph_options_pb2 -from mediapipe.tasks.cc.vision.gesture_recognizer.proto import hand_gesture_recognizer_graph_options_pb2 -from mediapipe.tasks.cc.vision.hand_landmarker.proto import hand_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.processors import classifier_options 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 @@ -34,8 +33,7 @@ from mediapipe.tasks.python.vision.core import image_processing_options as image _BaseOptions = base_options_module.BaseOptions _GestureRecognizerGraphOptionsProto = gesture_recognizer_graph_options_pb2.GestureRecognizerGraphOptions -_HandGestureRecognizerGraphOptionsProto = hand_gesture_recognizer_graph_options_pb2.HandGestureRecognizerGraphOptions -_HandLandmarkerGraphOptionsProto = hand_landmarker_graph_options_pb2.HandLandmarkerGraphOptions +_ClassifierOptions = classifier_options.ClassifierOptions _RunningMode = running_mode_module.VisionTaskRunningMode _ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _TaskInfo = task_info_module.TaskInfo @@ -137,11 +135,16 @@ class GestureRecognizerOptions: score in the hand landmark detection. min_tracking_confidence: The minimum confidence score for the hand tracking to be considered successful. - min_gesture_confidence: The minimum confidence score for the gestures to be - considered successful. If < 0, the gesture confidence thresholds in the - model metadata are used. - TODO: Note this option is subject to change, after scoring merging - calculator is implemented. + canned_gesture_classifier_options: Options for configuring the canned + gestures classifier, such as score threshold, allow list and deny list of + gestures. The categories for canned gesture classifiers are: + ["None", "Closed_Fist", "Open_Palm", "Pointing_Up", "Thumb_Down", + "Thumb_Up", "Victory", "ILoveYou"] + TODO :Note this option is subject to change. + custom_gesture_classifier_options: Options for configuring the custom + gestures classifier, such as score threshold, allow list and deny list of + gestures. + TODO :Note this option is subject to change. 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. @@ -152,7 +155,8 @@ class GestureRecognizerOptions: min_hand_detection_confidence: Optional[float] = 0.5 min_hand_presence_confidence: Optional[float] = 0.5 min_tracking_confidence: Optional[float] = 0.5 - min_gesture_confidence: Optional[float] = -1 + canned_gesture_classifier_options: Optional[_ClassifierOptions] = _ClassifierOptions() + custom_gesture_classifier_options: Optional[_ClassifierOptions] = _ClassifierOptions() result_callback: Optional[ Callable[[GestureRecognitionResult, image_module.Image, int], None]] = None @@ -163,23 +167,22 @@ class GestureRecognizerOptions: base_options_proto = self.base_options.to_pb2() base_options_proto.use_stream_mode = False if self.running_mode == _RunningMode.IMAGE else True + # Initialize gesture recognizer options from base options. + gesture_recognizer_options_proto = _GestureRecognizerGraphOptionsProto( + base_options=base_options_proto) # Configure hand detector and hand landmarker options. - hand_landmarker_options_proto = _HandLandmarkerGraphOptionsProto() + hand_landmarker_options_proto = gesture_recognizer_options_proto.hand_landmarker_graph_options hand_landmarker_options_proto.min_tracking_confidence = self.min_tracking_confidence hand_landmarker_options_proto.hand_detector_graph_options.num_hands = self.num_hands hand_landmarker_options_proto.hand_detector_graph_options.min_detection_confidence = self.min_hand_detection_confidence hand_landmarker_options_proto.hand_landmarks_detector_graph_options.min_detection_confidence = self.min_hand_presence_confidence # Configure hand gesture recognizer options. - hand_gesture_recognizer_options_proto = _HandGestureRecognizerGraphOptionsProto() - hand_gesture_recognizer_options_proto.canned_gesture_classifier_graph_options.classifier_options.score_threshold = self.min_gesture_confidence - hand_gesture_recognizer_options_proto.custom_gesture_classifier_graph_options.classifier_options.score_threshold = self.min_gesture_confidence + hand_gesture_recognizer_options_proto = gesture_recognizer_options_proto.hand_gesture_recognizer_graph_options + hand_gesture_recognizer_options_proto.canned_gesture_classifier_graph_options.classifier_options.CopyFrom(self.canned_gesture_classifier_options.to_pb2()) + hand_gesture_recognizer_options_proto.custom_gesture_classifier_graph_options.classifier_options.CopyFrom(self.custom_gesture_classifier_options.to_pb2()) - return _GestureRecognizerGraphOptionsProto( - base_options=base_options_proto, - hand_landmarker_graph_options=hand_landmarker_options_proto, - hand_gesture_recognizer_graph_options=hand_gesture_recognizer_options_proto - ) + return gesture_recognizer_options_proto class GestureRecognizer(base_vision_task_api.BaseVisionTaskApi): From a913255080b10692808a9a66edd10f1e490758af Mon Sep 17 00:00:00 2001 From: kinaryml Date: Mon, 31 Oct 2022 23:07:05 -0700 Subject: [PATCH 15/16] Removed min score thres from tests --- mediapipe/tasks/python/test/vision/gesture_recognizer_test.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index d5cd72cd..fb8ca671 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -367,7 +367,7 @@ class GestureRecognizerTest(parameterized.TestCase): _GESTURE_RECOGNIZER_WITH_CUSTOM_CLASSIFIER_BUNDLE_ASSET_FILE) base_options = _BaseOptions(model_asset_path=model_path) canned_gesture_classifier_options = _ClassifierOptions( - score_threshold=.5, category_allowlist=[ + category_allowlist=[ 'None', 'Open_Palm', 'Victory', 'Thumb_Down', 'Thumb_Up', 'ILoveYou', 'Closed_Fist']) options = _GestureRecognizerOptions( @@ -389,7 +389,7 @@ class GestureRecognizerTest(parameterized.TestCase): _GESTURE_RECOGNIZER_WITH_CUSTOM_CLASSIFIER_BUNDLE_ASSET_FILE) base_options = _BaseOptions(model_asset_path=model_path) canned_gesture_classifier_options = _ClassifierOptions( - score_threshold=.5, category_allowlist=['Pointing_Up'], + category_allowlist=['Pointing_Up'], category_denylist=['Pointing_Up']) options = _GestureRecognizerOptions( base_options=base_options, From c5765ac8363b17557d5820c7c6f9f6942cde2492 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Tue, 1 Nov 2022 15:37:00 -0700 Subject: [PATCH 16/16] Refactored Rect to use top-left coordinates and appropriately updated the Image Classifier and Gesture Recognizer APIs/tests --- .../python/components/containers/rect.py | 73 ++++++------------- mediapipe/tasks/python/test/vision/BUILD | 1 + .../test/vision/gesture_recognizer_test.py | 2 +- .../test/vision/image_classifier_test.py | 30 ++++---- mediapipe/tasks/python/vision/BUILD | 2 + .../vision/core/base_vision_task_api.py | 14 ++-- .../vision/core/image_processing_options.py | 2 +- .../tasks/python/vision/gesture_recognizer.py | 2 +- .../tasks/python/vision/image_classifier.py | 49 ++++++------- 9 files changed, 75 insertions(+), 100 deletions(-) diff --git a/mediapipe/tasks/python/components/containers/rect.py b/mediapipe/tasks/python/components/containers/rect.py index 51056159..90e98fef 100644 --- a/mediapipe/tasks/python/components/containers/rect.py +++ b/mediapipe/tasks/python/components/containers/rect.py @@ -19,75 +19,44 @@ from typing import Any, Optional from mediapipe.framework.formats import rect_pb2 from mediapipe.tasks.python.core.optional_dependencies import doc_controls -_RectProto = rect_pb2.Rect _NormalizedRectProto = rect_pb2.NormalizedRect @dataclasses.dataclass class Rect: - """A rectangle with rotation in image coordinates. + """A rectangle, used e.g. as part of detection results or as input + region-of-interest. - Attributes: x_center : The X coordinate of the top-left corner, in pixels. - y_center : The Y coordinate of the top-left corner, in pixels. - width: The width of the rectangle, in pixels. - height: The height of the rectangle, in pixels. - rotation: Rotation angle is clockwise in radians. - rect_id: Optional unique id to help associate different rectangles to each - other. + The coordinates are normalized wrt the image dimensions, i.e. generally in + [0,1] but they may exceed these bounds if describing a region overlapping the + image. The origin is on the top-left corner of the image. + + Attributes: + left: The X coordinate of the left side of the rectangle. + top: The Y coordinate of the top of the rectangle. + right: The X coordinate of the right side of the rectangle. + bottom: The Y coordinate of the bottom of the rectangle. """ - x_center: int - y_center: int - width: int - height: int - rotation: Optional[float] = 0.0 - rect_id: Optional[int] = None - - @doc_controls.do_not_generate_docs - def to_pb2(self) -> _RectProto: - """Generates a Rect protobuf object.""" - return _RectProto( - x_center=self.x_center, - y_center=self.y_center, - width=self.width, - height=self.height, - ) - - @classmethod - @doc_controls.do_not_generate_docs - def create_from_pb2(cls, pb2_obj: _RectProto) -> 'Rect': - """Creates a `Rect` object from the given protobuf object.""" - return Rect( - x_center=pb2_obj.x_center, - y_center=pb2_obj.y_center, - width=pb2_obj.width, - height=pb2_obj.height) - - 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, Rect): - return False - - return self.to_pb2().__eq__(other.to_pb2()) + left: float + top: float + right: float + bottom: float @dataclasses.dataclass class NormalizedRect: - """A rectangle with rotation in normalized coordinates. + """A rectangle with rotation in normalized coordinates. Location of the center + of the rectangle in image coordinates. The (0.0, 0.0) point is at the + (top, left) corner. The values of box center location and size are within [0, 1]. - Attributes: x_center : The X normalized coordinate of the top-left corner. - y_center : The Y normalized coordinate of the top-left corner. + Attributes: x_center: The normalized X coordinate of the rectangle, in + image coordinates. + y_center: The normalized Y coordinate of the rectangle, in image coordinates. width: The width of the rectangle. height: The height of the rectangle. rotation: Rotation angle is clockwise in radians. diff --git a/mediapipe/tasks/python/test/vision/BUILD b/mediapipe/tasks/python/test/vision/BUILD index da8ad3f8..4966ffd2 100644 --- a/mediapipe/tasks/python/test/vision/BUILD +++ b/mediapipe/tasks/python/test/vision/BUILD @@ -54,6 +54,7 @@ py_test( "//mediapipe/tasks/python/test:test_utils", "//mediapipe/tasks/python/vision:image_classifier", "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + "//mediapipe/tasks/python/vision/core:image_processing_options", ], ) diff --git a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py index fb8ca671..e2fbcbcd 100644 --- a/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py +++ b/mediapipe/tasks/python/test/vision/gesture_recognizer_test.py @@ -78,7 +78,7 @@ def _get_expected_gesture_recognition_result( file_path) with open(landmarks_detection_result_file_path, "rb") as f: landmarks_detection_result_proto = _LandmarksDetectionResultProto() - # # Use this if a .pb file is available. + # Use this if a .pb file is available. # landmarks_detection_result_proto.ParseFromString(f.read()) text_format.Parse(f.read(), landmarks_detection_result_proto) landmarks_detection_result = _LandmarksDetectionResult.create_from_pb2( diff --git a/mediapipe/tasks/python/test/vision/image_classifier_test.py b/mediapipe/tasks/python/test/vision/image_classifier_test.py index afaf921a..e56bcdea 100644 --- a/mediapipe/tasks/python/test/vision/image_classifier_test.py +++ b/mediapipe/tasks/python/test/vision/image_classifier_test.py @@ -29,8 +29,10 @@ 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 image_classifier from mediapipe.tasks.python.vision.core import vision_task_running_mode +from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module -_NormalizedRect = rect.NormalizedRect + +_Rect = rect.Rect _BaseOptions = base_options_module.BaseOptions _ClassifierOptions = classifier_options.ClassifierOptions _Category = category.Category @@ -41,6 +43,7 @@ _Image = image.Image _ImageClassifier = image_classifier.ImageClassifier _ImageClassifierOptions = image_classifier.ImageClassifierOptions _RUNNING_MODE = vision_task_running_mode.VisionTaskRunningMode +_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _MODEL_FILE = 'mobilenet_v2_1.0_224.tflite' _IMAGE_FILE = 'burger.jpg' @@ -226,11 +229,11 @@ class ImageClassifierTest(parameterized.TestCase): # Load the test image. test_image = _Image.create_from_file( test_utils.get_test_data_path('multi_objects.jpg')) - # NormalizedRect around the soccer ball. - roi = _NormalizedRect( - x_center=0.532, y_center=0.521, width=0.164, height=0.427) + # Region-of-interest around the soccer ball. + roi = _Rect(left=0.45, top=0.3075, right=0.614, bottom=0.7345) + image_processing_options = _ImageProcessingOptions(roi) # Performs image classification on the input. - image_result = classifier.classify(test_image, roi) + image_result = classifier.classify(test_image, image_processing_options) # Comparing results. _assert_proto_equals(image_result.to_pb2(), _generate_soccer_ball_results(0).to_pb2()) @@ -414,12 +417,12 @@ class ImageClassifierTest(parameterized.TestCase): # Load the test image. test_image = _Image.create_from_file( test_utils.get_test_data_path('multi_objects.jpg')) - # NormalizedRect around the soccer ball. - roi = _NormalizedRect( - x_center=0.532, y_center=0.521, width=0.164, height=0.427) + # Region-of-interest around the soccer ball. + roi = _Rect(left=0.45, top=0.3075, right=0.614, bottom=0.7345) + image_processing_options = _ImageProcessingOptions(roi) for timestamp in range(0, 300, 30): classification_result = classifier.classify_for_video( - test_image, timestamp, roi) + test_image, timestamp, image_processing_options) self.assertEqual(classification_result, _generate_soccer_ball_results(timestamp)) @@ -486,9 +489,9 @@ class ImageClassifierTest(parameterized.TestCase): # Load the test image. test_image = _Image.create_from_file( test_utils.get_test_data_path('multi_objects.jpg')) - # NormalizedRect around the soccer ball. - roi = _NormalizedRect( - x_center=0.532, y_center=0.521, width=0.164, height=0.427) + # Region-of-interest around the soccer ball. + roi = _Rect(left=0.45, top=0.3075, right=0.614, bottom=0.7345) + image_processing_options = _ImageProcessingOptions(roi) observed_timestamp_ms = -1 def check_result(result: _ClassificationResult, output_image: _Image, @@ -508,7 +511,8 @@ class ImageClassifierTest(parameterized.TestCase): result_callback=check_result) with _ImageClassifier.create_from_options(options) as classifier: for timestamp in range(0, 300, 30): - classifier.classify_async(test_image, timestamp, roi) + classifier.classify_async(test_image, timestamp, + image_processing_options) if __name__ == '__main__': diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index dec14990..2b9b5201 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -56,6 +56,7 @@ py_library( "//mediapipe/tasks/python/core:task_info", "//mediapipe/tasks/python/vision/core:base_vision_task_api", "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + "//mediapipe/tasks/python/vision/core:image_processing_options", ], ) @@ -96,5 +97,6 @@ py_library( "//mediapipe/tasks/python/core:task_info", "//mediapipe/tasks/python/vision/core:base_vision_task_api", "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + "//mediapipe/tasks/python/vision/core:image_processing_options", ], ) diff --git a/mediapipe/tasks/python/vision/core/base_vision_task_api.py b/mediapipe/tasks/python/vision/core/base_vision_task_api.py index be290c83..86771ade 100644 --- a/mediapipe/tasks/python/vision/core/base_vision_task_api.py +++ b/mediapipe/tasks/python/vision/core/base_vision_task_api.py @@ -160,15 +160,15 @@ class BaseVisionTaskApi(object): if not roi_allowed: raise ValueError("This task doesn't support region-of-interest.") roi = options.region_of_interest - if roi.x_center >= roi.width or roi.y_center >= roi.height: + if roi.left >= roi.right or roi.top >= roi.bottom: raise ValueError( - "Expected Rect with x_center < width and y_center < height.") - if roi.x_center < 0 or roi.y_center < 0 or roi.width > 1 or roi.height > 1: + "Expected Rect with left < right and top < bottom.") + if roi.left < 0 or roi.top < 0 or roi.right > 1 or roi.bottom > 1: raise ValueError("Expected Rect values to be in [0,1].") - normalized_rect.x_center = roi.x_center + roi.width / 2.0 - normalized_rect.y_center = roi.y_center + roi.height / 2.0 - normalized_rect.width = roi.width - roi.x_center - normalized_rect.height = roi.height - roi.y_center + normalized_rect.x_center = (roi.left + roi.right) / 2.0 + normalized_rect.y_center = (roi.top + roi.bottom) / 2.0 + normalized_rect.width = roi.right - roi.left + normalized_rect.height = roi.bottom - roi.top return normalized_rect def close(self) -> None: diff --git a/mediapipe/tasks/python/vision/core/image_processing_options.py b/mediapipe/tasks/python/vision/core/image_processing_options.py index 1a519809..fafde049 100644 --- a/mediapipe/tasks/python/vision/core/image_processing_options.py +++ b/mediapipe/tasks/python/vision/core/image_processing_options.py @@ -30,7 +30,7 @@ class ImageProcessingOptions: Attributes: region_of_interest: The optional region-of-interest to crop from the image. If not specified, the full image is used. Coordinates must be in [0,1] - with 'x_center' < 'width' and 'y_center' < height. + with 'left' < 'right' and 'top' < 'bottom'. rotation_degress: The rotation to apply to the image (or cropped region-of-interest), in degrees clockwise. The rotation must be a multiple (positive or negative) of 90°. diff --git a/mediapipe/tasks/python/vision/gesture_recognizer.py b/mediapipe/tasks/python/vision/gesture_recognizer.py index 2659f9a0..33286b90 100644 --- a/mediapipe/tasks/python/vision/gesture_recognizer.py +++ b/mediapipe/tasks/python/vision/gesture_recognizer.py @@ -63,7 +63,7 @@ class GestureRecognitionResult: Attributes: gestures: Recognized hand gestures of detected hands. Note that the index - of the gesture is always 0, because the raw indices from multiple gesture + of the gesture is always -1, because the raw indices from multiple gesture classifiers cannot consolidate to a meaningful index. handedness: Classification of handedness. hand_landmarks: Detected hand landmarks in normalized image coordinates. diff --git a/mediapipe/tasks/python/vision/image_classifier.py b/mediapipe/tasks/python/vision/image_classifier.py index 7be5d573..89e6775e 100644 --- a/mediapipe/tasks/python/vision/image_classifier.py +++ b/mediapipe/tasks/python/vision/image_classifier.py @@ -31,12 +31,14 @@ 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 vision_task_running_mode +from mediapipe.tasks.python.vision.core import image_processing_options as image_processing_options_module _NormalizedRect = rect.NormalizedRect _BaseOptions = base_options_module.BaseOptions _ImageClassifierGraphOptionsProto = image_classifier_graph_options_pb2.ImageClassifierGraphOptions _ClassifierOptions = classifier_options.ClassifierOptions _RunningMode = vision_task_running_mode.VisionTaskRunningMode +_ImageProcessingOptions = image_processing_options_module.ImageProcessingOptions _TaskInfo = task_info_module.TaskInfo _CLASSIFICATION_RESULT_OUT_STREAM_NAME = 'classification_result_out' @@ -44,17 +46,12 @@ _CLASSIFICATION_RESULT_TAG = 'CLASSIFICATION_RESULT' _IMAGE_IN_STREAM_NAME = 'image_in' _IMAGE_OUT_STREAM_NAME = 'image_out' _IMAGE_TAG = 'IMAGE' -_NORM_RECT_NAME = 'norm_rect_in' +_NORM_RECT_STREAM_NAME = 'norm_rect_in' _NORM_RECT_TAG = 'NORM_RECT' _TASK_GRAPH_NAME = 'mediapipe.tasks.vision.image_classifier.ImageClassifierGraph' _MICRO_SECONDS_PER_MILLISECOND = 1000 -def _build_full_image_norm_rect() -> _NormalizedRect: - # Builds a NormalizedRect covering the entire image. - return _NormalizedRect(x_center=0.5, y_center=0.5, width=1, height=1) - - @dataclasses.dataclass class ImageClassifierOptions: """Options for the image classifier task. @@ -156,7 +153,7 @@ class ImageClassifier(base_vision_task_api.BaseVisionTaskApi): task_graph=_TASK_GRAPH_NAME, input_streams=[ ':'.join([_IMAGE_TAG, _IMAGE_IN_STREAM_NAME]), - ':'.join([_NORM_RECT_TAG, _NORM_RECT_NAME]), + ':'.join([_NORM_RECT_TAG, _NORM_RECT_STREAM_NAME]), ], output_streams=[ ':'.join([ @@ -171,17 +168,16 @@ class ImageClassifier(base_vision_task_api.BaseVisionTaskApi): _RunningMode.LIVE_STREAM), options.running_mode, packets_callback if options.result_callback else None) - # TODO: Replace _NormalizedRect with ImageProcessingOption def classify( self, image: image_module.Image, - roi: Optional[_NormalizedRect] = None + image_processing_options: Optional[_ImageProcessingOptions] = None ) -> classifications.ClassificationResult: """Performs image classification on the provided MediaPipe Image. Args: image: MediaPipe Image. - roi: The region of interest. + image_processing_options: Options for image processing. Returns: A classification result object that contains a list of classifications. @@ -190,10 +186,11 @@ class ImageClassifier(base_vision_task_api.BaseVisionTaskApi): ValueError: If any of the input arguments is invalid. RuntimeError: If image classification failed to run. """ - norm_rect = roi if roi is not None else _build_full_image_norm_rect() + normalized_rect = self.convert_to_normalized_rect(image_processing_options) output_packets = self._process_image_data({ _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image), - _NORM_RECT_NAME: packet_creator.create_proto(norm_rect.to_pb2()) + _NORM_RECT_STREAM_NAME: packet_creator.create_proto( + normalized_rect.to_pb2()) }) classification_result_proto = classifications_pb2.ClassificationResult() @@ -210,7 +207,7 @@ class ImageClassifier(base_vision_task_api.BaseVisionTaskApi): self, image: image_module.Image, timestamp_ms: int, - roi: Optional[_NormalizedRect] = None + image_processing_options: Optional[_ImageProcessingOptions] = None ) -> classifications.ClassificationResult: """Performs image classification on the provided video frames. @@ -222,7 +219,7 @@ class ImageClassifier(base_vision_task_api.BaseVisionTaskApi): Args: image: MediaPipe Image. timestamp_ms: The timestamp of the input video frame in milliseconds. - roi: The region of interest. + image_processing_options: Options for image processing. Returns: A classification result object that contains a list of classifications. @@ -231,13 +228,13 @@ class ImageClassifier(base_vision_task_api.BaseVisionTaskApi): ValueError: If any of the input arguments is invalid. RuntimeError: If image classification failed to run. """ - norm_rect = roi if roi is not None else _build_full_image_norm_rect() + normalized_rect = self.convert_to_normalized_rect(image_processing_options) output_packets = self._process_video_data({ _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image).at( timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND), - _NORM_RECT_NAME: - packet_creator.create_proto(norm_rect.to_pb2()).at( + _NORM_RECT_STREAM_NAME: + packet_creator.create_proto(normalized_rect.to_pb2()).at( timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) }) @@ -251,10 +248,12 @@ class ImageClassifier(base_vision_task_api.BaseVisionTaskApi): for classification in classification_result_proto.classifications ]) - def classify_async(self, - image: image_module.Image, - timestamp_ms: int, - roi: Optional[_NormalizedRect] = None) -> None: + def classify_async( + self, + image: image_module.Image, + timestamp_ms: int, + image_processing_options: Optional[_ImageProcessingOptions] = None + ) -> None: """Sends live image data (an Image with a unique timestamp) to perform image classification. Only use this method when the ImageClassifier is created with the live @@ -275,18 +274,18 @@ class ImageClassifier(base_vision_task_api.BaseVisionTaskApi): Args: image: MediaPipe Image. timestamp_ms: The timestamp of the input image in milliseconds. - roi: The region of interest. + image_processing_options: Options for image processing. Raises: ValueError: If the current input timestamp is smaller than what the image classifier has already processed. """ - norm_rect = roi if roi is not None else _build_full_image_norm_rect() + normalized_rect = self.convert_to_normalized_rect(image_processing_options) self._send_live_stream_data({ _IMAGE_IN_STREAM_NAME: packet_creator.create_image(image).at( timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND), - _NORM_RECT_NAME: - packet_creator.create_proto(norm_rect.to_pb2()).at( + _NORM_RECT_STREAM_NAME: + packet_creator.create_proto(normalized_rect.to_pb2()).at( timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) })