HotSight / scripts /resize_dataset.py
hotsight's picture
Super-squash branch 'main' using huggingface_hub
4e6a175
Raw History Blame Contribute Delete
6.3 kB
#!/usr/bin/env python3
"""Downsample a dataset by 2 while preserving its directory structure."""
import argparse
import json
import os
import shutil
import tempfile
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from PIL import Image
FACTOR = 2
IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png"}
DEFAULT_WORKERS = min(8, os.cpu_count() or 1)
def half_size(size):
width, height = size
return max(1, width // FACTOR), max(1, height // FACTOR)
def resize_image(source, destination):
with Image.open(source) as image:
resized = image.resize(half_size(image.size), Image.Resampling.LANCZOS)
save_options = (
{"quality": 90}
if source.suffix.lower() in {".jpg", ".jpeg"}
else {}
)
resized.save(destination, **save_options)
def resize_mask(source, destination):
rgb_path = source.parent.parent / "rgb" / f"{source.stem}.png"
if not rgb_path.is_file():
raise RuntimeError(f"cannot determine dimensions for mask without {rgb_path}")
with Image.open(rgb_path) as rgb:
size = rgb.size
values = source.read_bytes()
expected = size[0] * size[1]
if len(values) != expected:
raise RuntimeError(
f"{source} contains {len(values)} values; expected {expected} "
f"for {size[0]}x{size[1]}"
)
mask = Image.frombytes("L", size, values)
resized = mask.resize(half_size(size), Image.Resampling.NEAREST)
destination.write_bytes(resized.tobytes())
def scale_homography_metadata(source, destination):
data = json.loads(source.read_text())
for key in ("ir_size", "rgb_size"):
if key in data:
data[key] = list(half_size(data[key]))
for subset in data.get("subsets", []):
for correspondence in subset.get("correspondences", []):
for key in ("ir", "rgb"):
if key in correspondence:
correspondence[key] = [
value / FACTOR for value in correspondence[key]
]
for key in ("ransac_threshold_px", "rmse_px"):
if key in subset:
subset[key] /= FACTOR
if "translation_px" in subset:
subset["translation_px"] = [
value / FACTOR for value in subset["translation_px"]
]
if "matrix" in subset:
matrix = subset["matrix"]
if len(matrix) != 3 or any(len(row) != 3 for row in matrix):
raise RuntimeError(f"invalid homography matrix in {source}")
# Both coordinate systems are scaled equally: H' = S H S^-1.
matrix[0][2] /= FACTOR
matrix[1][2] /= FACTOR
matrix[2][0] *= FACTOR
matrix[2][1] *= FACTOR
destination.write_text(json.dumps(data, indent=2) + "\n")
def copy_entry(source, destination):
suffix = source.suffix.lower()
if suffix in IMAGE_SUFFIXES:
resize_image(source, destination)
elif suffix == ".txt" and source.parent.name == "mask":
resize_mask(source, destination)
elif suffix == ".json" and source.parent.name == "homography":
scale_homography_metadata(source, destination)
else:
shutil.copy2(source, destination)
def resize_dataset(source_root, output_root, workers=DEFAULT_WORKERS):
source_root = source_root.resolve()
output_root = output_root.resolve()
if workers < 1:
raise RuntimeError("workers must be at least 1")
if not source_root.is_dir():
raise RuntimeError(f"dataset directory does not exist: {source_root}")
if source_root == output_root or source_root in output_root.parents:
raise RuntimeError("output directory must not be inside the source dataset")
if output_root.exists() and (
not output_root.is_dir() or any(output_root.iterdir())
):
raise RuntimeError(f"output directory is not empty: {output_root}")
output_root.parent.mkdir(parents=True, exist_ok=True)
count = 0
with tempfile.TemporaryDirectory(
prefix=f".{output_root.name}.", dir=output_root.parent
) as temp:
staged_root = Path(temp) / output_root.name
staged_root.mkdir()
files = []
for source in sorted(source_root.rglob("*")):
if source.is_symlink():
raise RuntimeError(f"symbolic links are not supported: {source}")
destination = staged_root / source.relative_to(source_root)
if source.is_dir():
destination.mkdir(exist_ok=True)
elif source.is_file():
destination.parent.mkdir(parents=True, exist_ok=True)
files.append((source, destination))
if workers == 1:
for source, destination in files:
copy_entry(source, destination)
elif files:
with ProcessPoolExecutor(max_workers=workers) as executor:
sources = (source for source, _ in files)
destinations = (destination for _, destination in files)
for _ in executor.map(copy_entry, sources, destinations):
pass
count = len(files)
if output_root.exists():
output_root.rmdir()
staged_root.replace(output_root)
return count
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"source",
nargs="?",
type=Path,
default=Path("Data"),
help="source dataset (default: Data/)",
)
parser.add_argument(
"output",
nargs="?",
type=Path,
default=Path("ResizedData"),
help="output dataset (default: ResizedData/)",
)
parser.add_argument(
"-j",
"--workers",
type=int,
default=DEFAULT_WORKERS,
help=f"parallel worker processes (default: {DEFAULT_WORKERS})",
)
return parser.parse_args()
def main():
args = parse_args()
try:
count = resize_dataset(args.source, args.output, args.workers)
except (OSError, RuntimeError, json.JSONDecodeError) as error:
raise SystemExit(f"error: {error}") from error
print(f"wrote {count} files to {args.output}")
if __name__ == "__main__":
main()