__init__.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from imageio import imread
  2. import numpy as np
  3. class Dataset(object):
  4. def __init__(self, uuids, annotations, crop_to_bb=False, crop_uniform=False):
  5. super(Dataset, self).__init__()
  6. self.uuids = uuids
  7. self._annot = annotations
  8. self.crop_to_bb = crop_to_bb
  9. self.crop_uniform = crop_uniform
  10. def bounding_box(self, i):
  11. bbox = self._get("bounding_box", i)
  12. x,y,w,h = [bbox[attr] for attr in "xywh"]
  13. if self.crop_uniform:
  14. x0 = x + w//2
  15. y0 = y + h//2
  16. crop_size = max(w//2, h//2)
  17. x,y = max(x0 - crop_size, 0), max(y0 - crop_size, 0)
  18. w = h = crop_size * 2
  19. return x,y,w,h
  20. def __len__(self):
  21. return len(self.uuids)
  22. def _get(self, method, i):
  23. return getattr(self._annot, method)(self.uuids[i])
  24. def get_example(self, i, mode="RGB"):
  25. methods = ["image", "parts", "label"]
  26. im_path, parts, label = [self._get(m, i) for m in methods]
  27. im = imread(im_path, pilmode=mode)
  28. if self.crop_to_bb:
  29. x,y,w,h = self.bounding_box(i)
  30. im = im[y:y+h, x:x+w]
  31. parts[:, 1] -= x
  32. parts[:, 2] -= y
  33. h,w,c = im.shape
  34. # fit to the dimensions of the image
  35. parts[:, 1] = np.minimum(parts[:, 1], w - 1)
  36. parts[:, 2] = np.minimum(parts[:, 2], h - 1)
  37. return im, parts, label
  38. __getitem__ = get_example