File size: 4,227 Bytes
0220f4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Generate camera preview images and timelapse videos from LPBF HDF5 data.

This script processes visible light and NIR camera images, creating:
- PNG images for each layer (5 image types × 1117 layers)
- Timelapse videos showing layer progression for each image type
"""

import h5py
import numpy as np
from pathlib import Path
from PIL import Image
import subprocess

HDF5_PATH = Path(__file__).parent.parent / "source/2024-05-01 M2 AMMTO Fatigue Blanks 05.hdf5"
PREVIEW_DIR = Path(__file__).parent.parent / "previews"

IMAGE_TYPES = [
    ("visible_0", "slices/camera_data/visible/0", "uint8"),   # Post-melt visible
    ("visible_1", "slices/camera_data/visible/1", "uint8"),   # Post-recoat visible
    ("nir_0", "slices/camera_data/nir/0", "uint16"),          # NIR sum
    ("nir_1", "slices/camera_data/nir/1", "uint16"),          # NIR max
    ("nir_2", "slices/camera_data/nir/2", "uint16"),          # NIR argmax
]


def normalize_image(data: np.ndarray, dtype: str) -> np.ndarray:
    """Normalize image data to uint8 for PNG output."""
    if dtype == "uint8":
        return data
    elif dtype == "uint16":
        data = data.astype(np.float32)
        p_low, p_high = np.percentile(data, [1, 99])
        if p_high > p_low:
            data = np.clip((data - p_low) / (p_high - p_low) * 255, 0, 255)
        else:
            data = np.zeros_like(data)
        return data.astype(np.uint8)
    else:
        raise ValueError(f"Unknown dtype: {dtype}")


def generate_pngs():
    """Generate PNG images for each layer and image type."""
    with h5py.File(HDF5_PATH, "r") as f:
        n_layers = f["slices/camera_data/visible/0"].shape[0]
        print(f"Generating PNGs for {n_layers} layers across {len(IMAGE_TYPES)} image types...")

        for img_name, hdf5_path, dtype in IMAGE_TYPES:
            output_dir = PREVIEW_DIR / img_name
            output_dir.mkdir(parents=True, exist_ok=True)

            dataset = f[hdf5_path]
            print(f"\nProcessing {img_name} ({dataset.shape})...")

            for layer_idx in range(n_layers):
                output_path = output_dir / f"layer_{layer_idx:04d}.png"

                if output_path.exists():
                    if layer_idx % 100 == 0:
                        print(f"  Layer {layer_idx}/{n_layers} (skipped, exists)")
                    continue

                data = dataset[layer_idx]
                normalized = normalize_image(data, dtype)

                img = Image.fromarray(normalized, mode="L")
                img.save(output_path, optimize=True)

                if layer_idx % 100 == 0:
                    print(f"  Layer {layer_idx}/{n_layers}")

            print(f"  Completed {img_name}: {n_layers} images")


def generate_videos(fps: int = 30):
    """Generate MP4 timelapse videos from PNG sequences."""
    print("\nGenerating timelapse videos...")

    for img_name, _, _ in IMAGE_TYPES:
        input_pattern = PREVIEW_DIR / img_name / "layer_%04d.png"
        output_path = PREVIEW_DIR / f"{img_name}.mp4"

        if output_path.exists():
            print(f"  {img_name}.mp4 already exists, skipping...")
            continue

        print(f"  Creating {img_name}.mp4...")

        cmd = [
            "ffmpeg",
            "-y",
            "-framerate", str(fps),
            "-i", str(input_pattern),
            "-c:v", "libx264",
            "-preset", "medium",
            "-crf", "23",
            "-pix_fmt", "yuv420p",
            str(output_path)
        ]

        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode != 0:
            print(f"    Error: {result.stderr}")
        else:
            print(f"    Created {output_path}")


def main():
    print("=" * 60)
    print("Camera Preview Generator")
    print("=" * 60)

    try:
        subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("Warning: ffmpeg not found. Videos will not be generated.")

    generate_pngs()
    generate_videos()

    print("\n" + "=" * 60)
    print("Camera preview generation complete!")
    print("=" * 60)


if __name__ == "__main__":
    main()