Datasets:
File size: 8,148 Bytes
00ed6f3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | """Generate BONAI official_v1 manifests and COCO subsets from released annotations."""
import argparse
from collections import Counter, defaultdict
from copy import deepcopy
import hashlib
import json
from pathlib import Path
import random
import re
CITIES = ('beijing', 'chengdu', 'haerbin', 'jinan', 'shanghai')
SEED = 42
VERSION = 'official_v1'
TEST_FILE = 'coco/bonai_shanghai_xian_test.json'
SOURCE_SHA256 = {
'coco/bonai_beijing_trainval.json': 'f495f2d3a7aecbca0466b2f54ee03d0a885e8c6da16e19d56ce74d5bd7ccfaa7',
'coco/bonai_chengdu_trainval.json': '30d2f0848101d602a3e2225631a4e93cc2612e96057e2b70ba0f22416bb2a7bb',
'coco/bonai_haerbin_trainval.json': '2e95d0251060ab7750c2ad4f14d7c6e9d55ba91fbed7217d945b4baea589c445',
'coco/bonai_jinan_trainval.json': '7b0ce3cc30603b9efced9603188ae5b01e93304c78da82c9f6d826c994098c98',
'coco/bonai_shanghai_trainval.json': '78f609ced48f2886ba3683dfdc5c5643354d26b50df4e26c7611b1c7b04551cc',
'coco/bonai_shanghai_xian_test.json': '8b492c2c685758f1f697a9883e31a9e913d0a02926cdd1a57f9527f6b371fe01',
}
def tile(filename):
match = re.search(r'L(\d+)_(\d+)_(\d+)__(\d+)_(\d+)\.png$', filename)
if match is None:
raise ValueError(f'Unsupported image filename: {filename}')
return tuple(map(int, match.groups()[:3]))
def dump(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
def generate(data_root, output_root):
sources, hashes = {}, {}
for city in CITIES:
name = f'coco/bonai_{city}_trainval.json'
content = (data_root / name).read_bytes()
sources[city] = json.loads(content)
hashes[name] = hashlib.sha256(content).hexdigest()
test_bytes = (data_root / TEST_FILE).read_bytes()
test = json.loads(test_bytes)
hashes[TEST_FILE] = hashlib.sha256(test_bytes).hexdigest()
if hashes != SOURCE_SHA256:
raise ValueError('Source files differ from the official_v1 inputs; see SOURCE_SHA256.')
groups = defaultdict(list)
for image in sources['shanghai']['images']:
groups[tile(image['file_name'])].append(image)
assert len(groups) == 157
expected = {(source, crop) for source in ('arg', 'google', 'ms')
for crop in ('0_0.png', '0_1024.png', '1024_0.png', '1024_1024.png')}
for images in groups.values():
assert len(images) == 12
assert {(im['file_name'].split('__')[0].split('_')[-1],
im['file_name'].split('__')[-1]) for im in images} == expected
validation_tiles = set(random.Random(SEED).sample(sorted(groups), 19))
template = {k: deepcopy(v) for k, v in sources['shanghai'].items()
if k not in ('images', 'annotations')}
outputs = {}
for split in ('train', 'val'):
outputs[split] = deepcopy(template)
outputs[split]['info']['description'] = f'BONAI {VERSION} {split}'
outputs[split]['images'] = []
outputs[split]['annotations'] = []
mapping, annotation_ranges = [], {}
next_image_id, next_annotation_id = 1, 1
for city in CITIES:
source = sources[city]
assert source['categories'] == template['categories']
assert source['licenses'] == template['licenses']
source_name = f'coco/bonai_{city}_trainval.json'
remap, membership = {}, {}
for image in sorted(source['images'], key=lambda im: im['id']):
split = 'val' if city == 'jinan' or (
city == 'shanghai' and tile(image['file_name']) in validation_tiles) else 'train'
assert image['id'] not in remap
remap[image['id']] = next_image_id
membership[image['id']] = split
outputs[split]['images'].append({**image, 'id': next_image_id})
mapping.append(dict(file_name=image['file_name'], source_file=source_name,
source_image_id=image['id'], image_id=next_image_id, split=split))
next_image_id += 1
annotation_ranges[source_name] = dict(first_id=next_annotation_id,
count=len(source['annotations']))
seen_annotation_ids = set()
for annotation in sorted(source['annotations'], key=lambda ann: ann['id']):
assert annotation['id'] not in seen_annotation_ids
seen_annotation_ids.add(annotation['id'])
old_image_id = annotation['image_id']
split = membership[old_image_id]
outputs[split]['annotations'].append(
{**annotation, 'id': next_annotation_id, 'image_id': remap[old_image_id]})
next_annotation_id += 1
names = {split: {im['file_name'] for im in data['images']} for split, data in outputs.items()}
names['test'] = {im['file_name'] for im in test['images']}
all_source_names = {im['file_name'] for source in sources.values() for im in source['images']}
assert len(all_source_names) == 3000
assert len(names['train']) == 2700 and len(names['val']) == 300 and len(names['test']) == 300
assert names['train'] | names['val'] == all_source_names
split_groups = {split: {tile(name) for name in files} for split, files in names.items()}
for a, b in [('train', 'val'), ('train', 'test'), ('val', 'test')]:
assert not names[a] & names[b]
assert not split_groups[a] & split_groups[b]
# Parent tiles cover 2048 pixels = 8 tiles on the 256-pixel L18 grid.
assert not any(x[0] == y[0] and abs(x[1] - y[1]) < 8 and abs(x[2] - y[2]) < 8
for x in split_groups[a] for y in split_groups[b])
folder = output_root / 'splits' / VERSION
folder.mkdir(parents=True, exist_ok=True)
for split, files in names.items():
(folder / f'{split}.txt').write_text(''.join(name + '\n' for name in sorted(files)))
for split, data in outputs.items():
path = output_root / 'coco' / f'bonai_{split}_{VERSION}.json'
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, separators=(',', ':')) + '\n')
dump(folder / 'image_id_map.json', mapping)
protocol = dict(
version=VERSION, seed=SEED,
selection='random.Random(42).sample(sorted(Shanghai parent tile tuples), 19)',
grouping='(zoom, first tile coordinate, second tile coordinate); all sources and crops stay together',
shanghai_validation_tiles=['L%d_%d_%d' % group for group in sorted(validation_tiles)],
source_sha256=hashes,
counts={split: dict(images=len(data['images']), annotations=len(data['annotations']),
cities=dict(Counter(im['file_name'].split('_')[0]
if im['file_name'].startswith(tuple(CITIES))
else 'xian' for im in data['images'])))
for split, data in {**outputs, 'test': test}.items()},
annotation_id_ranges=annotation_ranges,
id_policy='Images and annotations are enumerated from 1 across alphabetically ordered source cities, then original numeric ID; train and val retain these global IDs. Test IDs are unchanged.',
geographic_check='No shared parent tile IDs or positive-area overlap between filename-derived 8-by-8 parent tile boxes across splits. Adjacent tile boundaries are allowed; no geographic buffer is imposed. This does not independently verify imagery georeferencing.',
provenance='This manifest defines the official_v1 protocol. Its identity with the historical image-level partition used for the paper results has not been established.',
)
dump(folder / 'protocol.json', protocol)
print(json.dumps(protocol['counts'], indent=2))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--data-root', type=Path, required=True,
help='Dataset root containing the original coco/ files')
parser.add_argument('--output-root', type=Path, required=True)
args = parser.parse_args()
generate(args.data_root, args.output_root)
|