utils.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import numpy as np
  2. DEFAULT_RATIO = np.sqrt(49 / 400)
  3. def __expand_parts(p):
  4. return p[:, 0], p[:, 1:3], p[:, 3].astype(bool)
  5. def uniform_part_locs(im, ratio=DEFAULT_RATIO, round_op=np.floor):
  6. h, w, c = im.shape
  7. part_w = round_op(w * ratio).astype(np.int32)
  8. part_h = round_op(h * ratio).astype(np.int32)
  9. n, m = w // part_w, h // part_h
  10. idxs = np.arange(n*m)
  11. locs = np.zeros((2, n*m), dtype=np.int32)
  12. for x in range(n):
  13. for y in range(m):
  14. i = y * n + x
  15. x0, y0 = x * part_w, y * part_h
  16. locs[:, i] = [x0 + part_w // 2, y0 + part_h // 2]
  17. return idxs, locs
  18. def visible_part_locs(p):
  19. idxs, locs, vis = __expand_parts(p)
  20. return idxs[vis], locs[vis].T
  21. def crops(im, xy, ratio=DEFAULT_RATIO, padding_mode="edge"):
  22. assert im.ndim == 3, "Only RGB images are currently supported!"
  23. h, w, c = im.shape
  24. crop_h, crop_w = int(h * ratio), int(w * ratio)
  25. crops = np.zeros((xy.shape[1], crop_h, crop_w, c), dtype=im.dtype)
  26. pad_h, pad_w = crop_h // 2, crop_w // 2
  27. padded_im = np.pad(im, [(pad_h, pad_h), (pad_w, pad_w), [0,0]], mode=padding_mode)
  28. for i, (x, y) in enumerate(xy.T):
  29. x0, y0 = x - crop_w // 2 + pad_w, y - crop_h // 2 + pad_h
  30. crops[i] = padded_im[y0:y0+crop_h, x0:x0+crop_w]
  31. return crops
  32. def visible_crops(im, p, *args, **kw):
  33. idxs, locs, vis = __expand_parts(p)
  34. parts = crops(im, locs[vis].T, *args, **kw)
  35. res = np.zeros((len(idxs),) + parts.shape[1:], dtype=parts.dtype)
  36. res[vis] = parts
  37. return res
  38. def reveal_parts(im, xy, ratio=DEFAULT_RATIO):
  39. h, w, c = im.shape
  40. crop_h, crop_w = int(h * ratio), int(w * ratio)
  41. res = np.zeros_like(im)
  42. for x, y in xy.T:
  43. x0, y0 = max(x - crop_w // 2, 0), max(y - crop_h // 2, 0)
  44. res[y0:y0+crop_h, x0:x0+crop_w] = im[y0:y0+crop_h, x0:x0+crop_w]
  45. return res