summaryrefslogtreecommitdiff
path: root/cli/app/search/image.py
diff options
context:
space:
mode:
authorJules Laplace <julescarbon@gmail.com>2019-12-10 22:23:04 +0100
committerJules Laplace <julescarbon@gmail.com>2019-12-10 22:23:04 +0100
commit0458542e4d06ae7aaae23c15e04ef43f54ad4f8d (patch)
treebcf584264b950a62500a7f9bc3c4f5703848a8bd /cli/app/search/image.py
parentc7ad87acbce1b307b49489eb11a6f5f8740a66e3 (diff)
refactor and add hdf5 support
Diffstat (limited to 'cli/app/search/image.py')
-rw-r--r--cli/app/search/image.py87
1 files changed, 87 insertions, 0 deletions
diff --git a/cli/app/search/image.py b/cli/app/search/image.py
new file mode 100644
index 0000000..f800a33
--- /dev/null
+++ b/cli/app/search/image.py
@@ -0,0 +1,87 @@
+import cv2 as cv
+import numpy as np
+
+def image_to_uint8(x):
+ """Converts [-1, 1] float array to [0, 255] uint8."""
+ x = np.asarray(x)
+ x = (256. / 2.) * (x + 1.)
+ x = np.clip(x, 0, 255)
+ x = x.astype(np.uint8)
+ return x
+
+def imconvert_uint8(im):
+ im = np.clip(((im + 1) / 2.0) * 256, 0, 255)
+ im = np.uint8(im)
+ return im
+
+def imconvert_float32(im):
+ im = np.float32(im)
+ im = (im / 256) * 2.0 - 1
+ return im
+
+def imread(filename):
+ img = cv.imread(filename, cv.IMREAD_UNCHANGED)
+ if img is not None:
+ if len(img.shape) > 2:
+ img = img[...,::-1]
+ return img
+
+def imwrite(filename, img):
+ if img is not None:
+ if len(img.shape) > 2:
+ img = img[...,::-1]
+ return cv.imwrite(filename, img)
+
+def imgrid(imarray, cols=5, pad=1):
+ if imarray.dtype != np.uint8:
+ raise ValueError('imgrid input imarray must be uint8')
+ pad = int(pad)
+ assert pad >= 0
+ cols = int(cols)
+ assert cols >= 1
+ N, H, W, C = imarray.shape
+ rows = int(np.ceil(N / float(cols)))
+ batch_pad = rows * cols - N
+ assert batch_pad >= 0
+ post_pad = [batch_pad, pad, pad, 0]
+ pad_arg = [[0, p] for p in post_pad]
+ imarray = np.pad(imarray, pad_arg, 'constant', constant_values=255)
+ H += pad
+ W += pad
+ grid = (imarray
+ .reshape(rows, cols, H, W, C)
+ .transpose(0, 2, 1, 3, 4)
+ .reshape(rows*H, cols*W, C))
+ if pad:
+ grid = grid[:-pad, :-pad]
+ return grid
+
+def resize_and_crop_image(target_im, opt_dims):
+ w = target_im.shape[1]
+ h = target_im.shape[0]
+ if w <= h:
+ scale = opt_dims / w
+ else:
+ scale = opt_dims / h
+ #print("{} {}".format(w, h))
+ target_im = cv.resize(target_im,(0,0), fx=scale, fy=scale)
+
+ w = target_im.shape[1]
+ h = target_im.shape[0]
+
+ x0 = 0
+ x1 = opt_dims
+ y0 = 0
+ y1 = opt_dims
+ if w > opt_dims:
+ x0 += int((w - opt_dims) / 2)
+ x1 += x0
+ if h > opt_dims:
+ y0 += int((h - opt_dims) / 2)
+ y1 += y0
+
+ phi_target = imconvert_float32(target_im)
+ phi_target = phi_target[y0:y1,x0:x1]
+ if phi_target.shape[2] == 4:
+ phi_target = phi_target[:,:,1:4]
+ return phi_target