|
@@ -1,13 +1,34 @@
|
|
|
import numpy as np
|
|
|
+from PIL.Image import Image as PIL_Image
|
|
|
|
|
|
DEFAULT_RATIO = np.sqrt(49 / 400)
|
|
|
|
|
|
def __expand_parts(p):
|
|
|
return p[:, 0], p[:, 1:3], p[:, 3].astype(bool)
|
|
|
|
|
|
+def dimensions(im):
|
|
|
+ if isinstance(im, np.ndarray):
|
|
|
+ assert im.ndim == 3, "Only RGB images are currently supported!"
|
|
|
+ return im.shape
|
|
|
+ elif isinstance(im, PIL_Image):
|
|
|
+ w, h = im.size
|
|
|
+ c = len(im.getbands())
|
|
|
+ # assert c == 3, "Only RGB images are currently supported!"
|
|
|
+ return h, w, c
|
|
|
+ else:
|
|
|
+ raise ValueError("Unknown image instance ({})!".format(type(im)))
|
|
|
+
|
|
|
+def asarray(im, dtype=np.uint8):
|
|
|
+ if isinstance(im, np.ndarray):
|
|
|
+ return im.astype(dtype)
|
|
|
+ elif isinstance(im, PIL_Image):
|
|
|
+ return np.asarray(im, dtype=dtype)
|
|
|
+ else:
|
|
|
+ raise ValueError("Unknown image instance ({})!".format(type(im)))
|
|
|
+
|
|
|
|
|
|
def uniform_parts(im, ratio=DEFAULT_RATIO, round_op=np.floor):
|
|
|
- h, w, c = im.shape
|
|
|
+ h, w, c = dimensions(im)
|
|
|
|
|
|
part_w = round_op(w * ratio).astype(np.int32)
|
|
|
part_h = round_op(h * ratio).astype(np.int32)
|
|
@@ -31,11 +52,9 @@ def visible_part_locs(p):
|
|
|
|
|
|
|
|
|
def crops(im, xy, ratio=DEFAULT_RATIO, padding_mode="edge"):
|
|
|
- assert im.ndim == 3, "Only RGB images are currently supported!"
|
|
|
-
|
|
|
- h, w, c = im.shape
|
|
|
+ h, w, c = dimensions(im)
|
|
|
crop_h, crop_w = int(h * ratio), int(w * ratio)
|
|
|
- crops = np.zeros((xy.shape[1], crop_h, crop_w, c), dtype=im.dtype)
|
|
|
+ crops = np.zeros((xy.shape[1], crop_h, crop_w, c), dtype=np.uint8)
|
|
|
|
|
|
pad_h, pad_w = crop_h // 2, crop_w // 2
|
|
|
|
|
@@ -49,15 +68,15 @@ def crops(im, xy, ratio=DEFAULT_RATIO, padding_mode="edge"):
|
|
|
|
|
|
def visible_crops(im, p, *args, **kw):
|
|
|
idxs, locs, vis = __expand_parts(p)
|
|
|
- parts = crops(im, locs[vis].T, *args, **kw)
|
|
|
+ parts = crops(asarray(im), locs[vis].T, *args, **kw)
|
|
|
res = np.zeros((len(idxs),) + parts.shape[1:], dtype=parts.dtype)
|
|
|
res[vis] = parts
|
|
|
return res
|
|
|
|
|
|
def reveal_parts(im, xy, ratio=DEFAULT_RATIO):
|
|
|
- h, w, c = im.shape
|
|
|
+ h, w, c = dimensions(im)
|
|
|
crop_h, crop_w = int(h * ratio), int(w * ratio)
|
|
|
-
|
|
|
+ im = asarray(im)
|
|
|
res = np.zeros_like(im)
|
|
|
for x, y in xy.T:
|
|
|
x0, y0 = max(x - crop_w // 2, 0), max(y - crop_h // 2, 0)
|