| |
| """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"), |
| ("visible_1", "slices/camera_data/visible/1", "uint8"), |
| ("nir_0", "slices/camera_data/nir/0", "uint16"), |
| ("nir_1", "slices/camera_data/nir/1", "uint16"), |
| ("nir_2", "slices/camera_data/nir/2", "uint16"), |
| ] |
|
|
|
|
| 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() |
|
|