Convert a raw image to properly resized, padded, and normalized ndarray.
(raw_image: np.ndarray)
| 56 | |
| 57 | |
| 58 | def _preprocess(raw_image: np.ndarray) -> Union[np.ndarray, float]: |
| 59 | """Convert a raw image to properly resized, padded, and normalized ndarray.""" |
| 60 | # (1) convert to tf.Tensor and float32. |
| 61 | img_tensor = tf.convert_to_tensor(raw_image, dtype=tf.float32) |
| 62 | |
| 63 | # (2) pad to square. |
| 64 | height, width = img_tensor.shape[:2] |
| 65 | maximum_side = tf.maximum(height, width) |
| 66 | height_pad = maximum_side - height |
| 67 | width_pad = maximum_side - width |
| 68 | img_tensor = tf.pad( |
| 69 | img_tensor, [[0, height_pad], [0, width_pad], [0, 0]], |
| 70 | constant_values=127) |
| 71 | ratio = maximum_side / _IMG_SIZE.value |
| 72 | # (3) resize long side to the maximum length. |
| 73 | img_tensor = tf.image.resize( |
| 74 | img_tensor, (_IMG_SIZE.value, _IMG_SIZE.value)) |
| 75 | img_tensor = tf.cast(img_tensor, tf.uint8) |
| 76 | |
| 77 | # (4) normalize |
| 78 | img_tensor = utilities.normalize_image_to_range(img_tensor) |
| 79 | |
| 80 | # (5) Add batch dimension and return as numpy array. |
| 81 | return tf.expand_dims(img_tensor, 0).numpy(), float(ratio) |
| 82 | |
| 83 | |
| 84 | def load_model() -> tf_keras.layers.Layer: |