1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import os import argparse import deepwatermap import tifffile as tiff import numpy as np import cv2 import matplotlib.pyplot as plt from download_data import download_from_gdrive from projection import set_projection import glob import tensorflow as tf
def find_padding(v, divisor=32): v_divisible = max(divisor, int(divisor * np.ceil( v / divisor ))) total_pad = v_divisible - v pad_1 = total_pad // 2 pad_2 = total_pad - pad_1 return pad_1, pad_2
def predict(checkpoint_path, image_path, save_path): image = tiff.imread(image_path) pad_r = find_padding(image.shape[0]) pad_c = find_padding(image.shape[1]) image = np.pad(image, ((pad_r[0], pad_r[1]), (pad_c[0], pad_c[1]), (0, 0)), 'reflect') image = image.astype(np.float32) image = image - np.min(image) image = image / np.maximum(np.max(image), 1) image = np.expand_dims(image, axis=0) dwm = model.predict(image) dwm = np.squeeze(dwm) dwm = dwm[pad_r[0]:-pad_r[1], pad_c[0]:-pad_c[1]] dwm = 1./(1+np.exp(-(16*(dwm-0.5)))) dwm = np.clip(dwm, 0, 1) cv2.imwrite(save_path, dwm * 255)
def load_model_gpus(checkpoint_path): strategy = tf.distribute.MirroredStrategy() with strategy.scope(): model = deepwatermap.model() model.load_weights(checkpoint_path) return model
if __name__ == '__main__': work_dir = os.path.dirname(os.path.abspath(__file__)) in_image_folder = "sample_data" use_png_ext = True output_dir = os.path.join(work_dir, "results") if not os.path.exists(output_dir): os.makedirs(output_dir) image_paths = glob.glob(os.path.join(work_dir, in_image_folder, '*.tif'))
gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) except RuntimeError as e: print(e)
batch_size = 4 checkpoint_path = os.path.join(work_dir, "checkpoints/cp.135.ckpt") model = load_model_gpus(checkpoint_path) num_gpus = len(gpus)
image_per_gpu = len(image_paths) // num_gpus for i in range(num_gpus): gpu_image_paths = image_paths[i * image_per_gpu : (i+1) * image_per_gpu] if i == num_gpus - 1 and len(image_paths) % num_gpus != 0: gpu_image_paths += image_paths[num_gpus * image_per_gpu:] for in_image_path in gpu_image_paths: basename, extension = os.path.splitext(os.path.basename(in_image_path)) if use_png_ext: extension = ".png" out_image_name = basename + "_water" + extension out_image_path = os.path.join(output_dir, out_image_name) predict(checkpoint_path, in_image_path, out_image_path) if not use_png_ext: set_projection(out_image_path, template_raster=in_image_path) print("\nOutput path: {}".format(out_image_path))
|