prepare_dataset.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import functools
  2. import io
  3. import json
  4. import os
  5. import pickle
  6. import sys
  7. import tarfile
  8. import gzip
  9. import zipfile
  10. from pathlib import Path
  11. from typing import Callable, Optional, Tuple, Union
  12. import argparse
  13. import numpy as np
  14. import PIL.Image
  15. from tqdm import tqdm
  16. def error(msg):
  17. print('Error: ' + msg)
  18. sys.exit(1)
  19. def maybe_min(a: int, b: Optional[int]) -> int:
  20. if b is not None:
  21. return min(a, b)
  22. return a
  23. def file_ext(name: Union[str, Path]) -> str:
  24. return str(name).split('.')[-1]
  25. def is_image_ext(fname: Union[str, Path]) -> bool:
  26. ext = file_ext(fname).lower()
  27. return f'.{ext}' in PIL.Image.EXTENSION # type: ignore
  28. def open_image_folder(source_dir, *, max_images: Optional[int]):
  29. input_images = [str(f) for f in sorted(Path(source_dir).rglob('*')) if is_image_ext(f) and os.path.isfile(f)]
  30. # Load labels.
  31. labels = {}
  32. meta_fname = os.path.join(source_dir, 'dataset.json')
  33. if os.path.isfile(meta_fname):
  34. with open(meta_fname, 'r') as file:
  35. labels = json.load(file)['labels']
  36. if labels is not None:
  37. labels = { x[0]: x[1] for x in labels }
  38. else:
  39. labels = {}
  40. max_idx = maybe_min(len(input_images), max_images)
  41. def iterate_images():
  42. for idx, fname in enumerate(input_images):
  43. arch_fname = os.path.relpath(fname, source_dir)
  44. arch_fname = arch_fname.replace('\\', '/')
  45. img = np.array(PIL.Image.open(fname))
  46. yield dict(img=img, label=labels.get(arch_fname))
  47. if idx >= max_idx-1:
  48. break
  49. return max_idx, iterate_images()
  50. def open_image_zip(source, *, max_images: Optional[int]):
  51. with zipfile.ZipFile(source, mode='r') as z:
  52. input_images = [str(f) for f in sorted(z.namelist()) if is_image_ext(f)]
  53. # Load labels.
  54. labels = {}
  55. if 'dataset.json' in z.namelist():
  56. with z.open('dataset.json', 'r') as file:
  57. labels = json.load(file)['labels']
  58. if labels is not None:
  59. labels = { x[0]: x[1] for x in labels }
  60. else:
  61. labels = {}
  62. max_idx = maybe_min(len(input_images), max_images)
  63. def iterate_images():
  64. with zipfile.ZipFile(source, mode='r') as z:
  65. for idx, fname in enumerate(input_images):
  66. with z.open(fname, 'r') as file:
  67. img = PIL.Image.open(file) # type: ignore
  68. img = np.array(img)
  69. yield dict(img=img, label=labels.get(fname))
  70. if idx >= max_idx-1:
  71. break
  72. return max_idx, iterate_images()
  73. def open_lmdb(lmdb_dir: str, *, max_images: Optional[int]):
  74. import cv2 # pip install opencv-python
  75. import lmdb # pip install lmdb # pylint: disable=import-error
  76. with lmdb.open(lmdb_dir, readonly=True, lock=False).begin(write=False) as txn:
  77. max_idx = maybe_min(txn.stat()['entries'], max_images)
  78. def iterate_images():
  79. with lmdb.open(lmdb_dir, readonly=True, lock=False).begin(write=False) as txn:
  80. for idx, (_key, value) in enumerate(txn.cursor()):
  81. try:
  82. try:
  83. img = cv2.imdecode(np.frombuffer(value, dtype=np.uint8), 1)
  84. if img is None:
  85. raise IOError('cv2.imdecode failed')
  86. img = img[:, :, ::-1] # BGR => RGB
  87. except IOError:
  88. img = np.array(PIL.Image.open(io.BytesIO(value)))
  89. yield dict(img=img, label=None)
  90. if idx >= max_idx-1:
  91. break
  92. except:
  93. print(sys.exc_info()[1])
  94. return max_idx, iterate_images()
  95. def open_cifar10(tarball: str, *, max_images: Optional[int]):
  96. images = []
  97. labels = []
  98. with tarfile.open(tarball, 'r:gz') as tar:
  99. for batch in range(1, 6):
  100. member = tar.getmember(f'cifar-10-batches-py/data_batch_{batch}')
  101. with tar.extractfile(member) as file:
  102. data = pickle.load(file, encoding='latin1')
  103. images.append(data['data'].reshape(-1, 3, 32, 32))
  104. labels.append(data['labels'])
  105. images = np.concatenate(images)
  106. labels = np.concatenate(labels)
  107. images = images.transpose([0, 2, 3, 1]) # NCHW -> NHWC
  108. assert images.shape == (50000, 32, 32, 3) and images.dtype == np.uint8
  109. assert labels.shape == (50000,) and labels.dtype in [np.int32, np.int64]
  110. assert np.min(images) == 0 and np.max(images) == 255
  111. assert np.min(labels) == 0 and np.max(labels) == 9
  112. max_idx = maybe_min(len(images), max_images)
  113. def iterate_images():
  114. for idx, img in enumerate(images):
  115. yield dict(img=img, label=int(labels[idx]))
  116. if idx >= max_idx-1:
  117. break
  118. return max_idx, iterate_images()
  119. def open_mnist(images_gz: str, *, max_images: Optional[int]):
  120. labels_gz = images_gz.replace('-images-idx3-ubyte.gz', '-labels-idx1-ubyte.gz')
  121. assert labels_gz != images_gz
  122. images = []
  123. labels = []
  124. with gzip.open(images_gz, 'rb') as f:
  125. images = np.frombuffer(f.read(), np.uint8, offset=16)
  126. with gzip.open(labels_gz, 'rb') as f:
  127. labels = np.frombuffer(f.read(), np.uint8, offset=8)
  128. images = images.reshape(-1, 28, 28)
  129. images = np.pad(images, [(0,0), (2,2), (2,2)], 'constant', constant_values=0)
  130. assert images.shape == (60000, 32, 32) and images.dtype == np.uint8
  131. assert labels.shape == (60000,) and labels.dtype == np.uint8
  132. assert np.min(images) == 0 and np.max(images) == 255
  133. assert np.min(labels) == 0 and np.max(labels) == 9
  134. max_idx = maybe_min(len(images), max_images)
  135. def iterate_images():
  136. for idx, img in enumerate(images):
  137. yield dict(img=img, label=int(labels[idx]))
  138. if idx >= max_idx-1:
  139. break
  140. return max_idx, iterate_images()
  141. def make_transform(
  142. transform: Optional[str],
  143. output_width: Optional[int],
  144. output_height: Optional[int],
  145. resize_filter: str
  146. ) -> Callable[[np.ndarray], Optional[np.ndarray]]:
  147. resample = { 'box': PIL.Image.BOX, 'lanczos': PIL.Image.LANCZOS }[resize_filter]
  148. def scale(width, height, img):
  149. w = img.shape[1]
  150. h = img.shape[0]
  151. if width == w and height == h:
  152. return img
  153. img = PIL.Image.fromarray(img)
  154. ww = width if width is not None else w
  155. hh = height if height is not None else h
  156. img = img.resize((ww, hh), resample)
  157. return np.array(img)
  158. def center_crop(width, height, img):
  159. crop = np.min(img.shape[:2])
  160. img = img[(img.shape[0] - crop) // 2 : (img.shape[0] + crop) // 2, (img.shape[1] - crop) // 2 : (img.shape[1] + crop) // 2]
  161. img = PIL.Image.fromarray(img, 'RGB')
  162. img = img.resize((width, height), resample)
  163. return np.array(img)
  164. def center_crop_wide(width, height, img):
  165. ch = int(np.round(width * img.shape[0] / img.shape[1]))
  166. if img.shape[1] < width or ch < height:
  167. return None
  168. img = img[(img.shape[0] - ch) // 2 : (img.shape[0] + ch) // 2]
  169. img = PIL.Image.fromarray(img, 'RGB')
  170. img = img.resize((width, height), resample)
  171. img = np.array(img)
  172. canvas = np.zeros([width, width, 3], dtype=np.uint8)
  173. canvas[(width - height) // 2 : (width + height) // 2, :] = img
  174. return canvas
  175. if transform is None:
  176. return functools.partial(scale, output_width, output_height)
  177. if transform == 'center-crop':
  178. if (output_width is None) or (output_height is None):
  179. error ('must specify --width and --height when using ' + transform + 'transform')
  180. return functools.partial(center_crop, output_width, output_height)
  181. if transform == 'center-crop-wide':
  182. if (output_width is None) or (output_height is None):
  183. error ('must specify --width and --height when using ' + transform + ' transform')
  184. return functools.partial(center_crop_wide, output_width, output_height)
  185. assert False, 'unknown transform'
  186. def open_dataset(source, *, max_images: Optional[int]):
  187. if os.path.isdir(source):
  188. if source.rstrip('/').endswith('_lmdb'):
  189. return open_lmdb(source, max_images=max_images)
  190. else:
  191. return open_image_folder(source, max_images=max_images)
  192. elif os.path.isfile(source):
  193. if os.path.basename(source) == 'cifar-10-python.tar.gz':
  194. return open_cifar10(source, max_images=max_images)
  195. elif os.path.basename(source) == 'train-images-idx3-ubyte.gz':
  196. return open_mnist(source, max_images=max_images)
  197. elif file_ext(source) == 'zip':
  198. return open_image_zip(source, max_images=max_images)
  199. else:
  200. assert False, 'unknown archive type'
  201. else:
  202. error(f'Missing input file or directory: {source}')
  203. def open_dest(dest: str) -> Tuple[str, Callable[[str, Union[bytes, str]], None], Callable[[], None]]:
  204. dest_ext = file_ext(dest)
  205. if dest_ext == 'zip':
  206. if os.path.dirname(dest) != '':
  207. os.makedirs(os.path.dirname(dest), exist_ok=True)
  208. zf = zipfile.ZipFile(file=dest, mode='w', compression=zipfile.ZIP_STORED)
  209. def zip_write_bytes(fname: str, data: Union[bytes, str]):
  210. zf.writestr(fname, data)
  211. return '', zip_write_bytes, zf.close
  212. else:
  213. # If the output folder already exists, check that is is
  214. # empty.
  215. #
  216. # Note: creating the output directory is not strictly
  217. # necessary as folder_write_bytes() also mkdirs, but it's better
  218. # to give an error message earlier in case the dest folder
  219. # somehow cannot be created.
  220. if os.path.isdir(dest) and len(os.listdir(dest)) != 0:
  221. error('--dest folder must be empty')
  222. os.makedirs(dest, exist_ok=True)
  223. def folder_write_bytes(fname: str, data: Union[bytes, str]):
  224. os.makedirs(os.path.dirname(fname), exist_ok=True)
  225. with open(fname, 'wb') as fout:
  226. if isinstance(data, str):
  227. data = data.encode('utf8')
  228. fout.write(data)
  229. return dest, folder_write_bytes, lambda: None
  230. def convert_dataset(cfg):
  231. """Convert an image dataset into a dataset archive usable with StyleGAN2 ADA PyTorch.
  232. The input dataset format is guessed from the --source argument:
  233. \b
  234. --source *_lmdb/ Load LSUN dataset
  235. --source cifar-10-python.tar.gz Load CIFAR-10 dataset
  236. --source train-images-idx3-ubyte.gz Load MNIST dataset
  237. --source path/ Recursively load all images from path/
  238. --source dataset.zip Recursively load all images from dataset.zip
  239. Specifying the output format and path:
  240. \b
  241. --dest /path/to/dir Save output files under /path/to/dir
  242. --dest /path/to/dataset.zip Save output files into /path/to/dataset.zip
  243. The output dataset format can be either an image folder or an uncompressed zip archive.
  244. Zip archives makes it easier to move datasets around file servers and clusters, and may
  245. offer better training performance on network file systems.
  246. Images within the dataset archive will be stored as uncompressed PNG.
  247. Uncompresed PNGs can be efficiently decoded in the training loop.
  248. Class labels are stored in a file called 'dataset.json' that is stored at the
  249. dataset root folder. This file has the following structure:
  250. \b
  251. {
  252. "labels": [
  253. ["00000/img00000000.png",6],
  254. ["00000/img00000001.png",9],
  255. ... repeated for every image in the datase
  256. ["00049/img00049999.png",1]
  257. ]
  258. }
  259. If the 'dataset.json' file cannot be found, the dataset is interpreted as
  260. not containing class labels.
  261. Image scale/crop and resolution requirements:
  262. Output images must be square-shaped and they must all have the same power-of-two
  263. dimensions.
  264. To scale arbitrary input image size to a specific width and height, use the
  265. --width and --height options. Output resolution will be either the original
  266. input resolution (if --width/--height was not specified) or the one specified with
  267. --width/height.
  268. Use the --transform=center-crop or --transform=center-crop-wide options to apply a
  269. center crop transform on the input image. These options should be used with the
  270. --width and --height options. For example:
  271. \b
  272. python dataset_tool.py --source LSUN/raw/cat_lmdb --dest /tmp/lsun_cat \\
  273. --transform=center-crop-wide --width 512 --height=384
  274. """
  275. PIL.Image.init() # type: ignore
  276. if cfg.dest == '':
  277. error('--dest output filename or directory must not be an empty string')
  278. num_files, input_iter = open_dataset(cfg.source, max_images=cfg.max_images)
  279. archive_root_dir, save_bytes, close_dest = open_dest(cfg.dest)
  280. transform_image = make_transform(cfg.transform, cfg.width, cfg.height, cfg.resize_filter)
  281. dataset_attrs = None
  282. labels = []
  283. for idx, image in tqdm(enumerate(input_iter), total=num_files):
  284. img_name = f'{idx:08d}.png'
  285. archive_name = f'images/{img_name}'
  286. # Apply crop and resize.
  287. img = transform_image(image['img'])
  288. # Transform may drop images.
  289. if img is None:
  290. continue
  291. # Error check to require uniform image attributes across the whole dataset.
  292. channels = img.shape[2] if img.ndim == 3 else 1
  293. cur_image_attrs = {
  294. 'width': img.shape[1],
  295. 'height': img.shape[0],
  296. 'channels': channels
  297. }
  298. if dataset_attrs is None:
  299. dataset_attrs = cur_image_attrs
  300. width = dataset_attrs['width']
  301. height = dataset_attrs['height']
  302. if width != height:
  303. error(f'Image dimensions after scale and crop are required to be square. Got {width}x{height}')
  304. if dataset_attrs['channels'] not in [1, 3]:
  305. error('Input images must be stored as RGB or grayscale')
  306. if width != 2 ** int(np.floor(np.log2(width))):
  307. error('Image width/height after scale and crop are required to be power-of-two')
  308. elif dataset_attrs != cur_image_attrs:
  309. err = [f' dataset {k}/cur image {k}: {dataset_attrs[k]}/{cur_image_attrs[k]}' for k in dataset_attrs.keys()]
  310. error(f'Image {archive_name} attributes must be equal across all images of the dataset. Got:\n' + '\n'.join(err))
  311. # Save the image as an uncompressed PNG.
  312. img = PIL.Image.fromarray(img, { 1: 'L', 3: 'RGB' }[channels])
  313. image_bits = io.BytesIO()
  314. img.save(image_bits, format='png', compress_level=0, optimize=False)
  315. save_bytes(os.path.join(archive_root_dir, archive_name), image_bits.getbuffer())
  316. labels.append([img_name, image['label']] if image['label'] is not None else None)
  317. metadata = {'labels': labels if all(x is not None for x in labels) else None}
  318. save_bytes(os.path.join(archive_root_dir, 'dataset.json'), json.dumps(metadata))
  319. close_dest()
  320. if __name__ == "__main__":
  321. parser = argparse.ArgumentParser()
  322. parser.add_argument('-s', '--source', type=str, default='', help='Directory or archive name for input dataset')
  323. parser.add_argument('-d', '--dest', type=str, default='', help='Output directory or archive name for output dataset')
  324. parser.add_argument('--max_images', type=int, default=None, help='Output only up to `max-images` images')
  325. parser.add_argument('--resize_filter', type=str, default='lanczos', choices=['box', 'lanczos'], help='Filter to use when resizing images for output resolution')
  326. parser.add_argument('--transform', type=str, default=None, choices=[None, 'center-crop', 'center-crop-wide'], help='Input crop/resize mode')
  327. parser.add_argument('--width', type=int, help='Output width')
  328. parser.add_argument('--height', type=int, help='Output height')
  329. cfg = parser.parse_args()
  330. convert_dataset(cfg)