Create helper.py
Browse files
helper.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from matplotlib import gridspec
|
3 |
+
import matplotlib.pylab as plt
|
4 |
+
import numpy as np
|
5 |
+
import tensorflow as tf
|
6 |
+
|
7 |
+
|
8 |
+
def crop_center(image):
|
9 |
+
"""Returns a cropped square image."""
|
10 |
+
shape = image.shape
|
11 |
+
new_shape = min(shape[1], shape[2])
|
12 |
+
offset_y = max(shape[1] - shape[2], 0) // 2
|
13 |
+
offset_x = max(shape[2] - shape[1], 0) // 2
|
14 |
+
image = tf.image.crop_to_bounding_box(
|
15 |
+
image, offset_y, offset_x, new_shape, new_shape)
|
16 |
+
return image
|
17 |
+
|
18 |
+
def load_image(image_url, image_size=(256, 256), preserve_aspect_ratio=True):
|
19 |
+
"""Loads and preprocesses images."""
|
20 |
+
# Cache image file locally.
|
21 |
+
image_path = tf.keras.utils.get_file(os.path.basename(image_url)[-128:], image_url)
|
22 |
+
# Load and convert to float32 numpy array, add batch dimension, and normalize to range [0, 1].
|
23 |
+
img = plt.imread(image_path).astype(np.float32)[np.newaxis, ...]
|
24 |
+
if img.max() > 1.0:
|
25 |
+
img = img / 255.
|
26 |
+
if len(img.shape) == 3:
|
27 |
+
img = tf.stack([img, img, img], axis=-1)
|
28 |
+
img = crop_center(img)
|
29 |
+
img = tf.image.resize(img, image_size, preserve_aspect_ratio=True)
|
30 |
+
return img
|