File size: 2,391 Bytes
4e6a175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()