|
| 1 | +"""Model Wrapper of OTX Visual Prompting.""" |
| 2 | + |
| 3 | +# Copyright (C) 2023 Intel Corporation |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions |
| 15 | +# and limitations under the License. |
| 16 | + |
| 17 | +from typing import Any, Dict, Tuple |
| 18 | + |
| 19 | +import cv2 |
| 20 | +import numpy as np |
| 21 | +from openvino.model_zoo.model_api.models import ImageModel |
| 22 | +from openvino.model_zoo.model_api.models.types import NumericalValue |
| 23 | + |
| 24 | +from otx.algorithms.segmentation.adapters.openvino.model_wrappers.blur import ( |
| 25 | + BlurSegmentation, |
| 26 | +) |
| 27 | +from otx.api.utils.segmentation_utils import create_hard_prediction_from_soft_prediction |
| 28 | + |
| 29 | + |
| 30 | +class ImageEncoder(ImageModel): |
| 31 | + """Image encoder class for visual prompting of openvino model wrapper.""" |
| 32 | + |
| 33 | + __model__ = "image_encoder" |
| 34 | + |
| 35 | + @classmethod |
| 36 | + def parameters(cls) -> Dict[str, Any]: # noqa: D102 |
| 37 | + parameters = super().parameters() |
| 38 | + parameters["resize_type"].default_value = "fit_to_window" |
| 39 | + parameters["mean_values"].default_value = [123.675, 116.28, 103.53] |
| 40 | + parameters["scale_values"].default_value = [58.395, 57.12, 57.375] |
| 41 | + return parameters |
| 42 | + |
| 43 | + |
| 44 | +class Decoder(BlurSegmentation): |
| 45 | + """Decoder class for visual prompting of openvino model wrapper. |
| 46 | +
|
| 47 | + TODO (sungchul): change parent class |
| 48 | + """ |
| 49 | + |
| 50 | + __model__ = "decoder" |
| 51 | + |
| 52 | + def preprocess(self, bbox: np.ndarray, original_size: Tuple[int]) -> Dict[str, Any]: |
| 53 | + """Ready decoder inputs.""" |
| 54 | + point_coords = bbox.reshape((-1, 2, 2)) |
| 55 | + point_labels = np.array([2, 3], dtype=np.float32).reshape((-1, 2)) |
| 56 | + inputs_decoder = { |
| 57 | + "point_coords": point_coords, |
| 58 | + "point_labels": point_labels, |
| 59 | + # TODO (sungchul): how to generate mask_input and has_mask_input |
| 60 | + "mask_input": np.zeros((1, 1, 256, 256), dtype=np.float32), |
| 61 | + "has_mask_input": np.zeros((1, 1), dtype=np.float32), |
| 62 | + "orig_size": np.array(original_size, dtype=np.float32).reshape((-1, 2)), |
| 63 | + } |
| 64 | + return inputs_decoder |
| 65 | + |
| 66 | + @classmethod |
| 67 | + def parameters(cls): # noqa: D102 |
| 68 | + parameters = super().parameters() |
| 69 | + parameters.update({"image_size": NumericalValue(value_type=int, default_value=1024, min=0, max=2048)}) |
| 70 | + return parameters |
| 71 | + |
| 72 | + def _get_inputs(self): |
| 73 | + """Get input layer name and shape.""" |
| 74 | + image_blob_names = [name for name in self.inputs.keys()] |
| 75 | + image_info_blob_names = [] |
| 76 | + return image_blob_names, image_info_blob_names |
| 77 | + |
| 78 | + def _get_outputs(self): |
| 79 | + """Get output layer name and shape.""" |
| 80 | + layer_name = "low_res_masks" |
| 81 | + layer_shape = self.outputs[layer_name].shape |
| 82 | + |
| 83 | + if len(layer_shape) == 3: |
| 84 | + self.out_channels = 0 |
| 85 | + elif len(layer_shape) == 4: |
| 86 | + self.out_channels = layer_shape[1] |
| 87 | + else: |
| 88 | + raise Exception(f"Unexpected output layer shape {layer_shape}. Only 4D and 3D output layers are supported") |
| 89 | + |
| 90 | + return layer_name |
| 91 | + |
| 92 | + def postprocess(self, outputs: Dict[str, np.ndarray], meta: Dict[str, Any]) -> Tuple[np.ndarray, np.ndarray]: |
| 93 | + """Postprocess to convert soft prediction to hard prediction. |
| 94 | +
|
| 95 | + Args: |
| 96 | + outputs (Dict[str, np.ndarray]): The output of the model. |
| 97 | + meta (Dict[str, Any]): Contain label and original size. |
| 98 | +
|
| 99 | + Returns: |
| 100 | + hard_prediction (np.ndarray): The hard prediction. |
| 101 | + soft_prediction (np.ndarray): Resized, cropped, and normalized soft prediction. |
| 102 | + """ |
| 103 | + |
| 104 | + def sigmoid(x): |
| 105 | + return 1 / (1 + np.exp(-x)) |
| 106 | + |
| 107 | + soft_prediction = outputs[self.output_blob_name].squeeze() |
| 108 | + soft_prediction = self.resize_and_crop(soft_prediction, meta["original_size"]) |
| 109 | + soft_prediction = sigmoid(soft_prediction) |
| 110 | + meta["soft_prediction"] = soft_prediction |
| 111 | + |
| 112 | + hard_prediction = create_hard_prediction_from_soft_prediction( |
| 113 | + soft_prediction=soft_prediction, |
| 114 | + soft_threshold=self.soft_threshold, |
| 115 | + blur_strength=self.blur_strength, |
| 116 | + ) |
| 117 | + |
| 118 | + probability = max(min(float(outputs["iou_predictions"]), 1.0), 0.0) |
| 119 | + meta["label"].probability = probability |
| 120 | + |
| 121 | + return hard_prediction, soft_prediction |
| 122 | + |
| 123 | + def resize_and_crop(self, soft_prediction: np.ndarray, original_size: np.ndarray) -> np.ndarray: |
| 124 | + """Resize and crop soft prediction. |
| 125 | +
|
| 126 | + Args: |
| 127 | + soft_prediction (np.ndarray): Predicted soft prediction with HxW shape. |
| 128 | + original_size (np.ndarray): The original image size. |
| 129 | +
|
| 130 | + Returns: |
| 131 | + final_soft_prediction (np.ndarray): Resized and cropped soft prediction for the original image. |
| 132 | + """ |
| 133 | + resized_soft_prediction = cv2.resize( |
| 134 | + soft_prediction, (self.image_size, self.image_size), 0, 0, interpolation=cv2.INTER_LINEAR |
| 135 | + ) |
| 136 | + |
| 137 | + prepadded_size = self.resize_longest_image_size(original_size, self.image_size).astype(np.int64) |
| 138 | + resized_cropped_soft_prediction = resized_soft_prediction[..., : prepadded_size[0], : prepadded_size[1]] |
| 139 | + |
| 140 | + original_size = original_size.astype(np.int64) |
| 141 | + h, w = original_size[0], original_size[1] |
| 142 | + final_soft_prediction = cv2.resize( |
| 143 | + resized_cropped_soft_prediction, (w, h), 0, 0, interpolation=cv2.INTER_LINEAR |
| 144 | + ) |
| 145 | + return final_soft_prediction |
| 146 | + |
| 147 | + def resize_longest_image_size(self, original_size: np.ndarray, longest_side: int) -> np.ndarray: |
| 148 | + """Resizes the longest side of the image to the given size. |
| 149 | +
|
| 150 | + Args: |
| 151 | + original_size (np.ndarray): The original image size with shape Bx2. |
| 152 | + longest_side (int): The size of the longest side. |
| 153 | +
|
| 154 | + Returns: |
| 155 | + transformed_size (np.ndarray): The transformed image size with shape Bx2. |
| 156 | + """ |
| 157 | + original_size = original_size.astype(np.float32) |
| 158 | + scale = longest_side / np.max(original_size) |
| 159 | + transformed_size = scale * original_size |
| 160 | + transformed_size = np.floor(transformed_size + 0.5).astype(np.int64) |
| 161 | + return transformed_size |
0 commit comments