2017-08-17 19:16:19 +00:00
|
|
|
import random
|
2017-08-16 12:24:29 +00:00
|
|
|
|
2019-10-24 19:37:21 +00:00
|
|
|
import numpy as np
|
2017-08-16 12:24:29 +00:00
|
|
|
|
2018-06-08 17:27:32 +00:00
|
|
|
|
|
|
|
def hwc_to_chw(img):
|
|
|
|
return np.transpose(img, axes=[2, 0, 1])
|
2017-08-17 19:16:19 +00:00
|
|
|
|
2019-10-24 19:37:21 +00:00
|
|
|
|
2017-08-19 08:59:51 +00:00
|
|
|
def resize_and_crop(pilimg, scale=0.5, final_height=None):
|
2017-08-16 12:24:29 +00:00
|
|
|
w = pilimg.size[0]
|
|
|
|
h = pilimg.size[1]
|
|
|
|
newW = int(w * scale)
|
|
|
|
newH = int(h * scale)
|
2017-08-17 19:16:19 +00:00
|
|
|
|
|
|
|
if not final_height:
|
|
|
|
diff = 0
|
|
|
|
else:
|
|
|
|
diff = newH - final_height
|
2017-08-16 12:24:29 +00:00
|
|
|
|
|
|
|
img = pilimg.resize((newW, newH))
|
|
|
|
img = img.crop((0, diff // 2, newW, newH - diff // 2))
|
2019-10-24 19:37:21 +00:00
|
|
|
ar = np.array(img, dtype=np.float32)
|
|
|
|
if len(ar.shape) == 2:
|
|
|
|
# for greyscale images, add a new axis
|
|
|
|
ar = np.expand_dims(ar, axis=2)
|
|
|
|
return ar
|
2017-08-17 19:16:19 +00:00
|
|
|
|
|
|
|
def batch(iterable, batch_size):
|
|
|
|
"""Yields lists by batch"""
|
|
|
|
b = []
|
|
|
|
for i, t in enumerate(iterable):
|
|
|
|
b.append(t)
|
2018-04-09 03:15:24 +00:00
|
|
|
if (i + 1) % batch_size == 0:
|
2017-08-17 19:16:19 +00:00
|
|
|
yield b
|
|
|
|
b = []
|
|
|
|
|
|
|
|
if len(b) > 0:
|
|
|
|
yield b
|
|
|
|
|
2019-10-24 19:37:21 +00:00
|
|
|
|
2017-08-17 19:16:19 +00:00
|
|
|
def split_train_val(dataset, val_percent=0.05):
|
|
|
|
dataset = list(dataset)
|
|
|
|
length = len(dataset)
|
|
|
|
n = int(length * val_percent)
|
|
|
|
random.shuffle(dataset)
|
|
|
|
return {'train': dataset[:-n], 'val': dataset[-n:]}
|
|
|
|
|
|
|
|
|
|
|
|
def normalize(x):
|
|
|
|
return x / 255
|
2017-08-21 16:00:07 +00:00
|
|
|
|
|
|
|
|
2018-06-08 17:27:32 +00:00
|
|
|
# credits to https://stackoverflow.com/users/6076729/manuel-lagunas
|
2017-09-26 19:00:51 +00:00
|
|
|
def rle_encode(mask_image):
|
|
|
|
pixels = mask_image.flatten()
|
|
|
|
# We avoid issues with '1' at the start or end (at the corners of
|
|
|
|
# the original image) by setting those pixels to '0' explicitly.
|
|
|
|
# We do not expect these to be non-zero for an accurate mask,
|
|
|
|
# so this should not harm the score.
|
|
|
|
pixels[0] = 0
|
|
|
|
pixels[-1] = 0
|
|
|
|
runs = np.where(pixels[1:] != pixels[:-1])[0] + 2
|
|
|
|
runs[1::2] = runs[1::2] - runs[:-1:2]
|
|
|
|
return runs
|