HotSight / scripts /make_mask_overlays.py
hotsight's picture
Super-squash branch 'main' using huggingface_hub
4e6a175
Raw History Blame Contribute Delete
2.39 kB
#!/usr/bin/env python3
"""Create RGB/mask overlay JPEGs in each clip's mask directory."""
import argparse
import sys
from pathlib import Path
import numpy as np
from PIL import Image
ALPHA = 0.5
QUALITY = 90
COLORS = np.zeros((256, 3), dtype=np.uint8)
COLORS[1] = (150, 0, 0) # dark red
COLORS[2] = (255, 128, 0) # orange
COLORS[3] = (255, 230, 0) # yellow
COLORS[4] = (0, 200, 0) # green
COLORS[5] = (0, 0, 0) # black
def find_clips(root):
if (root / "rgb").is_dir() and (root / "mask").is_dir():
return [root]
return sorted(path.parent for path in root.glob("*/*/rgb") if (path.parent / "mask").is_dir())
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"root",
nargs="?",
type=Path,
default="Data",
help="dataset root or individual clip (default: Data/)",
)
return parser.parse_args()
def main():
root = parse_args().root
written = skipped = 0
for clip in find_clips(root):
masks = sorted((clip / "mask").glob("*.txt"))
if not masks:
print(f"{clip.name}: no masks, skipping")
continue
clip_written = 0
for mask_path in masks:
rgb_path = clip / "rgb" / mask_path.with_suffix(".png").name
if not rgb_path.is_file():
print(f" {clip.name}/{mask_path.stem}: no rgb, skipping")
skipped += 1
continue
rgb = np.asarray(Image.open(rgb_path).convert("RGB"))
height, width = rgb.shape[:2]
raw = np.frombuffer(mask_path.read_bytes(), dtype=np.uint8)
if raw.size != height * width:
sys.exit(
f"{mask_path}: {raw.size} px but rgb is "
f"{width}x{height} = {width * height}"
)
mask = (raw - ord("0")).reshape(height, width)
overlay = (1 - ALPHA) * rgb + ALPHA * COLORS[mask]
Image.fromarray(overlay.astype(np.uint8)).save(
mask_path.with_name(f"{mask_path.stem}_overlay.jpg"), quality=QUALITY
)
written += 1
clip_written += 1
print(f"{clip.name}: {clip_written} overlays -> {clip / 'mask'}")
print(f"\ndone: {written} written, {skipped} skipped")
if __name__ == "__main__":
main()