vaihingen.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import glob
  4. import math
  5. import os
  6. import os.path as osp
  7. import tempfile
  8. import zipfile
  9. import mmcv
  10. import numpy as np
  11. from mmengine.utils import ProgressBar, mkdir_or_exist
  12. def parse_args():
  13. parser = argparse.ArgumentParser(
  14. description='Convert vaihingen dataset to mmsegmentation format')
  15. parser.add_argument('dataset_path', help='vaihingen folder path')
  16. parser.add_argument('--tmp_dir', help='path of the temporary directory')
  17. parser.add_argument('-o', '--out_dir', help='output path')
  18. parser.add_argument(
  19. '--clip_size',
  20. type=int,
  21. help='clipped size of image after preparation',
  22. default=512)
  23. parser.add_argument(
  24. '--stride_size',
  25. type=int,
  26. help='stride of clipping original images',
  27. default=256)
  28. args = parser.parse_args()
  29. return args
  30. def clip_big_image(image_path, clip_save_dir, to_label=False):
  31. # Original image of Vaihingen dataset is very large, thus pre-processing
  32. # of them is adopted. Given fixed clip size and stride size to generate
  33. # clipped image, the intersection of width and height is determined.
  34. # For example, given one 5120 x 5120 original image, the clip size is
  35. # 512 and stride size is 256, thus it would generate 20x20 = 400 images
  36. # whose size are all 512x512.
  37. image = mmcv.imread(image_path)
  38. h, w, c = image.shape
  39. cs = args.clip_size
  40. ss = args.stride_size
  41. num_rows = math.ceil((h - cs) / ss) if math.ceil(
  42. (h - cs) / ss) * ss + cs >= h else math.ceil((h - cs) / ss) + 1
  43. num_cols = math.ceil((w - cs) / ss) if math.ceil(
  44. (w - cs) / ss) * ss + cs >= w else math.ceil((w - cs) / ss) + 1
  45. x, y = np.meshgrid(np.arange(num_cols + 1), np.arange(num_rows + 1))
  46. xmin = x * cs
  47. ymin = y * cs
  48. xmin = xmin.ravel()
  49. ymin = ymin.ravel()
  50. xmin_offset = np.where(xmin + cs > w, w - xmin - cs, np.zeros_like(xmin))
  51. ymin_offset = np.where(ymin + cs > h, h - ymin - cs, np.zeros_like(ymin))
  52. boxes = np.stack([
  53. xmin + xmin_offset, ymin + ymin_offset,
  54. np.minimum(xmin + cs, w),
  55. np.minimum(ymin + cs, h)
  56. ],
  57. axis=1)
  58. if to_label:
  59. color_map = np.array([[0, 0, 0], [255, 255, 255], [255, 0, 0],
  60. [255, 255, 0], [0, 255, 0], [0, 255, 255],
  61. [0, 0, 255]])
  62. flatten_v = np.matmul(
  63. image.reshape(-1, c),
  64. np.array([2, 3, 4]).reshape(3, 1))
  65. out = np.zeros_like(flatten_v)
  66. for idx, class_color in enumerate(color_map):
  67. value_idx = np.matmul(class_color,
  68. np.array([2, 3, 4]).reshape(3, 1))
  69. out[flatten_v == value_idx] = idx
  70. image = out.reshape(h, w)
  71. for box in boxes:
  72. start_x, start_y, end_x, end_y = box
  73. clipped_image = image[start_y:end_y,
  74. start_x:end_x] if to_label else image[
  75. start_y:end_y, start_x:end_x, :]
  76. area_idx = osp.basename(image_path).split('_')[3].strip('.tif')
  77. mmcv.imwrite(
  78. clipped_image.astype(np.uint8),
  79. osp.join(clip_save_dir,
  80. f'{area_idx}_{start_x}_{start_y}_{end_x}_{end_y}.png'))
  81. def main():
  82. splits = {
  83. 'train': [
  84. 'area1', 'area11', 'area13', 'area15', 'area17', 'area21',
  85. 'area23', 'area26', 'area28', 'area3', 'area30', 'area32',
  86. 'area34', 'area37', 'area5', 'area7'
  87. ],
  88. 'val': [
  89. 'area6', 'area24', 'area35', 'area16', 'area14', 'area22',
  90. 'area10', 'area4', 'area2', 'area20', 'area8', 'area31', 'area33',
  91. 'area27', 'area38', 'area12', 'area29'
  92. ],
  93. }
  94. dataset_path = args.dataset_path
  95. if args.out_dir is None:
  96. out_dir = osp.join('data', 'vaihingen')
  97. else:
  98. out_dir = args.out_dir
  99. print('Making directories...')
  100. mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train'))
  101. mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val'))
  102. mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train'))
  103. mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val'))
  104. zipp_list = glob.glob(os.path.join(dataset_path, '*.zip'))
  105. print('Find the data', zipp_list)
  106. with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir:
  107. for zipp in zipp_list:
  108. zip_file = zipfile.ZipFile(zipp)
  109. zip_file.extractall(tmp_dir)
  110. src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif'))
  111. if 'ISPRS_semantic_labeling_Vaihingen' in zipp:
  112. src_path_list = glob.glob(
  113. os.path.join(os.path.join(tmp_dir, 'top'), '*.tif'))
  114. if 'ISPRS_semantic_labeling_Vaihingen_ground_truth_eroded_COMPLETE' in zipp: # noqa
  115. src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif'))
  116. # delete unused area9 ground truth
  117. for area_ann in src_path_list:
  118. if 'area9' in area_ann:
  119. src_path_list.remove(area_ann)
  120. prog_bar = ProgressBar(len(src_path_list))
  121. for i, src_path in enumerate(src_path_list):
  122. area_idx = osp.basename(src_path).split('_')[3].strip('.tif')
  123. data_type = 'train' if area_idx in splits['train'] else 'val'
  124. if 'noBoundary' in src_path:
  125. dst_dir = osp.join(out_dir, 'ann_dir', data_type)
  126. clip_big_image(src_path, dst_dir, to_label=True)
  127. else:
  128. dst_dir = osp.join(out_dir, 'img_dir', data_type)
  129. clip_big_image(src_path, dst_dir, to_label=False)
  130. prog_bar.update()
  131. print('Removing the temporary files...')
  132. print('Done!')
  133. if __name__ == '__main__':
  134. args = parse_args()
  135. main()