Sking / DDJ_real2render /create_grid_template.py
EntropyDrop
update
60df411
Raw
History Blame
9.35 kB
#!/usr/bin/env python3
import argparse
import os
import sys
import numpy as np
from PIL import Image, ImageColor
try:
from .create_template import VIEW_NAMES, parse_bg_color, resolve_renderer_path
except ImportError:
from create_template import VIEW_NAMES, parse_bg_color, resolve_renderer_path
DEFAULT_SIZE = "344x768"
def parse_rgb_color(color):
if isinstance(color, str):
return ImageColor.getrgb(color)
if isinstance(color, (tuple, list)) and len(color) >= 3:
return tuple(int(channel) for channel in color[:3])
raise ValueError(f"Invalid RGB color: {color!r}")
def render_visible_grid(mapping_path, skin_alpha, fill_color, grid_color):
import torch
mapping = torch.load(mapping_path, map_location="cpu")
required_keys = ("geometry_uv_layers", "geometry_masks", "geometry_sort_indices")
missing_keys = [key for key in required_keys if key not in mapping]
if missing_keys:
raise KeyError(
f"Geometry visibility data missing from {mapping_path}: {', '.join(missing_keys)}"
)
geometry_uv = mapping["geometry_uv_layers"].cpu().numpy()
geometry_masks = mapping["geometry_masks"].cpu().numpy().astype(bool)
sort_indices = mapping["geometry_sort_indices"].cpu().numpy().astype(np.intp)
if geometry_uv.shape[0] == 0:
raise ValueError(f"No geometry layers found in mapping: {mapping_path}")
layer_count, height, width = geometry_masks.shape
u = geometry_uv[..., 0].astype(np.intp)
v = geometry_uv[..., 1].astype(np.intp)
valid_uv = (u >= 0) & (u < 64) & (v >= 0) & (v < 64)
safe_u = np.clip(u, 0, 63)
safe_v = np.clip(v, 0, 63)
layer_visible = geometry_masks & valid_uv & (skin_alpha[safe_v, safe_u] > 0)
# The sort order is back-to-front, matching DifferentiableRenderer's
# compositing order. Pick only the nearest visible geometry at every pixel.
sorted_visible = np.take_along_axis(layer_visible, sort_indices, axis=0)
has_visible_surface = sorted_visible.any(axis=0)
nearest_from_front = np.argmax(sorted_visible[::-1], axis=0)
nearest_position = layer_count - 1 - nearest_from_front
nearest_geometry = np.take_along_axis(
sort_indices,
nearest_position[np.newaxis, ...],
axis=0,
)[0]
rows, columns = np.indices((height, width))
selected_u = u[nearest_geometry, rows, columns]
selected_v = v[nearest_geometry, rows, columns]
# A grid edge is a boundary between visible UV texels/geometries, or the
# silhouette between visible geometry and the transparent background.
grid_edges = np.zeros((height, width), dtype=bool)
left_visible = has_visible_surface[:, :-1]
right_visible = has_visible_surface[:, 1:]
horizontal_change = (left_visible != right_visible) | (
left_visible
& right_visible
& (
(nearest_geometry[:, :-1] != nearest_geometry[:, 1:])
| (selected_u[:, :-1] != selected_u[:, 1:])
| (selected_v[:, :-1] != selected_v[:, 1:])
)
)
grid_edges[:, :-1] |= horizontal_change & left_visible
grid_edges[:, 1:] |= horizontal_change & ~left_visible & right_visible
top_visible = has_visible_surface[:-1, :]
bottom_visible = has_visible_surface[1:, :]
vertical_change = (top_visible != bottom_visible) | (
top_visible
& bottom_visible
& (
(nearest_geometry[:-1, :] != nearest_geometry[1:, :])
| (selected_u[:-1, :] != selected_u[1:, :])
| (selected_v[:-1, :] != selected_v[1:, :])
)
)
grid_edges[:-1, :] |= vertical_change & top_visible
grid_edges[1:, :] |= vertical_change & ~top_visible & bottom_visible
grid_edges[0, :] |= has_visible_surface[0, :]
grid_edges[-1, :] |= has_visible_surface[-1, :]
grid_edges[:, 0] |= has_visible_surface[:, 0]
grid_edges[:, -1] |= has_visible_surface[:, -1]
output = np.zeros((height, width, 4), dtype=np.uint8)
output[has_visible_surface, :3] = fill_color
output[has_visible_surface, 3] = 255
output[grid_edges, :3] = grid_color
output[grid_edges, 3] = 255
return Image.fromarray(output, mode="RGBA")
def create_grid_template(
skin_path,
output_path,
renderer_path,
size=DEFAULT_SIZE,
bg_color="black",
fill_color="white",
grid_color="black",
):
"""Render four visible-surface Minecraft texel grids into one horizontal image."""
if not os.path.exists(skin_path):
raise FileNotFoundError(f"Skin image '{skin_path}' does not exist.")
dmr_path = resolve_renderer_path(renderer_path)
if dmr_path not in sys.path:
sys.path.insert(0, dmr_path)
from config import parse_sizes
if isinstance(size, str):
target_size = parse_sizes(size)[0]
elif isinstance(size, (tuple, list)) and len(size) == 2:
target_size = (int(size[0]), int(size[1]))
else:
target_size = tuple(int(value) for value in DEFAULT_SIZE.split("x"))
skin_img = Image.open(skin_path).convert("RGBA")
if skin_img.size != (64, 64):
raise ValueError(
f"Minecraft grid rendering requires a 64x64 skin, "
f"got {skin_img.size[0]}x{skin_img.size[1]}."
)
skin_np = np.array(skin_img)
alpha = skin_np[..., 3]
semi_transparent = (alpha > 0) & (alpha < 255)
skin_np[semi_transparent, 3] = 255
fill_rgb = parse_rgb_color(fill_color)
grid_rgb = parse_rgb_color(grid_color)
mappings_dir = os.path.join(dmr_path, f"mappings_{target_size[0]}x{target_size[1]}")
if not os.path.isdir(mappings_dir):
raise FileNotFoundError(
f"Differentiable renderer mappings not found for size "
f"{target_size[0]}x{target_size[1]}: {mappings_dir}"
)
rendered_images = []
for view_name in VIEW_NAMES:
print(f"Rendering visible grid view: {view_name} (Size: {target_size})...")
mapping_path = os.path.join(mappings_dir, f"{view_name}_mapping.pt")
if not os.path.isfile(mapping_path):
raise FileNotFoundError(f"View mapping not found: {mapping_path}")
rendered_image = render_visible_grid(
mapping_path=mapping_path,
skin_alpha=skin_np[..., 3],
fill_color=fill_rgb,
grid_color=grid_rgb,
)
if rendered_image.size != target_size:
raise ValueError(
f"Mapping size for {view_name} is {rendered_image.size}, expected {target_size}."
)
rendered_images.append(rendered_image)
widths, heights = zip(*(image.size for image in rendered_images))
merged_img = Image.new("RGBA", (sum(widths), max(heights)))
x_offset = 0
for image in rendered_images:
merged_img.paste(image, (x_offset, 0))
x_offset += image.width
parsed_bg = parse_bg_color(bg_color)
if parsed_bg is not None:
background = Image.new("RGBA", merged_img.size, parsed_bg)
merged_img = Image.alpha_composite(background, merged_img)
output_dir = os.path.dirname(os.path.abspath(output_path))
if output_dir:
os.makedirs(output_dir, exist_ok=True)
merged_img.save(output_path)
print(f"Successfully generated grid template: {output_path} (Size: {merged_img.size})")
return output_path
def main():
parser = argparse.ArgumentParser(
description=(
"Create a horizontal visible-surface grid for the front-left, "
"front-right, back-left, and back-right Minecraft views."
)
)
parser.add_argument(
"--skin",
"--skin_path",
dest="skin_path",
required=True,
help="Path to the input 64x64 Minecraft skin.",
)
parser.add_argument(
"--output",
"--output_path",
dest="output_path",
required=True,
help="Path to save the merged grid image.",
)
parser.add_argument(
"--renderer_path",
"--renderer",
dest="renderer_path",
required=True,
help="Path to the differentiable_minecraft_renderer directory.",
)
parser.add_argument(
"--size",
"--resolution",
default=DEFAULT_SIZE,
help=(
f"Resolution per view (default: {DEFAULT_SIZE}; four horizontal "
"views produce 1376x768)."
),
)
parser.add_argument(
"--bg_color",
"--bg-color",
"--background",
dest="bg_color",
default="black",
help="Output background color (default: black); use 'transparent' for transparency.",
)
parser.add_argument(
"--fill_color",
"--fill-color",
dest="fill_color",
default="white",
help="Visible surface fill color behind the black grid (default: white).",
)
parser.add_argument(
"--grid_color",
"--grid-color",
dest="grid_color",
default="black",
help="Grid line color (default: black).",
)
args = parser.parse_args()
create_grid_template(
skin_path=args.skin_path,
output_path=args.output_path,
renderer_path=args.renderer_path,
size=args.size,
bg_color=args.bg_color,
fill_color=args.fill_color,
grid_color=args.grid_color,
)
if __name__ == "__main__":
main()