diff --git a/.gitignore b/.gitignore index 10c1897..4c268f1 100644 --- a/.gitignore +++ b/.gitignore @@ -115,6 +115,7 @@ venv.bak/ .v36 .v37 .v38 +.v39 # Spyder project settings .spyderproject diff --git a/README.md b/README.md index 4c9d0b9..4a41f81 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Lobe Python API Code to run exported Lobe models in Python using the TensorFlow, TensorFlow Lite, or ONNX options. -Works with Python 3.6, 3.7, and 3.8 untested for other versions. +Works with Python 3.6, 3.7, 3.8, and 3.9 untested for other versions. ## Install ### Backend options with pip @@ -94,6 +94,10 @@ print(result.prediction) for label, confidence in result.labels: print(f"{label}: {confidence*100}%") +# Visualize the heatmap of the prediction on the image +# this shows where the model was looking to make its prediction. +heatmap = model.visualize(img) +heatmap.show() ``` Note: model predict functions should be thread-safe. If you find bugs please file an issue. diff --git a/RELEASE.md b/RELEASE.md index b1a0871..e3a1370 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,3 +1,23 @@ +# Release 0.6.0 +___ +## Breaking Changes +* Refactored the ML backends into sub-folders: + * `TFModel` class: `backends/backend_tf.py -> backends/tf/backend.py` + * `TFLiteModel` class: `backends/backend_tflite.py -> backends/tflite/backend.py` + * `ONNXModel` class: `backends/backend_onnx.py -> backends/onnx/backend.py` + +## Bug Fixes and Other Improvements +* Added `Backend` and `ImageBackend` abstract base classes in `backends/backend.py` +* Added ImageBackend classes for each ML backend: + * `TFImageModel` class: `backends/tf/image_backend.py` + * `TFLiteImageModel` class: `backends/tflite/image_backend.py` + * `ONNXImageModel` class: `backends/onnx/image_backend.py` +* Added Grad-CAM++ implementation (`ImageBackend.gradcam_plusplus(image, label) -> np.ndarray`) for visualizing +convolutional neural network heatmaps for explaining why the model predicted a certain label. +_Note:_ Grad-CAM++ only implemented currently in `TFImageModel` for TensorFlow Lobe model exports. +The visualization can be called from the top-level API of `ImageModel` -> `ImageModel.visualize(image)` + + # Release 0.5.0 ___ ## Breaking Changes diff --git a/setup.py b/setup.py index c92afcc..8eb58fc 100644 --- a/setup.py +++ b/setup.py @@ -20,8 +20,9 @@ mac_version = None requirements = [ - "pillow~=8.3.1", - "requests" + "pillow~=8.4.0", + "requests", + "matplotlib~=3.4.3", ] tf_req = "tensorflow~=2.5.0;platform_machine!='armv7l'" onnx_req = "onnxruntime~=1.8.1;platform_machine!='armv7l'" @@ -68,7 +69,7 @@ setup( name="lobe", - version="0.5.0", + version="0.6.0", description="Lobe Python SDK", long_description=readme, long_description_content_type="text/markdown", @@ -81,6 +82,5 @@ 'all': [tf_req, onnx_req], 'tf': [tf_req], 'onnx': [onnx_req], - #'tflite': [tflite_req], } ) diff --git a/src/lobe/__init__.py b/src/lobe/__init__.py index 9e5bab9..d3c33db 100644 --- a/src/lobe/__init__.py +++ b/src/lobe/__init__.py @@ -1,2 +1,2 @@ from .signature import Signature -from .model.image_model import ImageModel +from .model.image_model import ImageModel, VizEnum diff --git a/src/lobe/backends/backend.py b/src/lobe/backends/backend.py new file mode 100644 index 0000000..04b9de2 --- /dev/null +++ b/src/lobe/backends/backend.py @@ -0,0 +1,37 @@ +""" +Abstract for our backend implementations. +""" +from abc import ABC, abstractmethod + +from ..signature import Signature +from ..results import BackendResult + + +class Backend(ABC): + def __init__(self, signature: Signature): + self.signature = signature + + @abstractmethod + def predict(self, data: any) -> BackendResult: + """ + Predict the outputs by running the data through the model. + + data: can be either a single input value (such as an image array), or a dictionary mapping the input + keys from the signature to the data they should be assigned + + Returns a dictionary in the form of the signature outputs {Name: value, ...} + """ + pass + + +class ImageBackend(Backend): + def gradcam_plusplus(self, image, label: str = None): + """ + Return the heatmap from Grad-CAM++ + https://arxiv.org/abs/1710.11063 + Grad-CAM++: Improved Visual Explanations for Deep Convolutional Networks + Aditya Chattopadhyay, Anirban Sarkar, Prantik Howlader, Vineeth N Balasubramanian + """ + raise NotImplementedError( + f"Image backend {self.__class__.__name__} doesn't have a Grad-CAM++ implementation yet." + ) diff --git a/src/lobe/backends/onnx/__init__.py b/src/lobe/backends/onnx/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/lobe/backends/backend_onnx.py b/src/lobe/backends/onnx/backend.py similarity index 86% rename from src/lobe/backends/backend_onnx.py rename to src/lobe/backends/onnx/backend.py index 88e6e05..9f8d330 100644 --- a/src/lobe/backends/backend_onnx.py +++ b/src/lobe/backends/onnx/backend.py @@ -1,16 +1,20 @@ from threading import Lock -from ..signature import Signature -from ..signature_constants import TENSOR_NAME -from ..utils import decode_dict_bytes_as_str +from ...signature import Signature +from ...signature_constants import TENSOR_NAME +from ...utils import decode_dict_bytes_as_str + +ONNX_IMPORT_ERROR = """ +ERROR: This is an ONNX model and requires onnx runtime to be installed on this device. +Please install lobe-python with lobe[onnx] or lobe[all] options. +If that doesn't work, please go to https://www.onnxruntime.ai/ for install instructions. +""" try: import onnxruntime as rt except ImportError: # Needs better error text - raise ImportError( - "ERROR: This is an ONNX model and requires onnx runtime to be installed on this device. Please install lobe-python with lobe[onnx] or lobe[all] options. If that doesn't work, please go to https://www.onnxruntime.ai/ for install instructions." - ) + raise ImportError(ONNX_IMPORT_ERROR) class ONNXModel(object): diff --git a/src/lobe/backends/onnx/image_backend.py b/src/lobe/backends/onnx/image_backend.py new file mode 100644 index 0000000..08fe401 --- /dev/null +++ b/src/lobe/backends/onnx/image_backend.py @@ -0,0 +1,11 @@ +from .backend import ONNXModel +from ..backend import ImageBackend +from ...signature import ImageClassificationSignature + + +class ONNXImageModel(ONNXModel, ImageBackend): + def __init__(self, signature: ImageClassificationSignature): + super(ONNXModel, self).__init__(signature=signature) + + def gradcam_plusplus(self, image, label=None): + super(ONNXImageModel, self).gradcam_plusplus(image=image, label=label) diff --git a/src/lobe/backends/tf/__init__.py b/src/lobe/backends/tf/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/lobe/backends/backend_tf.py b/src/lobe/backends/tf/backend.py similarity index 76% rename from src/lobe/backends/backend_tf.py rename to src/lobe/backends/tf/backend.py index f2a28dc..59d7ec2 100644 --- a/src/lobe/backends/backend_tf.py +++ b/src/lobe/backends/tf/backend.py @@ -1,23 +1,31 @@ from threading import Lock -from ..signature import Signature -from ..utils import decode_dict_bytes_as_str +from ..backend import Backend +from ...signature import Signature +from ...utils import decode_dict_bytes_as_str + +TF_IMPORT_ERROR = """ +ERROR: This is a TensorFlow model and requires tensorflow to be installed on this device. +Please install lobe-python with lobe[tf] or lobe[all] options. +If that doesn't work, please go to https://www.tensorflow.org/install for instructions. +""" try: import tensorflow as tf + from tensorflow.python.training.tracking.tracking import AutoTrackable except ImportError: - raise ImportError("ERROR: This is a TensorFlow model and requires tensorflow to be installed on this device. Please install lobe-python with lobe[tf] or lobe[all] options. If that doesn't work, please go to https://www.tensorflow.org/install for instructions.") + raise ImportError(TF_IMPORT_ERROR) -class TFModel(object): +class TFModel(Backend): """ - Generic wrapper for running a tensorflow model + Generic wrapper for running a TensorFlow model from Lobe. """ def __init__(self, signature: Signature): + super(TFModel, self).__init__(signature=signature) self.lock = Lock() - self.signature = signature - self.model = tf.saved_model.load(export_dir=self.signature.model_path, tags=self.signature.tags) + self.model: AutoTrackable = tf.saved_model.load(export_dir=self.signature.model_path, tags=self.signature.tags) self.predict_fn = self.model.signatures['serving_default'] def predict(self, data): diff --git a/src/lobe/backends/tf/image_backend.py b/src/lobe/backends/tf/image_backend.py new file mode 100644 index 0000000..4e46c15 --- /dev/null +++ b/src/lobe/backends/tf/image_backend.py @@ -0,0 +1,162 @@ +from .backend import TFModel, TF_IMPORT_ERROR +from ..backend import ImageBackend +from ...signature import ImageClassificationSignature + +import numpy as np + +from ...signature_constants import SUPPORTED_EXPORT_VERSIONS, LABEL_CONFIDENCES, LABEL_CONFIDENCES_COMPAT, IMAGE_INPUT, TENSOR_NAME +from ...utils import dict_get_compat + +try: + import tensorflow as tf +except ImportError: + raise ImportError(TF_IMPORT_ERROR) + + +class TFImageModel(TFModel, ImageBackend): + signature: ImageClassificationSignature + + def __init__(self, signature: ImageClassificationSignature): + super(TFImageModel, self).__init__(signature=signature) + + def gradcam_plusplus(self, image: np.ndarray, label=None) -> np.ndarray: + """ + Implementation of Grad-CAM++, + adapted for TF 2.x from the original source: https://github.com/adityac94/Grad_CAM_plus_plus + + @article{chattopadhyay2017grad, + title={Grad-CAM++: Generalized Gradient-based Visual Explanations for Deep Convolutional Networks}, + author={Chattopadhyay, Aditya and Sarkar, Anirban and Howlader, Prantik and Balasubramanian, Vineeth N}, + journal={arXiv preprint arXiv:1710.11063}, + year={2017} + } + """ + labels = self.signature.classes + # Get the output index of the desired label for visualizing + # If no desired label is given, find the predicted label by running the model on the image + if label is None: + label_idx = self._get_predicted_label_argmax(image=image) + else: + # if we are batched, get the indices by looping, otherwise just get the index + if isinstance(label, list): + label_idx = [labels.index(_label) for _label in label] + else: + label_idx = [labels.index(label)] + # create a one-hot vector of our label indices to use as a mask for the output cost + label_idx = tf.one_hot(label_idx, depth=len(labels)) + if len(label_idx) != len(image): + raise ValueError( + f"Supplied label (or list of labels) does not match the the number of input images. Images : {len(image)}, labels: {len(label_idx)}" + ) + + with self.lock: + # now we want to get the derivatives of the output with respect to the last conv layer + # get the layer name of the confidences logits output and the last convolutional layer + last_fc_tensor, last_conv_tensor = self._get_last_fc_and_conv_tensors() + + # now get the function that returns the fc and conv tensors from the image + input_image_name = self.signature.inputs[IMAGE_INPUT][TENSOR_NAME] + last_conv_fn = self.model.prune(input_image_name, last_conv_tensor.name) + last_fc_fn = self.model.prune(last_conv_tensor.name, last_fc_tensor.name) + + # get the last conv out + last_conv_out = last_conv_fn(tf.constant(image)) + + # take the 3 derivatives of the cost wrt the conv layer + with tf.GradientTape() as t3: + t3.watch(last_conv_out) + with tf.GradientTape() as t2: + t2.watch(last_conv_out) + with tf.GradientTape() as t1: + t1.watch(last_conv_out) + last_fc_out = last_fc_fn(last_conv_out) + # get the output neuron corresponding to the class of interest + cost = last_fc_out * label_idx + # first derivative + conv_first_grad = t1.gradient(cost, last_conv_out) + # second derivative + conv_second_grad = t2.gradient(conv_first_grad, last_conv_out) + # triple derivative + conv_third_grad = t3.gradient(conv_second_grad, last_conv_out) + + batch, _, _, filters = last_conv_out.shape + + global_sum = tf.math.reduce_sum(last_conv_out, axis=[1, 2]) + + alpha_num = conv_second_grad + broadcasted_global_sum = tf.reshape(global_sum, (batch, 1, 1, filters)) + alpha_denom = conv_second_grad * 2.0 + conv_third_grad * broadcasted_global_sum + alpha_denom = tf.where(alpha_denom != 0.0, alpha_denom, tf.ones(alpha_denom.shape)) + alphas = alpha_num / alpha_denom + + weights = tf.maximum(conv_first_grad, 0.0) + + alphas_thresholding = tf.where(weights != 0.0, alphas, 0.0) + + alpha_normalization_constant = tf.math.reduce_sum(alphas_thresholding, axis=[1, 2]) + alpha_normalization_constant_processed = tf.where(alpha_normalization_constant != 0.0, + alpha_normalization_constant, + tf.ones(alpha_normalization_constant.shape)) + + alphas /= tf.reshape(alpha_normalization_constant_processed, (batch, 1, 1, filters)) + + deep_linearization_weights = tf.math.reduce_sum((weights * alphas), axis=[1, 2]) + broadcasted_deep_lin_weights = tf.reshape(deep_linearization_weights, (batch, 1, 1, filters)) + grad_CAM_map = tf.math.reduce_sum(broadcasted_deep_lin_weights * last_conv_out, axis=3) + + # Passing through ReLU + cam = tf.maximum(grad_CAM_map, 0) + cam_max = tf.math.reduce_max(cam, axis=[1, 2]) + cam /= tf.reshape(cam_max, (batch, 1, 1)) # scale 0 to 1.0 + return cam.numpy() + + def _get_predicted_label_argmax(self, image: np.ndarray): + """ + Given an image, run our model and return the array of predicted argmax indices. + """ + result = self.predict(data=image) + if self.signature.export_version not in SUPPORTED_EXPORT_VERSIONS: + raise ValueError( + f"Lobe model export version {self.signature.export_version} not supported. Need one of: {SUPPORTED_EXPORT_VERSIONS}") + + # grab the list of confidences + confidences, _ = dict_get_compat( + in_dict=result, current_key=LABEL_CONFIDENCES, compat_keys=LABEL_CONFIDENCES_COMPAT, default=[] + ) + return tf.argmax(confidences, axis=1) + + def _get_last_fc_and_conv_tensors(self): + """ + Gets the tensor that represents the last fully-connected layer outputs (logits). + Since the 'Confidences' output is the softmax tensor, its input is the last FC layer. + + Also find the tensor that is the last convolution layer's output before any pooling (this will be the + RELU output before the global max or avg pooling) + """ + confidences_out, _ = dict_get_compat( + in_dict=self.signature.outputs, current_key=LABEL_CONFIDENCES, compat_keys=LABEL_CONFIDENCES_COMPAT + ) + softmax_tensor = self.model.graph.get_tensor_by_name(confidences_out.get(TENSOR_NAME)) + # get the op (softmax)'s inputs -- the last fc layer tensor will be the only (first) input to this op + last_fc_tensor = softmax_tensor.op.inputs[0] + + # now from the last fc layer, bfs search for the closest max pooling op and find its input -- that is the + # last conv layer output (the RELU tensor) + last_conv_tensor = None + visited, queue = [], [] + queue.append(last_fc_tensor) + while queue: + tensor = queue.pop() + visited.append(tensor.name) + op = tensor.op + # if this was from the max/avg pool op, get the input tensor + # (which is the output of the last conv layer's relu) + if op.type in ["Max", "Mean"]: + last_conv_tensor = op.inputs[0] + break + else: + for input_tensor in op.inputs: + if input_tensor.name not in visited: + queue.append(input_tensor) + + return last_fc_tensor, last_conv_tensor diff --git a/src/lobe/backends/tflite/__init__.py b/src/lobe/backends/tflite/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/lobe/backends/backend_tflite.py b/src/lobe/backends/tflite/backend.py similarity index 85% rename from src/lobe/backends/backend_tflite.py rename to src/lobe/backends/tflite/backend.py index 56aefde..8accb8f 100644 --- a/src/lobe/backends/backend_tflite.py +++ b/src/lobe/backends/tflite/backend.py @@ -1,7 +1,13 @@ from threading import Lock -from ..signature import Signature -from ..signature_constants import TENSOR_NAME -from ..utils import decode_dict_bytes_as_str +from ..backend import Backend +from ...signature import Signature +from ...signature_constants import TENSOR_NAME +from ...utils import decode_dict_bytes_as_str + +TFLITE_IMPORT_ERROR = """ +ERROR: This is a TensorFlow Lite model and requires TensorFlow Lite interpreter to be installed on this device. +Please go to https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python for installation instructions for you device. +""" # first try to import the tflite interpreter from TensorFlow base library (if we have both installed) to avoid a collision try: @@ -11,20 +17,18 @@ import tflite_runtime.interpreter as tflite except ImportError: - raise ImportError( - "ERROR: This is a TensorFlow Lite model and requires TensorFlow Lite interpreter to be installed on this device. Please go to https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python for installation instructions for you device." - ) + raise ImportError(TFLITE_IMPORT_ERROR) -class TFLiteModel(object): +class TFLiteModel(Backend): """ Generic wrapper for running a TF Lite model exported from Lobe """ def __init__(self, signature: Signature): + super(TFLiteModel, self).__init__(signature=signature) model_path = "{}/{}".format( signature.model_path, signature.filename ) - self.signature = signature self.interpreter = tflite.Interpreter(model_path=model_path) self.interpreter.allocate_tensors() diff --git a/src/lobe/backends/tflite/image_backend.py b/src/lobe/backends/tflite/image_backend.py new file mode 100644 index 0000000..2f057c7 --- /dev/null +++ b/src/lobe/backends/tflite/image_backend.py @@ -0,0 +1,11 @@ +from .backend import TFLiteModel +from ..backend import ImageBackend +from ...signature import ImageClassificationSignature + + +class TFLiteImageModel(TFLiteModel, ImageBackend): + def __init__(self, signature: ImageClassificationSignature): + super(TFLiteModel, self).__init__(signature=signature) + + def gradcam_plusplus(self, image, label=None): + super(TFLiteModel, self).gradcam_plusplus(image=image, label=label) diff --git a/src/lobe/image_utils.py b/src/lobe/image_utils.py index bc0217d..9420d82 100644 --- a/src/lobe/image_utils.py +++ b/src/lobe/image_utils.py @@ -97,3 +97,12 @@ def image_to_array(image: Image.Image) -> np.ndarray: # pad with an extra batch dimension image = np.expand_dims(image, axis=0).astype(np.float32) return image + + +def array_to_image(image: np.ndarray) -> Image.Image: + # make the input array 0-255 int + image = np.uint8(image * 255) + # squeeze extra batch dimension if it exists + if image.shape[0] == 1: + image = np.squeeze(image, axis=0) + return Image.fromarray(image) diff --git a/src/lobe/model/image_model.py b/src/lobe/model/image_model.py index 9ecfc1a..7647b43 100644 --- a/src/lobe/model/image_model.py +++ b/src/lobe/model/image_model.py @@ -1,14 +1,25 @@ """ Load a Lobe saved model for image classification """ +from typing import Dict, Union, Optional, List + +import numpy as np from PIL import Image +from matplotlib import cm +from matplotlib.colors import Colormap from .model import Model -from ..signature import ImageClassificationSignature from .. import image_utils +from ..backends.backend import ImageBackend +from ..signature import ImageClassificationSignature +from ..signature_constants import TF_MODEL, TFLITE_MODEL, ONNX_MODEL from ..results import ClassificationResult +class VizEnum: + GRADCAM_PLUSPLUS = 'gradcam_plusplus' + + class ImageModel(Model): signature: ImageClassificationSignature @@ -16,15 +27,15 @@ class ImageModel(Model): def load_from_signature(cls, signature: ImageClassificationSignature): # Select the appropriate backend model_format = signature.format - if model_format == "tf": - from ..backends.backend_tf import TFModel - return cls(signature, TFModel(signature)) - elif model_format == "tf_lite": - from ..backends.backend_tflite import TFLiteModel - return cls(signature, TFLiteModel(signature)) - elif model_format == "onnx": - from ..backends.backend_onnx import ONNXModel - return cls(signature, ONNXModel(signature)) + if model_format == TF_MODEL: + from ..backends.tf.image_backend import TFImageModel + return cls(signature, TFImageModel(signature)) + elif model_format == TFLITE_MODEL: + from ..backends.tflite.image_backend import TFLiteImageModel + return cls(signature, TFLiteImageModel(signature)) + elif model_format == ONNX_MODEL: + from ..backends.onnx.image_backend import ONNXImageModel + return cls(signature, ONNXImageModel(signature)) else: raise ValueError(f"Model is an unsupported format: {model_format}") @@ -33,10 +44,15 @@ def load(cls, model_path: str): # Load the signature return cls.load_from_signature(ImageClassificationSignature(model_path)) - def __init__(self, signature: ImageClassificationSignature, backend): + def __init__(self, signature: ImageClassificationSignature, backend: ImageBackend): super(ImageModel, self).__init__(signature) self.backend = backend + # register the available visualization functions + self._viz_functions = { + VizEnum.GRADCAM_PLUSPLUS: self.backend.gradcam_plusplus, + } + def predict_from_url(self, url: str): return self.predict(image_utils.get_image_from_url(url)) @@ -51,3 +67,99 @@ def predict(self, image: Image.Image) -> ClassificationResult: results=results, labels=self.signature.classes, export_version=self.signature.export_version ) return classification_results + + def visualize( + self, + image: Union[Image.Image, List[Image.Image]], + label: Union[Optional[str], List[Optional[str]]] = None, + viz: Optional[str] = VizEnum.GRADCAM_PLUSPLUS, + colormap: Union[str, Colormap] = None, + opacity=0.5 + ) -> Union[Union[Image.Image, List[Image.Image]], Dict[str, Union[Image.Image, List[Image.Image]]]]: + """ + Visualize what the image classification model is using for its output prediction. + If label is not supplied, it will use the predicted label from running the model on the image. + You can optionally supply a matplotlib colormap for colorizing the heatmap on the image. + You can choose different options for 'viz' to return different methods: + VizEnum.GRADCAM_PLUSPLUS: Grad-CAM++ (https://arxiv.org/abs/1710.11063) Chattopadhyay et al. + COMING SOON: + VizEnum.CNN_FIXATIONS: CNN Fixations (https://arxiv.org/abs/1708.06670) Mopuri et al. + If 'None' option is given, this will return a dictionary with all options - + where the key is the same as the options above and the value is the image. + + This also works in batch mode -- pass a list of images and list of desired labels (or None for using + the predicted label). + """ + if viz is not None and viz not in self._viz_functions: + raise ValueError( + f"Visualization option `{viz}` not recognized, try one of: {list(self._viz_functions.keys())}." + ) + + # if a single image was passed, promote it to a list so we work in batch mode (and keep track if it was a list) + is_batched = True + if not isinstance(image, list): + is_batched = False + image = [image] + + # similarly promote the label to a list if it isn't + if label is not None and not isinstance(label, list): + label = [label] + + if isinstance(image, list) and isinstance(label, list) and len(image) != len(label): + raise ValueError( + f"Number of images doesn't match the supplied number of labels. Images: {len(image)} | Labels: {len(label)}" + ) + + preprocessed_images = [image_utils.preprocess_image(img, self.signature.input_image_size) for img in image] + image_arrays = np.concatenate([image_utils.image_to_array(img) for img in preprocessed_images]) + + viz_return = {} + for viz_name, viz_func in self._viz_functions.items(): + if viz is None or viz == viz_name: + viz_heatmaps = viz_func(image_arrays, label) + heatmaps_and_images = zip(viz_heatmaps, preprocessed_images) + combined_viz = [ + _image_from_heatmap( + heatmap=viz_heatmap, + image=img, + opacity=opacity, + colormap=colormap + ) + for viz_heatmap, img in heatmaps_and_images + ] + if not is_batched: + combined_viz = combined_viz[0] + viz_return[viz_name] = combined_viz + + if viz is not None: + viz_return = viz_return.get(viz) + + return viz_return + + +def _image_from_heatmap(heatmap: np.ndarray, image: Image.Image, opacity=0.5, colormap=None) -> Image.Image: + """ + Given an activation heatmap (like from Grad-CAM), create a superimposed image of the heatmap + on the given input image. + """ + # make sure our heatmap is resized to be same shape as image + width, height = image.size # pillow image + + # un-batch the heatmap to a single image if needed + if len(heatmap.shape) == 3 and heatmap.shape[0] == 1: + heatmap = np.squeeze(heatmap, axis=0) + + # Use inferno colormap by default to colorize heatmap, unless supplied kwarg + if colormap is None: + colormap = "inferno" + cmap = cm.get_cmap(colormap) + + # Expect heatmap to be floats in 0-1 range, and just grab the rgb values (not rgba) + color_heatmap = cmap(heatmap)[:, :, :3] + + heatmap_img = image_utils.array_to_image(color_heatmap) + + heatmap_img = heatmap_img.resize((height, width)) + # Return the blended heatmap overlay on the original image + blended_img = Image.blend(image, heatmap_img, opacity) + return blended_img diff --git a/src/lobe/results.py b/src/lobe/results.py index edf2658..fff5665 100644 --- a/src/lobe/results.py +++ b/src/lobe/results.py @@ -7,6 +7,8 @@ ) from .utils import dict_get_compat +BackendResult = Dict[str, any] + class ClassificationResult: """ @@ -19,7 +21,7 @@ class ClassificationResult: These can be batched and contain the results for many examples. """ - def __init__(self, results: Dict[str, any], labels: List[str] = None, export_version: int = None): + def __init__(self, results: BackendResult, labels: List[str] = None, export_version: int = None): """ Parse the classification results from a dictionary in the form {Name: val} for each output in the signature diff --git a/src/lobe/signature_constants.py b/src/lobe/signature_constants.py index b773fc3..d367c8d 100644 --- a/src/lobe/signature_constants.py +++ b/src/lobe/signature_constants.py @@ -40,3 +40,8 @@ # Special known input key IMAGE_INPUT = 'Image' + +# Values of our model types +TF_MODEL = 'tf' +TFLITE_MODEL = 'tf_lite' +ONNX_MODEL = 'onnx'