File size: 4,716 Bytes
d0e86f6 | 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 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Rendering utilities for video and image output."""
from pathlib import Path
import imageio
import numpy as np
from PIL import Image
def resample_list(items: list, target_length: int) -> list:
"""
Resample a list to a target length using nearest-neighbor interpolation.
Args:
items: Input list of any elements.
target_length: Desired output length.
Returns:
Resampled list of length target_length.
"""
if not items or target_length <= 0:
return []
n_in = len(items)
if target_length == 1:
return [items[0]]
return [
items[round(i * (n_in - 1) / (target_length - 1) + 1e-4)]
for i in range(target_length)
]
def make_image_grid(
images: list[Image.Image],
n_cols: int,
image_size: int | None = None,
) -> Image.Image:
"""
Create a grid image from a list of images.
Args:
images: List of PIL Images.
n_cols: Number of columns in the grid.
image_size: Optional size to resize images to (square).
Returns:
Single PIL Image containing the grid.
"""
if image_size is not None:
images = [img.resize((image_size, image_size)) for img in images]
n_rows = (len(images) + n_cols - 1) // n_cols
w, h = images[0].size
grid = Image.new("RGBA", (n_cols * w, n_rows * h), (0, 0, 0, 0))
for idx, img in enumerate(images):
col, row = idx % n_cols, idx // n_cols
grid.paste(img, (col * w, row * h))
return grid
def save_video(
frames: list[Image.Image],
output_path: str | Path,
fps: int = 12,
) -> None:
"""
Save a list of PIL Images as an MP4 video.
Args:
frames: List of PIL Images.
output_path: Path to save the video.
fps: Frames per second.
"""
if not frames:
return
frames_rgb = [np.array(frame.convert("RGB")) for frame in frames]
imageio.mimsave(str(output_path), frames_rgb, fps=fps)
def save_rgba_video(
frames: list[Image.Image],
output_path: str | Path,
bg_color: tuple[int, int, int] = (255, 255, 255),
fps: int = 12,
) -> None:
"""
Save RGBA frames as a video, compositing onto a solid background.
Args:
frames: List of PIL Images (RGBA mode).
output_path: Path to save the video.
bg_color: RGB background color (0-255). Defaults to white.
fps: Frames per second.
"""
if not frames:
return
composited = []
for frame in frames:
rgba = frame.convert("RGBA")
background = Image.new("RGB", rgba.size, bg_color)
background.paste(rgba, mask=rgba.split()[3])
composited.append(background)
save_video(composited, output_path, fps=fps)
def save_multiview_video_grid(
views: list[list[dict[str, Image.Image]]],
output_dir: str | Path,
modalities: list[str] | None = None,
n_cols: int = 2,
fps: int = 12,
image_size: int | None = None,
) -> list[Path]:
"""
Save multi-view predictions as grid videos, one per modality.
Args:
views: List of views, where each view is a list of frames,
and each frame is a dict mapping modality name to PIL Image.
output_dir: Directory to save videos.
modalities: Modalities to save. If None, saves all available.
n_cols: Number of columns in the grid.
fps: Frames per second.
image_size: Optional size to resize images to (square).
Returns:
List of saved file paths.
"""
if not views or not views[0]:
return []
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
n_frames = len(views[0])
# Find modalities available in all views and frames
available = set(views[0][0].keys())
for view in views:
for frame in view:
available &= set(frame.keys())
# Filter to requested modalities
if modalities is not None:
modalities = [m for m in modalities if m in available]
else:
modalities = sorted(available)
saved_files = []
for modality in modalities:
grid_frames = [
make_image_grid(
[view[i][modality] for view in views],
n_cols,
image_size,
)
for i in range(n_frames)
]
output_path = output_dir / f"grid_{modality}.mp4"
save_video(grid_frames, output_path, fps=fps)
saved_files.append(output_path)
return saved_files
|