File size: 9,761 Bytes
505117b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""Create a side-by-side raw and Mask R-CNN segmentation showcase video."""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path

import cv2
import numpy as np
import torch
from detectron2 import model_zoo
from detectron2.config import get_cfg
from detectron2.engine import DefaultPredictor


CASE_SPECS = (
    ("5gs_22C", "45", "5 g/s | inlet subcooling 22 deg C | 45 V"),
    ("10gs_22C", "45V", "10 g/s | inlet subcooling 22 deg C | 45 V"),
    ("15gs_20C", "45", "15 g/s | inlet subcooling 20 deg C | 45 V"),
    ("25gs_20C", "45", "25 g/s | inlet subcooling 20 deg C | 45 V"),
)

ROI_X = 0
ROI_Y = 485
ROI_WIDTH = 1024
ROI_HEIGHT = 70
DISPLAY_Y0 = 360
DISPLAY_Y1 = 680
MINIMAL_DISPLAY_Y0 = 430
MINIMAL_DISPLAY_Y1 = 590
FRAME_SIZE = (1920, 720)
PANEL_SIZE = (880, 275)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset-root", required=True, type=Path)
    parser.add_argument("--weights", required=True, type=Path)
    parser.add_argument("--output", required=True, type=Path)
    parser.add_argument("--frames-per-case", type=int, default=20)
    parser.add_argument("--fps", type=float, default=5.0)
    parser.add_argument("--minimal-stacked", action="store_true")
    parser.add_argument("--score-threshold", type=float, default=0.30)
    parser.add_argument("--detections-per-image", type=int, default=300)
    parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
    return parser.parse_args()


def build_predictor(args: argparse.Namespace) -> DefaultPredictor:
    cfg = get_cfg()
    cfg.merge_from_file(
        model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
    )
    cfg.MODEL.WEIGHTS = str(args.weights)
    cfg.MODEL.DEVICE = args.device
    cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1
    cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = args.score_threshold
    cfg.MODEL.ANCHOR_GENERATOR.SIZES = [[8], [16], [32], [64], [128]]
    cfg.INPUT.MIN_SIZE_TEST = 640
    cfg.INPUT.MAX_SIZE_TEST = 900
    cfg.TEST.DETECTIONS_PER_IMAGE = args.detections_per_image
    return DefaultPredictor(cfg)


def select_frames(image_dir: Path, count: int) -> list[Path]:
    images = sorted(image_dir.glob("*.bmp"))
    if len(images) < count:
        raise ValueError(f"{image_dir} has {len(images)} BMP files; need {count}.")
    indices = np.linspace(0, len(images) - 1, count, dtype=int)
    return [images[index] for index in indices]


def union_mask(predictor: DefaultPredictor, roi: np.ndarray) -> np.ndarray:
    outputs = predictor(roi)
    masks = outputs["instances"].pred_masks.to("cpu").numpy()
    if len(masks) == 0:
        return np.zeros(roi.shape[:2], dtype=np.uint8)
    return np.any(masks, axis=0).astype(np.uint8) * 255


def make_overlay(roi: np.ndarray, mask: np.ndarray) -> np.ndarray:
    overlay = roi.copy()
    red = np.zeros_like(roi)
    red[:, :, 2] = 255
    selected = mask.astype(bool)
    overlay[selected] = cv2.addWeighted(roi, 0.48, red, 0.52, 0)[selected]
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(overlay, contours, -1, (70, 235, 110), 1)
    return overlay


def draw_text(image: np.ndarray, text: str, position: tuple[int, int], scale: float, color: tuple[int, int, int]) -> None:
    cv2.putText(image, text, position, cv2.FONT_HERSHEY_SIMPLEX, scale, color, 2, cv2.LINE_AA)


def compose_frame(
    raw: np.ndarray,
    overlay: np.ndarray,
    case_text: str,
    progress: str,
    display_fps: float,
) -> np.ndarray:
    canvas = np.full((FRAME_SIZE[1], FRAME_SIZE[0], 3), (20, 24, 30), dtype=np.uint8)
    draw_text(canvas, "BubbleID-Flow: Raw Optical Image and Mask R-CNN Segmentation", (55, 55), 0.92, (245, 245, 245))
    draw_text(canvas, case_text, (55, 105), 0.70, (185, 215, 235))
    draw_text(canvas, progress, (1420, 105), 0.55, (190, 190, 190))

    raw_panel = cv2.resize(raw, PANEL_SIZE, interpolation=cv2.INTER_AREA)
    overlay_panel = cv2.resize(overlay, PANEL_SIZE, interpolation=cv2.INTER_AREA)
    left_x, right_x, top_y = 70, 970, 180
    canvas[top_y : top_y + PANEL_SIZE[1], left_x : left_x + PANEL_SIZE[0]] = raw_panel
    canvas[top_y : top_y + PANEL_SIZE[1], right_x : right_x + PANEL_SIZE[0]] = overlay_panel
    cv2.rectangle(canvas, (left_x, top_y), (left_x + PANEL_SIZE[0], top_y + PANEL_SIZE[1]), (220, 220, 220), 2)
    cv2.rectangle(canvas, (right_x, top_y), (right_x + PANEL_SIZE[0], top_y + PANEL_SIZE[1]), (220, 220, 220), 2)
    draw_text(canvas, "RAW OPTICAL IMAGE", (left_x, top_y - 20), 0.66, (245, 245, 245))
    draw_text(canvas, "UNION-MASK OVERLAY", (right_x, top_y - 20), 0.66, (245, 245, 245))
    draw_text(canvas, "Red: predicted vapor region | Green: union-mask boundary", (55, 540), 0.62, (230, 155, 155))
    draw_text(canvas, f"Display uses uniformly sampled frames at {display_fps:g} fps; source acquisition rate: 3000 frames/s.", (55, 595), 0.52, (190, 190, 190))
    draw_text(canvas, "Metric: image-plane vapor area fraction, not volumetric void fraction.", (55, 635), 0.52, (190, 190, 190))
    return canvas


def compose_minimal_stacked(raw: np.ndarray, overlay: np.ndarray) -> np.ndarray:
    canvas = np.zeros((FRAME_SIZE[1], FRAME_SIZE[0], 3), dtype=np.uint8)
    panel_size = (1600, 250)
    raw_panel = cv2.resize(raw, panel_size, interpolation=cv2.INTER_AREA)
    overlay_panel = cv2.resize(overlay, panel_size, interpolation=cv2.INTER_AREA)
    left_x, top_y, bottom_y = 160, 70, 400
    canvas[top_y : top_y + panel_size[1], left_x : left_x + panel_size[0]] = raw_panel
    canvas[bottom_y : bottom_y + panel_size[1], left_x : left_x + panel_size[0]] = overlay_panel
    draw_text(canvas, "RAW", (left_x, 45), 0.70, (245, 245, 245))
    draw_text(canvas, "SEGMENTED", (left_x, 375), 0.70, (245, 245, 245))
    return canvas


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def main() -> None:
    args = parse_args()
    if args.frames_per_case <= 0 or args.fps <= 0:
        raise ValueError("frames-per-case and fps must be positive")
    image_root = args.dataset_root / "MultimodalData" / "Images"
    if not image_root.is_dir():
        raise FileNotFoundError(f"Expected image root: {image_root}")
    if not args.weights.is_file():
        raise FileNotFoundError(f"Weights not found: {args.weights}")

    args.output.parent.mkdir(parents=True, exist_ok=True)
    predictor = build_predictor(args)
    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    writer = cv2.VideoWriter(str(args.output), fourcc, args.fps, FRAME_SIZE)
    if not writer.isOpened():
        raise RuntimeError(f"Could not open video writer for {args.output}")

    selected: dict[str, list[str]] = {}
    try:
        total_frames = len(CASE_SPECS) * args.frames_per_case
        frame_number = 0
        for case_id, state_id, label in CASE_SPECS:
            source_files = select_frames(image_root / case_id / state_id, args.frames_per_case)
            selected[case_id] = [path.name for path in source_files]
            for image_path in source_files:
                image = cv2.imread(str(image_path), cv2.IMREAD_COLOR)
                if image is None or image.shape[:2] != (1024, 1024):
                    raise ValueError(f"Expected a 1024 x 1024 readable image: {image_path}")
                roi = image[ROI_Y : ROI_Y + ROI_HEIGHT, ROI_X : ROI_X + ROI_WIDTH]
                mask = union_mask(predictor, roi)
                if args.minimal_stacked:
                    display_y0, display_y1 = MINIMAL_DISPLAY_Y0, MINIMAL_DISPLAY_Y1
                else:
                    display_y0, display_y1 = DISPLAY_Y0, DISPLAY_Y1
                display_raw = image[display_y0:display_y1, :]
                display_overlay = display_raw.copy()
                y0 = ROI_Y - display_y0
                display_overlay[y0 : y0 + ROI_HEIGHT, :] = make_overlay(roi, mask)
                frame_number += 1
                if args.minimal_stacked:
                    writer.write(compose_minimal_stacked(display_raw, display_overlay))
                else:
                    writer.write(
                        compose_frame(
                            display_raw,
                            display_overlay,
                            label,
                            f"Frame {frame_number}/{total_frames}",
                            args.fps,
                        )
                    )
    finally:
        writer.release()

    manifest = {
        "dataset_root": str(args.dataset_root),
        "weights": str(args.weights),
        "weights_sha256": sha256(args.weights),
        "output": str(args.output),
        "duration_seconds": len(CASE_SPECS) * args.frames_per_case / args.fps,
        "fps": args.fps,
        "frames_per_case": args.frames_per_case,
        "score_threshold": args.score_threshold,
        "detections_per_image": args.detections_per_image,
        "roi_xywh": [ROI_X, ROI_Y, ROI_WIDTH, ROI_HEIGHT],
        "display_crop_y": [
            MINIMAL_DISPLAY_Y0 if args.minimal_stacked else DISPLAY_Y0,
            MINIMAL_DISPLAY_Y1 if args.minimal_stacked else DISPLAY_Y1,
        ],
        "minimal_stacked": args.minimal_stacked,
        "case_order": [spec[0] for spec in CASE_SPECS],
        "selected_frames": selected,
    }
    manifest_path = args.output.with_suffix(".json")
    manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
    print(f"Wrote {args.output}")
    print(f"Wrote {manifest_path}")


if __name__ == "__main__":
    main()