image.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. from imageio import imread
  2. from os.path import isfile
  3. import copy
  4. import numpy as np
  5. from . import utils
  6. def should_have_parts(func):
  7. def inner(self, *args, **kwargs):
  8. assert self.has_parts, "parts are not present!"
  9. return func(self, *args, **kwargs)
  10. return inner
  11. class ImageWrapper(object):
  12. def __init__(self, im_path, label, parts=None, mode="RGB"):
  13. if isinstance(im_path, str):
  14. assert isfile(im_path), "Image \"{}\" does not exist!".format(im_path)
  15. self.im = imread(im_path, pilmode=mode)
  16. else:
  17. self.im = im_path
  18. self.label = label
  19. self.parts = parts
  20. self.parent = None
  21. def as_tuple(self):
  22. return self.im, self.parts, self.label
  23. def copy(self):
  24. new = copy.deepcopy(self)
  25. new.parent = self
  26. return new
  27. def crop(self, x, y, w, h):
  28. result = self.copy()
  29. result.im = self.im[y:y+h, x:x+w]
  30. if self.has_parts:
  31. result.parts[:, 1] -= x
  32. result.parts[:, 2] -= y
  33. return result
  34. @should_have_parts
  35. def hide_parts_outside_bb(self, x, y, w, h):
  36. idxs, (xs,ys) = self.visible_part_locs()
  37. f = np.logical_and
  38. mask = f(f(x <= xs, xs <= x+w), f(y <= ys, ys <= y+h))
  39. result = self.copy()
  40. result.parts[:, -1] = mask.astype(self.parts.dtype)
  41. return result
  42. def uniform_parts(self, ratio):
  43. result = self.copy()
  44. result.parts = utils.uniform_parts(self.im, ratio=ratio)
  45. return result
  46. @should_have_parts
  47. def select_parts(self, idxs):
  48. result = self.copy()
  49. result.parts[:, -1] = 0
  50. result.parts[idxs, -1] = 1
  51. return result
  52. @should_have_parts
  53. def select_random_parts(self, rnd, n_parts):
  54. idxs, xy = self.visible_part_locs()
  55. rnd_idxs = utils.random_idxs(idxs, rnd=rnd, n_parts=n_parts)
  56. return self.select_parts(rnd_idxs)
  57. @should_have_parts
  58. def visible_crops(self, ratio):
  59. return utils.visible_crops(self.im, self.parts, ratio=ratio)
  60. @should_have_parts
  61. def visible_part_locs(self):
  62. return utils.visible_part_locs(self.parts)
  63. @should_have_parts
  64. def reveal_visible(self, ratio):
  65. _, xy = self.visible_part_locs()
  66. result = self.copy()
  67. result.im = utils.reveal_parts(self.im, xy, ratio=ratio)
  68. return result
  69. @should_have_parts
  70. def part_crops(self, ratio):
  71. crops = self.visible_crops(ratio)
  72. idxs, _ = self.visible_part_locs()
  73. result = self.copy()
  74. result.im = crops[idxs]
  75. return result
  76. @property
  77. def has_parts(self):
  78. return self.parts is not None