common.py 12 KB

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