reader_image_tar.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """ A dataset reader that reads single tarfile based datasets
  2. This reader can read datasets consisting if a single tarfile containing images.
  3. I am planning to deprecated it in favour of ParerImageInTar.
  4. Hacked together by / Copyright 2020 Ross Wightman
  5. """
  6. import os
  7. import tarfile
  8. from timm.utils.misc import natural_key
  9. from .class_map import load_class_map
  10. from .img_extensions import get_img_extensions
  11. from .reader import Reader
  12. def extract_tarinfo(tarfile, class_to_idx=None, sort=True):
  13. extensions = get_img_extensions(as_set=True)
  14. files = []
  15. labels = []
  16. for ti in tarfile.getmembers():
  17. if not ti.isfile():
  18. continue
  19. dirname, basename = os.path.split(ti.path)
  20. label = os.path.basename(dirname)
  21. ext = os.path.splitext(basename)[1]
  22. if ext.lower() in extensions:
  23. files.append(ti)
  24. labels.append(label)
  25. if class_to_idx is None:
  26. unique_labels = set(labels)
  27. sorted_labels = list(sorted(unique_labels, key=natural_key))
  28. class_to_idx = {c: idx for idx, c in enumerate(sorted_labels)}
  29. tarinfo_and_targets = [(f, class_to_idx[l]) for f, l in zip(files, labels) if l in class_to_idx]
  30. if sort:
  31. tarinfo_and_targets = sorted(tarinfo_and_targets, key=lambda k: natural_key(k[0].path))
  32. return tarinfo_and_targets, class_to_idx
  33. class ReaderImageTar(Reader):
  34. """ Single tarfile dataset where classes are mapped to folders within tar
  35. NOTE: This class is being deprecated in favour of the more capable ReaderImageInTar that can
  36. operate on folders of tars or tars in tars.
  37. """
  38. def __init__(self, root, class_map=''):
  39. super().__init__()
  40. class_to_idx = None
  41. if class_map:
  42. class_to_idx = load_class_map(class_map, root)
  43. assert os.path.isfile(root)
  44. self.root = root
  45. with tarfile.open(root) as tf: # cannot keep this open across processes, reopen later
  46. self.samples, self.class_to_idx = extract_tarinfo(tf, class_to_idx)
  47. self.imgs = self.samples
  48. self.tarfile = None # lazy init in __getitem__
  49. def __getitem__(self, index):
  50. if self.tarfile is None:
  51. self.tarfile = tarfile.open(self.root)
  52. tarinfo, target = self.samples[index]
  53. fileobj = self.tarfile.extractfile(tarinfo)
  54. return fileobj, target
  55. def __len__(self):
  56. return len(self.samples)
  57. def _filename(self, index, basename=False, absolute=False):
  58. filename = self.samples[index][0].name
  59. if basename:
  60. filename = os.path.basename(filename)
  61. return filename