From 71d5b695442ef36c1a574b2c7b6a956b5d6f2667 Mon Sep 17 00:00:00 2001 From: kinaryml Date: Thu, 20 Oct 2022 02:29:14 -0700 Subject: [PATCH] Added files for the image embedder implementation and a simple test --- mediapipe/python/BUILD | 1 + .../tasks/python/components/containers/BUILD | 18 ++ .../components/containers/embeddings.py | 246 +++++++++++++++ .../python/components/containers/rect.py | 141 +++++++++ mediapipe/tasks/python/components/proto/BUILD | 28 ++ .../tasks/python/components/proto/__init__.py | 13 + .../components/proto/embedder_options.py | 72 +++++ mediapipe/tasks/python/test/vision/BUILD | 19 ++ .../python/test/vision/image_embedder_test.py | 98 ++++++ mediapipe/tasks/python/vision/BUILD | 19 ++ .../tasks/python/vision/image_embedder.py | 288 ++++++++++++++++++ 11 files changed, 943 insertions(+) create mode 100644 mediapipe/tasks/python/components/containers/embeddings.py create mode 100644 mediapipe/tasks/python/components/containers/rect.py create mode 100644 mediapipe/tasks/python/components/proto/BUILD create mode 100644 mediapipe/tasks/python/components/proto/__init__.py create mode 100644 mediapipe/tasks/python/components/proto/embedder_options.py create mode 100644 mediapipe/tasks/python/test/vision/image_embedder_test.py create mode 100644 mediapipe/tasks/python/vision/image_embedder.py diff --git a/mediapipe/python/BUILD b/mediapipe/python/BUILD index 2911e2fd6..3df0e2798 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/image_embedder:image_embedder_graph", ], ) diff --git a/mediapipe/tasks/python/components/containers/BUILD b/mediapipe/tasks/python/components/containers/BUILD index 8dd9fcd60..cb123562f 100644 --- a/mediapipe/tasks/python/components/containers/BUILD +++ b/mediapipe/tasks/python/components/containers/BUILD @@ -27,6 +27,15 @@ 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 = "category", srcs = ["category.py"], @@ -47,3 +56,12 @@ py_library( "//mediapipe/tasks/python/core:optional_dependencies", ], ) + +py_library( + name = "embeddings", + srcs = ["embeddings.py"], + deps = [ + "//mediapipe/tasks/cc/components/containers/proto:embeddings_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) diff --git a/mediapipe/tasks/python/components/containers/embeddings.py b/mediapipe/tasks/python/components/containers/embeddings.py new file mode 100644 index 000000000..21f53670c --- /dev/null +++ b/mediapipe/tasks/python/components/containers/embeddings.py @@ -0,0 +1,246 @@ +# 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. +"""Embeddings data class.""" + +import dataclasses +from typing import Any, Optional, List + +import numpy as np +from mediapipe.tasks.cc.components.containers.proto import embeddings_pb2 +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_FloatEmbeddingProto = embeddings_pb2.FloatEmbedding +_QuantizedEmbeddingProto = embeddings_pb2.QuantizedEmbedding +_EmbeddingEntryProto = embeddings_pb2.EmbeddingEntry +_EmbeddingsProto = embeddings_pb2.Embeddings +_EmbeddingResultProto = embeddings_pb2.EmbeddingResult + + +@dataclasses.dataclass +class FloatEmbedding: + """Defines a dense floating-point embedding. + + Attributes: + values: A NumPy array indicating the raw output of the embedding layer. + """ + + values: np.ndarray + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _FloatEmbeddingProto: + """Generates a FloatEmbedding protobuf object.""" + return _FloatEmbeddingProto(values=self.values) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, pb2_obj: _FloatEmbeddingProto) -> 'FloatEmbedding': + """Creates a `FloatEmbedding` object from the given protobuf object.""" + return FloatEmbedding(values=np.array(pb2_obj.value_float, dtype=float)) + + 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, FloatEmbedding): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class QuantizedEmbedding: + """Defines a dense scalar-quantized embedding. + + Attributes: + values: A NumPy array indicating the raw output of the embedding layer. + """ + + values: np.ndarray + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _QuantizedEmbeddingProto: + """Generates a QuantizedEmbedding protobuf object.""" + return _QuantizedEmbeddingProto(values=self.values) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, pb2_obj: _QuantizedEmbeddingProto) -> 'QuantizedEmbedding': + """Creates a `QuantizedEmbedding` object from the given protobuf object.""" + return QuantizedEmbedding( + values=np.array(bytearray(pb2_obj.value_string), dtype=np.uint8)) + + 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, QuantizedEmbedding): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class EmbeddingEntry: + """Floating-point or scalar-quantized embedding with an optional timestamp. + + Attributes: + embedding: The actual embedding, either floating-point or scalar-quantized. + timestamp_ms: The optional timestamp (in milliseconds) associated to the + embedding entry. This is useful for time series use cases, e.g. audio + embedding. + """ + + embedding: np.ndarray + timestamp_ms: Optional[int] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _EmbeddingEntryProto: + """Generates a EmbeddingEntry protobuf object.""" + + if self.embedding.dtype == float: + return _EmbeddingEntryProto(float_embedding=self.embedding) + + elif self.embedding.dtype == np.uint8: + return _EmbeddingEntryProto(quantized_embedding=bytes(self.embedding)) + + else: + raise ValueError("Invalid dtype. Only float and np.uint8 are supported.") + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, pb2_obj: _EmbeddingEntryProto) -> 'EmbeddingEntry': + """Creates a `EmbeddingEntry` object from the given protobuf object.""" + + if pb2_obj.float_embedding: + return EmbeddingEntry( + embedding=np.array(pb2_obj.float_embedding.values, dtype=float)) + + elif pb2_obj.quantized_embedding: + return EmbeddingEntry( + embedding=np.array(bytearray(pb2_obj.quantized_embedding.values), + dtype=np.uint8)) + + else: + raise ValueError("Either float_embedding or quantized_embedding must " + "exist.") + + 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, EmbeddingEntry): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class Embeddings: + """Embeddings for a given embedder head. + Attributes: + entries: A list of `ClassificationEntry` objects. + head_index: The index of the embedder head that produced this embedding. + This is useful for multi-head models. + head_name: The name of the embedder head, which is the corresponding tensor + metadata name (if any). This is useful for multi-head models. + """ + + entries: List[EmbeddingEntry] + head_index: int + head_name: str + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _EmbeddingsProto: + """Generates a Embeddings protobuf object.""" + return _EmbeddingsProto( + entries=[entry.to_pb2() for entry in self.entries], + head_index=self.head_index, + head_name=self.head_name) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _EmbeddingsProto) -> 'Embeddings': + """Creates a `Embeddings` object from the given protobuf object.""" + return Embeddings( + entries=[ + EmbeddingEntry.create_from_pb2(entry) + for entry in pb2_obj.entries + ], + head_index=pb2_obj.head_index, + head_name=pb2_obj.head_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, Embeddings): + return False + + return self.to_pb2().__eq__(other.to_pb2()) + + +@dataclasses.dataclass +class EmbeddingResult: + """Contains one set of results per embedder head. + Attributes: + embeddings: A list of `Embeddings` objects. + """ + + embeddings: List[Embeddings] + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _EmbeddingResultProto: + """Generates a EmbeddingResult protobuf object.""" + return _EmbeddingResultProto( + embeddings=[ + embedding.to_pb2() for embedding in self.embeddings + ]) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2( + cls, pb2_obj: _EmbeddingResultProto) -> 'EmbeddingResult': + """Creates a `EmbeddingResult` object from the given protobuf object.""" + return EmbeddingResult( + embeddings=[ + Embeddings.create_from_pb2(embedding) + for embedding in pb2_obj.embeddings + ]) + + 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, EmbeddingResult): + 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 000000000..aadb404db --- /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/proto/BUILD b/mediapipe/tasks/python/components/proto/BUILD new file mode 100644 index 000000000..973f150ca --- /dev/null +++ b/mediapipe/tasks/python/components/proto/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 = "embedder_options", + srcs = ["embedder_options.py"], + deps = [ + "//mediapipe/tasks/cc/components/proto:embedder_options_py_pb2", + "//mediapipe/tasks/python/core:optional_dependencies", + ], +) diff --git a/mediapipe/tasks/python/components/proto/__init__.py b/mediapipe/tasks/python/components/proto/__init__.py new file mode 100644 index 000000000..65c1214af --- /dev/null +++ b/mediapipe/tasks/python/components/proto/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/mediapipe/tasks/python/components/proto/embedder_options.py b/mediapipe/tasks/python/components/proto/embedder_options.py new file mode 100644 index 000000000..3c257b976 --- /dev/null +++ b/mediapipe/tasks/python/components/proto/embedder_options.py @@ -0,0 +1,72 @@ +# 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. +"""Embedder options data class.""" + +import dataclasses +from typing import Any, Optional + +from mediapipe.tasks.cc.components.proto import embedder_options_pb2 +from mediapipe.tasks.python.core.optional_dependencies import doc_controls + +_EmbedderOptionsProto = embedder_options_pb2.EmbedderOptions + + +@dataclasses.dataclass +class EmbedderOptions: + """Shared options used by all embedding extraction tasks. + + Attributes: + l2_normalize: Whether to normalize the returned feature vector with L2 norm. + Use this option only if the model does not already contain a native + L2_NORMALIZATION TF Lite Op. In most cases, this is already the case and + L2 norm is thus achieved through TF Lite inference. + quantize: Whether the returned embedding should be quantized to bytes via + scalar quantization. Embeddings are implicitly assumed to be unit-norm and + therefore any dimension is guaranteed to have a value in [-1.0, 1.0]. Use + the l2_normalize option if this is not the case. + """ + + l2_normalize: Optional[bool] = None + quantize: Optional[bool] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _EmbedderOptionsProto: + """Generates a EmbedderOptions protobuf object.""" + return _EmbedderOptionsProto( + l2_normalize=self.l2_normalize, + quantize=self.quantize + ) + + @classmethod + @doc_controls.do_not_generate_docs + def create_from_pb2(cls, pb2_obj: _EmbedderOptionsProto) -> 'EmbedderOptions': + """Creates a `EmbedderOptions` object from the given protobuf object.""" + return EmbedderOptions( + l2_normalize=pb2_obj.l2_normalize, + quantize=pb2_obj.quantize + ) + + 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, EmbedderOptions): + 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 290b665e7..62595d377 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 = "image_embedder_test", + srcs = ["image_embedder_test.py"], + data = [ + "//mediapipe/tasks/testdata/vision:test_images", + "//mediapipe/tasks/testdata/vision:test_models", + ], + deps = [ + "//mediapipe/python:_framework_bindings", + "//mediapipe/tasks/python/components/proto:embedder_options", + "//mediapipe/tasks/python/components/containers:embeddings", + "//mediapipe/tasks/python/components/containers:rect", + "//mediapipe/tasks/python/core:base_options", + "//mediapipe/tasks/python/test:test_utils", + "//mediapipe/tasks/python/vision:image_embedder", + "//mediapipe/tasks/python/vision/core:vision_task_running_mode", + ], +) diff --git a/mediapipe/tasks/python/test/vision/image_embedder_test.py b/mediapipe/tasks/python/test/vision/image_embedder_test.py new file mode 100644 index 000000000..8ddf3c992 --- /dev/null +++ b/mediapipe/tasks/python/test/vision/image_embedder_test.py @@ -0,0 +1,98 @@ +# 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 image embedder.""" + +import enum +from unittest import mock + +import numpy as np +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.proto import embedder_options as embedder_options_module +from mediapipe.tasks.python.components.containers import embeddings as embeddings_module +from mediapipe.tasks.python.components.containers import rect as rect_module +from mediapipe.tasks.python.core import base_options as base_options_module +from mediapipe.tasks.python.test import test_utils +from mediapipe.tasks.python.vision import image_embedder +from mediapipe.tasks.python.vision.core import vision_task_running_mode as running_mode_module + +_NormalizedRect = rect_module.NormalizedRect +_BaseOptions = base_options_module.BaseOptions +_EmbedderOptions = embedder_options_module.EmbedderOptions +_FloatEmbedding = embeddings_module.FloatEmbedding +_QuantizedEmbedding = embeddings_module.QuantizedEmbedding +_ClassificationEntry = embeddings_module.EmbeddingEntry +_Classifications = embeddings_module.Embeddings +_ClassificationResult = embeddings_module.EmbeddingResult +_Image = image_module.Image +_ImageEmbedder = image_embedder.ImageEmbedder +_ImageEmbedderOptions = image_embedder.ImageEmbedderOptions +_RUNNING_MODE = running_mode_module.VisionTaskRunningMode + +_MODEL_FILE = 'mobilenet_v3_small_100_224_embedder.tflite' +_IMAGE_FILE = 'burger.jpg' +_ALLOW_LIST = ['cheeseburger', 'guacamole'] +_DENY_LIST = ['cheeseburger'] +_SCORE_THRESHOLD = 0.5 +_MAX_RESULTS = 3 + + +class ModelFileType(enum.Enum): + FILE_CONTENT = 1 + FILE_NAME = 2 + + +class ImageClassifierTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self.test_image = _Image.create_from_file( + test_utils.get_test_data_path(_IMAGE_FILE)) + self.model_path = test_utils.get_test_data_path(_MODEL_FILE) + + @parameterized.parameters( + (ModelFileType.FILE_NAME, False, False), + (ModelFileType.FILE_CONTENT, False, False)) + def test_embed(self, model_file_type, l2_normalize, quantize): + # Creates embedder. + 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.') + + embedder_options = _EmbedderOptions(l2_normalize=l2_normalize, + quantize=quantize) + options = _ImageEmbedderOptions( + base_options=base_options, embedder_options=embedder_options) + embedder = _ImageEmbedder.create_from_options(options) + + # Performs image embedding extraction on the input. + image_result = embedder.embed(self.test_image) + + # TODO: Verify results. + + # Closes the embedder explicitly when the classifier is not used in + # a context. + embedder.close() + + +if __name__ == '__main__': + absltest.main() diff --git a/mediapipe/tasks/python/vision/BUILD b/mediapipe/tasks/python/vision/BUILD index 7ff818610..08c2709fc 100644 --- a/mediapipe/tasks/python/vision/BUILD +++ b/mediapipe/tasks/python/vision/BUILD @@ -36,3 +36,22 @@ py_library( "//mediapipe/tasks/python/vision/core:vision_task_running_mode", ], ) + +py_library( + name = "image_embedder", + srcs = [ + "image_embedder.py", + ], + deps = [ + "//mediapipe/python:_framework_bindings", + "//mediapipe/python:packet_creator", + "//mediapipe/python:packet_getter", + "//mediapipe/tasks/cc/vision/image_embedder/proto:image_embedder_graph_options_py_pb2", + "//mediapipe/tasks/python/components/containers:embeddings", + "//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/image_embedder.py b/mediapipe/tasks/python/vision/image_embedder.py new file mode 100644 index 000000000..23ef492e5 --- /dev/null +++ b/mediapipe/tasks/python/vision/image_embedder.py @@ -0,0 +1,288 @@ +# 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 image embedder task.""" + +import dataclasses +from typing import Callable, Mapping, Optional + +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.image_embedder.proto import image_embedder_graph_options_pb2 +from mediapipe.tasks.python.components.proto import embedder_options +from mediapipe.tasks.python.components.containers import embeddings as embeddings_module +from mediapipe.tasks.python.components.containers import rect as rect_module +from mediapipe.tasks.python.core import base_options as base_options_module +from mediapipe.tasks.python.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 +_ImageEmbedderGraphOptionsProto = image_embedder_graph_options_pb2.ImageEmbedderGraphOptions +_EmbedderOptions = embedder_options.EmbedderOptions +_RunningMode = running_mode_module.VisionTaskRunningMode +_TaskInfo = task_info_module.TaskInfo +_TaskRunner = task_runner_module.TaskRunner + +_EMBEDDING_RESULT_OUT_STREAM_NAME = 'embedding_result_out' +_EMBEDDING_RESULT_TAG = 'EMBEDDING_RESULT' +_IMAGE_IN_STREAM_NAME = 'image_in' +_IMAGE_OUT_STREAM_NAME = 'image_out' +_IMAGE_TAG = 'IMAGE' +_NORM_RECT_NAME = 'norm_rect_in' +_NORM_RECT_TAG = 'NORM_RECT' +_TASK_GRAPH_NAME = 'mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph' +_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 ImageEmbedderOptions: + """Options for the image embedder task. + + Attributes: + base_options: Base options for the image embedder task. + running_mode: The running mode of the task. Default to the image mode. + Image embedder task has three running modes: + 1) The image mode for embedding image on single image inputs. + 2) The video mode for embedding image on the decoded frames of a + video. + 3) The live stream mode for embedding image on a live stream of input + data, such as from camera. + embedder_options: Options for the image embedder task. + 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 + embedder_options: _EmbedderOptions = _EmbedderOptions() + result_callback: Optional[ + Callable[[embeddings_module.EmbeddingResult, image_module.Image, + int], None]] = None + + @doc_controls.do_not_generate_docs + def to_pb2(self) -> _ImageEmbedderGraphOptionsProto: + """Generates an ImageEmbedderOptions 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 + embedder_options_proto = self.embedder_options.to_pb2() + + return _ImageEmbedderGraphOptionsProto( + base_options=base_options_proto, + embedder_options=embedder_options_proto + ) + + +class ImageEmbedder(base_vision_task_api.BaseVisionTaskApi): + """Class that performs embedding extraction on images.""" + + @classmethod + def create_from_model_path(cls, model_path: str) -> 'ImageEmbedder': + """Creates an `ImageEmbedder` object from a TensorFlow Lite model and the + default `ImageEmbedderOptions`. + + Note that the created `ImageEmbedder` instance is in image mode, for + embedding image on single image inputs. + + Args: + model_path: Path to the model. + + Returns: + `ImageEmbedder` object that's created from the model file and the default + `ImageEmbedderOptions`. + + Raises: + ValueError: If failed to create `ImageClassifier` 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 = ImageEmbedderOptions( + base_options=base_options, running_mode=_RunningMode.IMAGE) + return cls.create_from_options(options) + + @classmethod + def create_from_options(cls, + options: ImageEmbedderOptions) -> 'ImageEmbedder': + """Creates the `ImageEmbedder` object from image embedder options. + + Args: + options: Options for the image embedder task. + + Returns: + `ImageEmbedder` object that's created from `options`. + + Raises: + ValueError: If failed to create `ImageEmbedder` object from + `ImageEmbedderOptions` 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 + embedding_result_proto = packet_getter.get_proto( + output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) + + embedding_result = embeddings_module.EmbeddingResult([ + embeddings_module.Embeddings.create_from_pb2(embedding) + for embedding in embedding_result_proto.embeddings + ]) + image = packet_getter.get_image(output_packets[_IMAGE_OUT_STREAM_NAME]) + timestamp = output_packets[_IMAGE_OUT_STREAM_NAME].timestamp + options.result_callback(embedding_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_NAME]), + ], + output_streams=[ + ':'.join([_EMBEDDING_RESULT_TAG, + _EMBEDDING_RESULT_OUT_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 embed( + self, + image: image_module.Image, + roi: Optional[_NormalizedRect] = None + ) -> embeddings_module.EmbeddingResult: + """Performs image embedding extraction on the provided MediaPipe Image. + Extraction is performed on the region of interest specified by the `roi` + argument if provided, or on the entire image otherwise. + + Args: + image: MediaPipe Image. + roi: The region of interest. + + Returns: + A embedding result object that contains a list of embeddings. + + Raises: + ValueError: If any of the input arguments is invalid. + RuntimeError: If image embedder 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_NAME: packet_creator.create_proto(norm_rect.to_pb2())}) + embedding_result_proto = packet_getter.get_proto( + output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) + + return embeddings_module.EmbeddingResult([ + embeddings_module.Embeddings.create_from_pb2(embedding) + for embedding in embedding_result_proto.embeddings + ]) + + def embed_for_video( + self, image: image_module.Image, + timestamp_ms: int, + roi: Optional[_NormalizedRect] = None + ) -> embeddings_module.EmbeddingResult: + """Performs image embedding extraction on the provided video frames. + Extraction is performed on the region of interested specified by the `roi` + argument if provided, or on the entire image otherwise. + + Only use this method when the ImageEmbedder 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: + A embedding result object that contains a list of embeddings. + + Raises: + ValueError: If any of the input arguments is invalid. + RuntimeError: If image embedder 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_NAME: packet_creator.create_proto(norm_rect.to_pb2()).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) + }) + embedding_result_proto = packet_getter.get_proto( + output_packets[_EMBEDDING_RESULT_OUT_STREAM_NAME]) + + return embeddings_module.EmbeddingResult([ + embeddings_module.Embeddings.create_from_pb2(embedding) + for embedding in embedding_result_proto.embeddings + ]) + + def embed_async( + self, + image: image_module.Image, + timestamp_ms: int, + roi: Optional[_NormalizedRect] = None + ) -> None: + """ Sends live image data to embedder, and the results will be available via + the "result_callback" provided in the ImageEmbedderOptions. Embedding + extraction is performed on the region of interested specified by the `roi` + argument if provided, or on the entire image otherwise. + + Only use this method when the ImageEmbedder 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 `ImageEmbedderOptions`. The + `embed_async` method is designed to process live stream data such as + camera input. To lower the overall latency, image embedder may drop the + input images if needed. In other words, it's not guaranteed to have output + per input image. + + The `result_callback` provides: + - A embedding result object that contains a list of embeddings. + - The input image that the image embedder 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 image + embedder 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_NAME: packet_creator.create_proto(norm_rect.to_pb2()).at( + timestamp_ms * _MICRO_SECONDS_PER_MILLISECOND) + })