common.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import argparse
  2. import random
  3. import copy
  4. import os
  5. import os.path as osp
  6. from glob import glob
  7. from itertools import count
  8. from functools import partial
  9. from concurrent.futures import ThreadPoolExecutor
  10. from skimage.io import imread, imsave
  11. from tqdm import tqdm
  12. def get_default_parser():
  13. """
  14. Get argument parser with commonly used options.
  15. Returns:
  16. argparse.ArgumentParser: Argument parser with the following arguments:
  17. --in_dataset_dir: Input dataset directory.
  18. --out_dataset_dir: Output dataset directory.
  19. """
  20. parser = argparse.ArgumentParser()
  21. parser.add_argument(
  22. '--in_dataset_dir',
  23. type=str,
  24. required=True,
  25. help="Input dataset directory.")
  26. parser.add_argument(
  27. '--out_dataset_dir', type=str, help="Output dataset directory.")
  28. return parser
  29. def add_crop_options(parser):
  30. """
  31. Add patch cropping related arguments to an argument parser. The parser will be
  32. modified in place.
  33. Args:
  34. parser (argparse.ArgumentParser): Argument parser.
  35. Returns:
  36. argparse.ArgumentParser: Argument parser with the following arguments:
  37. --crop_size: Size of cropped patches.
  38. --crop_stride: Stride of sliding windows when cropping patches.
  39. """
  40. parser.add_argument(
  41. '--crop_size', type=int, help="Size of cropped patches.")
  42. parser.add_argument(
  43. '--crop_stride',
  44. type=int,
  45. help="Stride of sliding windows when cropping patches. `crop_size` will be used only if `crop_size` is not None.",
  46. )
  47. return parser
  48. def crop_and_save(path, out_subdir, crop_size, stride):
  49. name, ext = osp.splitext(osp.basename(path))
  50. out_subsubdir = osp.join(out_subdir, name)
  51. if not osp.exists(out_subsubdir):
  52. os.makedirs(out_subsubdir)
  53. img = imread(path)
  54. w, h = img.shape[:2]
  55. counter = count()
  56. for i in range(0, h - crop_size + 1, stride):
  57. for j in range(0, w - crop_size + 1, stride):
  58. imsave(
  59. osp.join(out_subsubdir, '{}_{}{}'.format(name,
  60. next(counter), ext)),
  61. img[i:i + crop_size, j:j + crop_size],
  62. check_contrast=False)
  63. def crop_patches(crop_size,
  64. stride,
  65. data_dir,
  66. out_dir,
  67. subsets=('train', 'val', 'test'),
  68. subdirs=('A', 'B', 'label'),
  69. glob_pattern='*',
  70. max_workers=0):
  71. """
  72. Crop patches from images in specific directories.
  73. Args:
  74. crop_size (int): Height and width of the cropped patches will be `crop_size`.
  75. stride (int): Stride of sliding windows when cropping patches.
  76. data_dir (str): Root directory of the dataset that contains the input images.
  77. out_dir (str): Directory to save the cropped patches.
  78. subsets (tuple|list|None, optional): List or tuple of names of subdirectories
  79. or None. Images to be cropped should be stored in `data_dir/subset/subdir/`
  80. or `data_dir/subdir/` (when `subsets` is set to None), where `subset` is an
  81. element of `subsets`. Defaults to ('train', 'val', 'test').
  82. subdirs (tuple|list, optional): List or tuple of names of subdirectories. Images
  83. to be cropped should be stored in `data_dir/subset/subdir/` or
  84. `data_dir/subdir/` (when `subsets` is set to None), where `subdir` is an
  85. element of `subdirs`. Defaults to ('A', 'B', 'label').
  86. glob_pattern (str, optional): Glob pattern used to match image files.
  87. Defaults to '*', which matches arbitrary file.
  88. max_workers (int, optional): Number of worker threads to perform the cropping
  89. operation. Deafults to 0.
  90. """
  91. if max_workers < 0:
  92. raise ValueError("`max_workers` must be a non-negative integer!")
  93. if subsets is None:
  94. subsets = ('', )
  95. if max_workers == 0:
  96. for subset in subsets:
  97. for subdir in subdirs:
  98. paths = glob(
  99. osp.join(data_dir, subset, subdir, glob_pattern),
  100. recursive=True)
  101. out_subdir = osp.join(out_dir, subset, subdir)
  102. for p in tqdm(paths):
  103. crop_and_save(
  104. p,
  105. out_subdir=out_subdir,
  106. crop_size=crop_size,
  107. stride=stride)
  108. else:
  109. # Concurrently crop image patches
  110. with ThreadPoolExecutor(max_workers=max_workers) as executor:
  111. for subset in subsets:
  112. for subdir in subdirs:
  113. paths = glob(
  114. osp.join(data_dir, subset, subdir, glob_pattern),
  115. recursive=True)
  116. out_subdir = osp.join(out_dir, subset, subdir)
  117. for _ in tqdm(
  118. executor.map(partial(
  119. crop_and_save,
  120. out_subdir=out_subdir,
  121. crop_size=crop_size,
  122. stride=stride),
  123. paths),
  124. total=len(paths)):
  125. pass
  126. def get_path_tuples(*dirs, glob_pattern='*', data_dir=None):
  127. """
  128. Get tuples of image paths. Each tuple corresponds to a sample in the dataset.
  129. Args:
  130. *dirs (str): Directories that contains the images.
  131. glob_pattern (str, optional): Glob pattern used to match image files.
  132. Defaults to '*', which matches arbitrary file.
  133. data_dir (str|None, optional): Root directory of the dataset that
  134. contains the images. If not None, `data_dir` will be used to
  135. determine relative paths of images. Defaults to None.
  136. Returns:
  137. list[tuple]: For directories with the following structure:
  138. ├── img
  139. │ ├── im1.png
  140. │ ├── im2.png
  141. │ └── im3.png
  142. ├── mask
  143. │ ├── im1.png
  144. │ ├── im2.png
  145. │ └── im3.png
  146. └── ...
  147. `get_path_tuples('img', 'mask', '*.png')` will return list of tuples:
  148. [('img/im1.png', 'mask/im1.png'), ('img/im2.png', 'mask/im2.png'), ('img/im3.png', 'mask/im3.png')]
  149. """
  150. all_paths = []
  151. for dir_ in dirs:
  152. paths = glob(osp.join(dir_, glob_pattern), recursive=True)
  153. paths = sorted(paths)
  154. if data_dir is not None:
  155. paths = [osp.relpath(p, data_dir) for p in paths]
  156. all_paths.append(paths)
  157. all_paths = list(zip(*all_paths))
  158. return all_paths
  159. def create_file_list(file_list, path_tuples, sep=' '):
  160. """
  161. Create file list.
  162. Args:
  163. file_list (str): Path of file list to create.
  164. path_tuples (list[tuple]): See get_path_tuples().
  165. sep (str, optional): Delimiter to use when writing lines to file list.
  166. Defaults to ' '.
  167. """
  168. with open(file_list, 'w') as f:
  169. for tup in path_tuples:
  170. line = sep.join(tup)
  171. f.write(line + '\n')
  172. def create_label_list(label_list, labels):
  173. """
  174. Create label list.
  175. Args:
  176. label_list (str): Path of label list to create.
  177. labels (list[str]|tuple[str]]): Label names.
  178. """
  179. with open(label_list, 'w') as f:
  180. for label in labels:
  181. f.write(label + '\n')
  182. def link_dataset(src, dst):
  183. """
  184. Make a symbolic link to a dataset.
  185. Args:
  186. src (str): Path of the original dataset.
  187. dst (str): Path of the symbolic link.
  188. """
  189. if osp.exists(dst) and not osp.isdir(dst):
  190. raise ValueError(f"{dst} exists and is not a directory.")
  191. elif not osp.exists(dst):
  192. os.makedirs(dst)
  193. src = osp.realpath(src)
  194. name = osp.basename(osp.normpath(src))
  195. os.symlink(src, osp.join(dst, name), target_is_directory=True)
  196. def random_split(samples,
  197. ratios=(0.7, 0.2, 0.1),
  198. inplace=True,
  199. drop_remainder=False):
  200. """
  201. Randomly split the dataset into two or three subsets.
  202. Args:
  203. samples (list): All samples of the dataset.
  204. ratios (tuple[float], optional): If the length of `ratios` is 2,
  205. the two elements indicate the ratios of samples used for training
  206. and evaluation. If the length of `ratios` is 3, the three elements
  207. indicate the ratios of samples used for training, validation, and
  208. testing. Defaults to (0.7, 0.2, 0.1).
  209. inplace (bool, optional): Whether to shuffle `samples` in place.
  210. Defaults to True.
  211. drop_remainder (bool, optional): Whether to discard the remaining samples.
  212. If False, the remaining samples will be included in the last subset.
  213. For example, if `ratios` is (0.7, 0.1) and `drop_remainder` is False,
  214. the two subsets after splitting will contain 70% and 30% of the samples,
  215. respectively. Defaults to False.
  216. """
  217. if not inplace:
  218. samples = copy.deepcopy(samples)
  219. if len(samples) == 0:
  220. raise ValueError("There are no samples!")
  221. if len(ratios) not in (2, 3):
  222. raise ValueError("`len(ratios)` must be 2 or 3!")
  223. random.shuffle(samples)
  224. n_samples = len(samples)
  225. acc_r = 0
  226. st_idx, ed_idx = 0, 0
  227. splits = []
  228. for r in ratios:
  229. acc_r += r
  230. ed_idx = round(acc_r * n_samples)
  231. splits.append(samples[st_idx:ed_idx])
  232. st_idx = ed_idx
  233. if ed_idx < len(ratios) and not drop_remainder:
  234. # Append remainder to the last split
  235. splits[-1].append(splits[ed_idx:])
  236. return splits