Datasets:
Tasks:
Image Segmentation
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
< 1K
License:
Download code/tools/prepare_data.py from COT5415/COT5415_Computer_Vision: direct link, hf CLI and curl.
- Browser
- Download file 4.09 kB
-
https://huggingface.co/datasets/COT5415/COT5415_Computer_Vision/resolve/main/code/tools/prepare_data.py
- Command line
-
hf download hf://datasets/COT5415/COT5415_Computer_Vision/code/tools/prepare_data.py
-
curl -L -o prepare_data.py https://huggingface.co/datasets/COT5415/COT5415_Computer_Vision/resolve/main/code/tools/prepare_data.py
4.09 kB
| """Extract the supplied archives without changing their original split layout.""" | |
| import argparse | |
| import json | |
| import os | |
| from pathlib import Path, PurePosixPath | |
| import shutil | |
| import tempfile | |
| import zipfile | |
| from tqdm import tqdm | |
| ROOT = Path(__file__).resolve().parents[2] | |
| def extract(archive, target, strip=None): | |
| count = 0 | |
| for item in tqdm(archive.infolist(), desc=target.name, mininterval=3, ascii=True): | |
| path = PurePosixPath(item.filename) | |
| if '__MACOSX' in path.parts or path.name in {'.DS_Store', 'Thumbs.db'} or path.name.startswith('._') or item.is_dir(): | |
| continue | |
| if path.is_absolute() or '..' in path.parts or '\\' in item.filename: | |
| raise ValueError(f'Unsafe archive member: {item.filename}') | |
| parts = path.parts | |
| if strip and parts[0] == strip: | |
| parts = parts[1:] | |
| out = target.joinpath(*parts).resolve() | |
| if not out.is_relative_to(target.resolve()): | |
| raise ValueError(f'Archive member escapes destination: {item.filename}') | |
| if out.exists(): | |
| if out.stat().st_size != item.file_size: | |
| raise FileExistsError(out) | |
| else: | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| with archive.open(item) as src, out.open('xb') as dst: | |
| shutil.copyfileobj(src, dst) | |
| count += 1 | |
| return count | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--root', type=Path, default=ROOT) | |
| args = parser.parse_args() | |
| root = args.root.resolve() | |
| data = root / 'datasets/PartImageNet' | |
| report = {} | |
| with zipfile.ZipFile(root / 'datasets/archives/PartImageNet_OOD.zip') as outer: | |
| (data / 'annotations').mkdir(parents=True, exist_ok=True) | |
| for split in ('train', 'val', 'test'): | |
| payload = outer.read(split + '.json') | |
| (data / 'annotations' / (split + '.json')).write_bytes(payload) | |
| with tempfile.TemporaryDirectory(prefix='partimagenet-') as tmp: | |
| nested = Path(tmp) / (split + '.zip') | |
| with outer.open(split + '.zip') as src, nested.open('wb') as dst: | |
| shutil.copyfileobj(src, dst) | |
| with zipfile.ZipFile(nested) as archive: | |
| count = extract(archive, data / 'images' / split, strip=split) | |
| annotation = json.loads(payload) | |
| image_root = data / 'images' / split | |
| missing = [im['file_name'] for im in annotation['images'] | |
| if not (image_root / im['file_name'][:9] / im['file_name']).is_file()] | |
| if missing: | |
| print(f'INCOMPLETE SOURCE ARCHIVE: {split}: {missing}') | |
| report['PartImageNet/' + split] = {'images': len(annotation['images']), | |
| 'annotations': len(annotation['annotations']), 'extracted_files': count, | |
| 'missing_images': len(missing), 'missing_filenames': missing} | |
| with zipfile.ZipFile(root / 'datasets/archives/Pascal_Part.zip') as archive: | |
| extract(archive, root / 'datasets/Pascal-Part', strip='Pascal_Part') | |
| for split in ('train', 'val'): | |
| base = root / 'datasets/Pascal-Part' | |
| parts = sorted((base / 'annotations' / split).glob('*.png')) | |
| images = {p.stem: p for p in (base / 'JPEGImages' / split).iterdir() if p.is_file()} | |
| for part in parts: | |
| if part.stem not in images or not (base / 'annotations' / (split + '_whole') / part.name).is_file(): | |
| raise FileNotFoundError(part) | |
| report['Pascal-Part/' + split] = {'images': len(images), 'part_masks': len(parts), | |
| 'whole_masks': len(list((base / 'annotations' / (split + '_whole')).glob('*.png')))} | |
| output = root / 'results/preparation' | |
| output.mkdir(parents=True, exist_ok=True) | |
| (output / 'data_inventory.json').write_text(json.dumps(report, indent=2) + '\n', encoding='utf-8') | |
| print(json.dumps(report, indent=2)) | |
| if __name__ == '__main__': | |
| main() | |