utils.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import numpy as np
  2. from PIL.Image import Image as PIL_Image
  3. DEFAULT_RATIO = np.sqrt(49 / 400)
  4. def __expand_parts(p):
  5. return p[:, 0], p[:, 1:3], p[:, 3].astype(bool)
  6. def dimensions(im):
  7. if isinstance(im, np.ndarray):
  8. assert im.ndim == 3, "Only RGB images are currently supported!"
  9. return im.shape
  10. elif isinstance(im, PIL_Image):
  11. w, h = im.size
  12. c = len(im.getbands())
  13. # assert c == 3, "Only RGB images are currently supported!"
  14. return h, w, c
  15. else:
  16. raise ValueError("Unknown image instance ({})!".format(type(im)))
  17. def asarray(im, dtype=np.uint8):
  18. if isinstance(im, np.ndarray):
  19. return im.astype(dtype)
  20. elif isinstance(im, PIL_Image):
  21. return np.asarray(im, dtype=dtype)
  22. else:
  23. raise ValueError("Unknown image instance ({})!".format(type(im)))
  24. def uniform_parts(im, ratio=DEFAULT_RATIO, round_op=np.floor):
  25. h, w, c = dimensions(im)
  26. part_w = round_op(w * ratio).astype(np.int32)
  27. part_h = round_op(h * ratio).astype(np.int32)
  28. n, m = w // part_w, h // part_h
  29. parts = np.ones((n*m, 4), dtype=int)
  30. parts[:, 0] = np.arange(n*m)
  31. for x in range(n):
  32. for y in range(m):
  33. i = y * n + x
  34. x0, y0 = x * part_w, y * part_h
  35. parts[i, 1:3] = [x0 + part_w // 2, y0 + part_h // 2]
  36. return parts
  37. def visible_part_locs(p):
  38. idxs, locs, vis = __expand_parts(p)
  39. return idxs[vis], locs[vis].T
  40. def crops(im, xy, ratio=DEFAULT_RATIO, padding_mode="edge"):
  41. h, w, c = dimensions(im)
  42. crop_h, crop_w = int(h * ratio), int(w * ratio)
  43. crops = np.zeros((xy.shape[1], crop_h, crop_w, c), dtype=np.uint8)
  44. pad_h, pad_w = crop_h // 2, crop_w // 2
  45. padded_im = np.pad(im, [(pad_h, pad_h), (pad_w, pad_w), [0,0]], mode=padding_mode)
  46. for i, (x, y) in enumerate(xy.T):
  47. x0, y0 = x - crop_w // 2 + pad_w, y - crop_h // 2 + pad_h
  48. crops[i] = padded_im[y0:y0+crop_h, x0:x0+crop_w]
  49. return crops
  50. def visible_crops(im, p, *args, **kw):
  51. idxs, locs, vis = __expand_parts(p)
  52. parts = crops(asarray(im), locs[vis].T, *args, **kw)
  53. res = np.zeros((len(idxs),) + parts.shape[1:], dtype=parts.dtype)
  54. res[vis] = parts
  55. return res
  56. def reveal_parts(im, xy, ratio=DEFAULT_RATIO):
  57. h, w, c = dimensions(im)
  58. crop_h, crop_w = int(h * ratio), int(w * ratio)
  59. im = asarray(im)
  60. res = np.zeros_like(im)
  61. for x, y in xy.T:
  62. x0, y0 = max(x - crop_w // 2, 0), max(y - crop_h // 2, 0)
  63. res[y0:y0+crop_h, x0:x0+crop_w] = im[y0:y0+crop_h, x0:x0+crop_w]
  64. return res
  65. def select(crops, mask):
  66. selected = np.zeros_like(crops)
  67. selected[mask] = crops[mask]
  68. return selected
  69. def selection_mask(idxs, n):
  70. return np.bincount(idxs, minlength=n).astype(bool)
  71. def random_select(idxs, xy, part_crops, *args, **kw):
  72. rnd_idxs = random_idxs(np.arange(len(idxs)), *args, **kw)
  73. idxs = idxs[rnd_idxs]
  74. xy = xy[:, rnd_idxs]
  75. mask = selection_mask(idxs, len(part_crops))
  76. selected_crops = select(part_crops, mask)
  77. return idxs, xy, selected_crops
  78. def random_idxs(idxs, rnd=None, n_parts=None):
  79. if rnd is None or isinstance(rnd, int):
  80. rnd = np.random.RandomState(rnd)
  81. else:
  82. assert isinstance(rnd, np.random.RandomState), \
  83. "'rnd' should be either a random seed or a RandomState instance!"
  84. n_parts = n_parts or rnd.randint(1, len(idxs))
  85. res = rnd.choice(idxs, n_parts, replace=False)
  86. res.sort()
  87. return res