Offical repo for the paper "LATO.2: Factorized 3D Mesh Generation with Vertex and Topology Flow"
feat: image-to-mesh via TRELLIS
lohhhha2828df49e82e
diff --git a/models/__init__.py b/models/__init__.pyindex 88b6db6..e549fb9 100644--- a/models/__init__.py+++ b/models/__init__.py@@ -6,4 +6,5 @@ from models.vertex_structured_flow import VertexSLatFlowModelfrom models.flow_sampler import VertFlowEulerCfgSampler, TopoFlowEulerSamplerfrom models.topo_autoencoder import TopologyVAEfrom models.topo_flow import TopologySiTFlow-from models.voxel_encoder import VoxelFieldConditioner\ No newline at end of file+from models.voxel_encoder import VoxelFieldConditioner+from models.background_remover import BackgroundRemover\ No newline at end of filediff --git a/models/background_remover.py b/models/background_remover.pynew file mode 100644index 0000000..6f06d3e--- /dev/null+++ b/models/background_remover.py@@ -0,0 +1,60 @@+import os++import torch+from PIL import Image+from torchvision import transforms++from utils import logging++REMBG_REPO_ID = "ZhengPeng7/BiRefNet"+++class BackgroundRemover:+ """BiRefNet matting model (https://huggingface.co/ZhengPeng7/BiRefNet).++ The model lives in ``ckpt_dir/BiRefNet``: reused when present, downloaded+ there otherwise. It ships its own code, which is executed on load+ (``trust_remote_code``).+ """++ def __init__(self, ckpt_dir: str, device: torch.device):+ from transformers import AutoModelForImageSegmentation++ self.model_dir = os.path.join(ckpt_dir, REMBG_REPO_ID.split("/")[-1])+ if not all(+ os.path.isfile(os.path.join(self.model_dir, f))+ for f in ("config.json", "model.safetensors")+ ):+ from huggingface_hub import snapshot_download++ logging.info(f"{self.model_dir} not found; downloading {REMBG_REPO_ID}")+ snapshot_download(+ REMBG_REPO_ID,+ local_dir=self.model_dir,+ allow_patterns=["*.json", "*.py", "*.safetensors"],+ )+ self.model = (+ AutoModelForImageSegmentation.from_pretrained(+ self.model_dir, trust_remote_code=True+ )+ .to(device)+ .eval()+ )+ self.transform = transforms.Compose(+ [+ transforms.Resize((1024, 1024)),+ transforms.ToTensor(),+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),+ ]+ )++ @torch.no_grad()+ def __call__(self, image: Image.Image) -> Image.Image:+ """RGB image -> RGBA image whose alpha is the predicted foreground matte."""+ param = next(self.model.parameters())+ x = self.transform(image).unsqueeze(0).to(device=param.device, dtype=param.dtype)+ matte = self.model(x)[-1].sigmoid()[0].float().cpu() # (1, 1024, 1024)+ mask = transforms.ToPILImage()(matte).resize(image.size)+ out = image.copy()+ out.putalpha(mask)+ return outdiff --git a/models/trellis_ss/__init__.py b/models/trellis_ss/__init__.pynew file mode 100644index 0000000..8b03e35--- /dev/null+++ b/models/trellis_ss/__init__.py@@ -0,0 +1,58 @@+"""TRELLIS stage-1 (sparse structure) models: image -> 64^3 occupancy.++Self-contained port of the sparse-structure flow and decoder of+https://github.com/microsoft/TRELLIS, enough to load the released checkpoints.+"""++import json+import os++from safetensors.torch import load_file++from utils import logging++from .decoder import SparseStructureDecoder+from .flow import SparseStructureFlowModel+from .sampler import SSFlowEulerSampler++TRELLIS_REPO_ID = "microsoft/TRELLIS-image-large"+SS_FLOW_NAME = "ss_flow_img_dit_L_16l8_fp16"+SS_DECODER_NAME = "ss_dec_conv3d_16l8_fp16"+# image conditioning the released SS flow was trained with+SS_COND_MODEL = "dinov2_vitl14_reg"+SS_COND_RESOLUTION = 518++_MODEL_CLASSES = {+ "SparseStructureFlowModel": SparseStructureFlowModel,+ "SparseStructureDecoder": SparseStructureDecoder,+}+++def load_trellis_model(name, ckpt_dir, device, repo_id=TRELLIS_REPO_ID):+ """Load a TRELLIS checkpoint pair ``ckpts/<name>.json`` + ``.safetensors``.++ Files already under ``ckpt_dir`` are reused; missing ones are downloaded+ there from the Hugging Face Hub repo ``repo_id``.+ """+ paths = {}+ for ext in ("json", "safetensors"):+ rel = f"ckpts/{name}.{ext}"+ path = os.path.join(ckpt_dir, rel)+ if not os.path.isfile(path):+ from huggingface_hub import hf_hub_download++ logging.info(f"{path} not found; downloading {repo_id}/{rel}")+ path = hf_hub_download(repo_id, rel, local_dir=ckpt_dir)+ paths[ext] = path++ with open(paths["json"]) as f:+ config = json.load(f)+ if config["name"] not in _MODEL_CLASSES:+ raise ValueError(+ f"{paths['json']}: unsupported TRELLIS model {config['name']!r}; "+ f"supported: {sorted(_MODEL_CLASSES)}"+ )+ model = _MODEL_CLASSES[config["name"]](**config["args"])+ model.load_state_dict(load_file(paths["safetensors"]), strict=True)+ logging.info(f"loaded {config['name']} from {paths['safetensors']}")+ return model.to(device).eval()diff --git a/models/trellis_ss/decoder.py b/models/trellis_ss/decoder.pynew file mode 100644index 0000000..05142cd--- /dev/null+++ b/models/trellis_ss/decoder.py@@ -0,0 +1,136 @@+# MIT License++# Copyright (c) Microsoft Corporation.++# Permission is hereby granted, free of charge, to any person obtaining a copy+# of this software and associated documentation files (the "Software"), to deal+# in the Software without restriction, including without limitation the rights+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+# copies of the Software, and to permit persons to whom the Software is+# furnished to do so, subject to the following conditions:++# The above copyright notice and this permission notice shall be included in all+# copies or substantial portions of the Software.++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+# SOFTWARE++# Copied and trimmed (decoder only) from+# https://github.com/microsoft/TRELLIS/blob/main/trellis/models/sparse_structure_vae.py++from typing import List, Literal, Optional++import torch+import torch.nn as nn+import torch.nn.functional as F++from modules.utils import convert_module_to_f16, zero_module++from .modules import ChannelLayerNorm32, GroupNorm32, pixel_shuffle_3d+++def norm_layer(norm_type: str, *args, **kwargs) -> nn.Module:+ if norm_type == "group":+ return GroupNorm32(32, *args, **kwargs)+ elif norm_type == "layer":+ return ChannelLayerNorm32(*args, **kwargs)+ raise ValueError(f"Invalid norm type {norm_type}")+++class ResBlock3d(nn.Module):+ def __init__(+ self,+ channels: int,+ out_channels: Optional[int] = None,+ norm_type: Literal["group", "layer"] = "layer",+ ):+ super().__init__()+ self.channels = channels+ self.out_channels = out_channels or channels++ self.norm1 = norm_layer(norm_type, channels)+ self.norm2 = norm_layer(norm_type, self.out_channels)+ self.conv1 = nn.Conv3d(channels, self.out_channels, 3, padding=1)+ self.conv2 = zero_module(+ nn.Conv3d(self.out_channels, self.out_channels, 3, padding=1)+ )+ self.skip_connection = (+ nn.Conv3d(channels, self.out_channels, 1)+ if channels != self.out_channels+ else nn.Identity()+ )++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ h = self.norm1(x)+ h = F.silu(h)+ h = self.conv1(h)+ h = self.norm2(h)+ h = F.silu(h)+ h = self.conv2(h)+ return h + self.skip_connection(x)+++class UpsampleBlock3d(nn.Module):+ def __init__(self, in_channels: int, out_channels: int):+ super().__init__()+ self.conv = nn.Conv3d(in_channels, out_channels * 8, 3, padding=1)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return pixel_shuffle_3d(self.conv(x), 2)+++class SparseStructureDecoder(nn.Module):+ """TRELLIS sparse-structure decoder: latent grid -> occupancy logits."""++ def __init__(+ self,+ out_channels: int,+ latent_channels: int,+ num_res_blocks: int,+ channels: List[int],+ num_res_blocks_middle: int = 2,+ norm_type: Literal["group", "layer"] = "layer",+ use_fp16: bool = False,+ ):+ super().__init__()+ self.out_channels = out_channels+ self.latent_channels = latent_channels+ self.dtype = torch.float16 if use_fp16 else torch.float32++ self.input_layer = nn.Conv3d(latent_channels, channels[0], 3, padding=1)++ # as upstream: norm_type only selects the output norm, the residual+ # blocks always use their default layer norm+ self.middle_block = nn.Sequential(+ *[ResBlock3d(channels[0], channels[0]) for _ in range(num_res_blocks_middle)]+ )++ self.blocks = nn.ModuleList([])+ for i, ch in enumerate(channels):+ self.blocks.extend([ResBlock3d(ch, ch) for _ in range(num_res_blocks)])+ if i < len(channels) - 1:+ self.blocks.append(UpsampleBlock3d(ch, channels[i + 1]))++ self.out_layer = nn.Sequential(+ norm_layer(norm_type, channels[-1]),+ nn.SiLU(),+ nn.Conv3d(channels[-1], out_channels, 3, padding=1),+ )++ if use_fp16:+ self.blocks.apply(convert_module_to_f16)+ self.middle_block.apply(convert_module_to_f16)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ h = self.input_layer(x)+ h = h.type(self.dtype)+ h = self.middle_block(h)+ for block in self.blocks:+ h = block(h)+ h = h.type(x.dtype)+ return self.out_layer(h)diff --git a/models/trellis_ss/flow.py b/models/trellis_ss/flow.pynew file mode 100644index 0000000..b9c8aab--- /dev/null+++ b/models/trellis_ss/flow.py@@ -0,0 +1,135 @@+# MIT License++# Copyright (c) Microsoft Corporation.++# Permission is hereby granted, free of charge, to any person obtaining a copy+# of this software and associated documentation files (the "Software"), to deal+# in the Software without restriction, including without limitation the rights+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+# copies of the Software, and to permit persons to whom the Software is+# furnished to do so, subject to the following conditions:++# The above copyright notice and this permission notice shall be included in all+# copies or substantial portions of the Software.++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+# SOFTWARE++# Copied and trimmed (inference only) from+# https://github.com/microsoft/TRELLIS/blob/main/trellis/models/sparse_structure_flow.py++from typing import Literal, Optional++import torch+import torch.nn as nn+import torch.nn.functional as F++from modules.transformer import AbsolutePositionEmbedder, TimestepEmbedder+from modules.utils import convert_module_to_f16++from .modules import ModulatedTransformerCrossBlock+++class SparseStructureFlowModel(nn.Module):+ """TRELLIS stage-1 flow transformer over the dense sparse-structure latent grid."""++ def __init__(+ self,+ resolution: int,+ in_channels: int,+ model_channels: int,+ cond_channels: int,+ out_channels: int,+ num_blocks: int,+ num_heads: Optional[int] = None,+ num_head_channels: Optional[int] = 64,+ mlp_ratio: float = 4,+ patch_size: int = 2,+ pe_mode: Literal["ape", "rope"] = "ape",+ use_fp16: bool = False,+ share_mod: bool = False,+ qk_rms_norm: bool = False,+ qk_rms_norm_cross: bool = False,+ ):+ super().__init__()+ if patch_size != 1 or pe_mode != "ape":+ raise NotImplementedError(+ f"only patch_size=1 / pe_mode='ape' sparse-structure flows are "+ f"supported, got patch_size={patch_size}, pe_mode={pe_mode!r}"+ )+ self.resolution = resolution+ self.in_channels = in_channels+ self.model_channels = model_channels+ self.cond_channels = cond_channels+ self.out_channels = out_channels+ self.num_blocks = num_blocks+ self.num_heads = num_heads or model_channels // num_head_channels+ self.mlp_ratio = mlp_ratio+ self.share_mod = share_mod+ self.dtype = torch.float16 if use_fp16 else torch.float32++ self.t_embedder = TimestepEmbedder(model_channels)+ if share_mod:+ self.adaLN_modulation = nn.Sequential(+ nn.SiLU(), nn.Linear(model_channels, 6 * model_channels, bias=True)+ )++ coords = torch.meshgrid(+ *[torch.arange(resolution) for _ in range(3)], indexing="ij"+ )+ coords = torch.stack(coords, dim=-1).reshape(-1, 3)+ self.register_buffer(+ "pos_emb", AbsolutePositionEmbedder(model_channels, 3)(coords)+ )++ self.input_layer = nn.Linear(in_channels, model_channels)+ self.blocks = nn.ModuleList(+ [+ ModulatedTransformerCrossBlock(+ model_channels,+ cond_channels,+ num_heads=self.num_heads,+ mlp_ratio=self.mlp_ratio,+ share_mod=share_mod,+ qk_rms_norm=qk_rms_norm,+ qk_rms_norm_cross=qk_rms_norm_cross,+ )+ for _ in range(num_blocks)+ ]+ )+ self.out_layer = nn.Linear(model_channels, out_channels)++ if use_fp16:+ self.blocks.apply(convert_module_to_f16)++ def forward(+ self, x: torch.Tensor, t: torch.Tensor, cond: torch.Tensor+ ) -> torch.Tensor:+ """x: (B, C, R, R, R) noisy latent, t: (B,) in [0, 1000], cond: (B, L, C_cond)."""+ res = self.resolution+ assert [*x.shape] == [x.shape[0], self.in_channels, res, res, res], (+ f"Input shape mismatch, got {x.shape}, expected "+ f"{[x.shape[0], self.in_channels, res, res, res]}"+ )++ h = x.view(*x.shape[:2], -1).permute(0, 2, 1).contiguous()+ h = self.input_layer(h)+ h = h + self.pos_emb[None]+ t_emb = self.t_embedder(t)+ if self.share_mod:+ t_emb = self.adaLN_modulation(t_emb)+ t_emb = t_emb.type(self.dtype)+ h = h.type(self.dtype)+ cond = cond.type(self.dtype)+ for block in self.blocks:+ h = block(h, t_emb, cond)+ h = h.type(x.dtype)+ h = F.layer_norm(h, h.shape[-1:])+ h = self.out_layer(h)++ return h.permute(0, 2, 1).view(h.shape[0], h.shape[2], res, res, res).contiguous()diff --git a/models/trellis_ss/modules.py b/models/trellis_ss/modules.pynew file mode 100644index 0000000..b9b3703--- /dev/null+++ b/models/trellis_ss/modules.py@@ -0,0 +1,196 @@+# MIT License++# Copyright (c) Microsoft Corporation.++# Permission is hereby granted, free of charge, to any person obtaining a copy+# of this software and associated documentation files (the "Software"), to deal+# in the Software without restriction, including without limitation the rights+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+# copies of the Software, and to permit persons to whom the Software is+# furnished to do so, subject to the following conditions:++# The above copyright notice and this permission notice shall be included in all+# copies or substantial portions of the Software.++# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+# SOFTWARE++# Dense building blocks of the TRELLIS sparse-structure models, copied and+# trimmed from https://github.com/microsoft/TRELLIS (trellis/modules). Module+# and parameter names are kept so the released checkpoints load unchanged.++from typing import Literal, Optional++import torch+import torch.nn as nn+import torch.nn.functional as F++from modules.norm import LayerNorm32+++class GroupNorm32(nn.GroupNorm):+ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return super().forward(x.float()).type(x.dtype)+++class ChannelLayerNorm32(LayerNorm32):+ def forward(self, x: torch.Tensor) -> torch.Tensor:+ dim = x.dim()+ x = x.permute(0, *range(2, dim), 1).contiguous()+ x = super().forward(x)+ return x.permute(0, dim - 1, *range(1, dim - 1)).contiguous()+++def pixel_shuffle_3d(x: torch.Tensor, scale_factor: int) -> torch.Tensor:+ B, C, H, W, D = x.shape+ C_ = C // scale_factor**3+ x = x.reshape(B, C_, scale_factor, scale_factor, scale_factor, H, W, D)+ x = x.permute(0, 1, 5, 2, 6, 3, 7, 4)+ return x.reshape(B, C_, H * scale_factor, W * scale_factor, D * scale_factor)+++class FeedForwardNet(nn.Module):+ def __init__(self, channels: int, mlp_ratio: float = 4.0):+ super().__init__()+ self.mlp = nn.Sequential(+ nn.Linear(channels, int(channels * mlp_ratio)),+ nn.GELU(approximate="tanh"),+ nn.Linear(int(channels * mlp_ratio), channels),+ )++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return self.mlp(x)+++class MultiHeadRMSNorm(nn.Module):+ def __init__(self, dim: int, heads: int):+ super().__init__()+ self.scale = dim**0.5+ self.gamma = nn.Parameter(torch.ones(heads, dim))++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return (F.normalize(x.float(), dim=-1) * self.gamma * self.scale).to(x.dtype)+++class MultiHeadAttention(nn.Module):+ """Full (non-windowed) multi-head self- or cross-attention over dense tokens."""++ def __init__(+ self,+ channels: int,+ num_heads: int,+ ctx_channels: Optional[int] = None,+ type: Literal["self", "cross"] = "self",+ qkv_bias: bool = True,+ qk_rms_norm: bool = False,+ ):+ super().__init__()+ assert channels % num_heads == 0+ assert type in ["self", "cross"], f"Invalid attention type: {type}"+ self.channels = channels+ self.head_dim = channels // num_heads+ self.ctx_channels = ctx_channels if ctx_channels is not None else channels+ self.num_heads = num_heads+ self._type = type+ self.qk_rms_norm = qk_rms_norm++ if self._type == "self":+ self.to_qkv = nn.Linear(channels, channels * 3, bias=qkv_bias)+ else:+ self.to_q = nn.Linear(channels, channels, bias=qkv_bias)+ self.to_kv = nn.Linear(self.ctx_channels, channels * 2, bias=qkv_bias)++ if self.qk_rms_norm:+ self.q_rms_norm = MultiHeadRMSNorm(self.head_dim, num_heads)+ self.k_rms_norm = MultiHeadRMSNorm(self.head_dim, num_heads)++ self.to_out = nn.Linear(channels, channels)++ def forward(+ self, x: torch.Tensor, context: Optional[torch.Tensor] = None+ ) -> torch.Tensor:+ B, L, _ = x.shape+ if self._type == "self":+ qkv = self.to_qkv(x).reshape(B, L, 3, self.num_heads, -1)+ q, k, v = qkv.unbind(dim=2) # each (B, L, H, C)+ else:+ q = self.to_q(x).reshape(B, L, self.num_heads, -1)+ kv = self.to_kv(context).reshape(B, context.shape[1], 2, self.num_heads, -1)+ k, v = kv.unbind(dim=2)+ if self.qk_rms_norm:+ q = self.q_rms_norm(q)+ k = self.k_rms_norm(k)+ h = F.scaled_dot_product_attention(+ q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)+ ) # (B, H, L, C)+ h = h.transpose(1, 2).reshape(B, L, -1)+ return self.to_out(h)+++class ModulatedTransformerCrossBlock(nn.Module):+ """Transformer block (MSA + MCA + FFN) with adaptive layer norm conditioning."""++ def __init__(+ self,+ channels: int,+ ctx_channels: int,+ num_heads: int,+ mlp_ratio: float = 4.0,+ qk_rms_norm: bool = False,+ qk_rms_norm_cross: bool = False,+ qkv_bias: bool = True,+ share_mod: bool = False,+ ):+ super().__init__()+ self.share_mod = share_mod+ self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6)+ self.norm2 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6)+ self.norm3 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6)+ self.self_attn = MultiHeadAttention(+ channels,+ num_heads=num_heads,+ type="self",+ qkv_bias=qkv_bias,+ qk_rms_norm=qk_rms_norm,+ )+ self.cross_attn = MultiHeadAttention(+ channels,+ ctx_channels=ctx_channels,+ num_heads=num_heads,+ type="cross",+ qkv_bias=qkv_bias,+ qk_rms_norm=qk_rms_norm_cross,+ )+ self.mlp = FeedForwardNet(channels, mlp_ratio=mlp_ratio)+ if not share_mod:+ self.adaLN_modulation = nn.Sequential(+ nn.SiLU(), nn.Linear(channels, 6 * channels, bias=True)+ )++ def forward(+ self, x: torch.Tensor, mod: torch.Tensor, context: torch.Tensor+ ) -> torch.Tensor:+ if not self.share_mod:+ mod = self.adaLN_modulation(mod)+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = mod.chunk(+ 6, dim=1+ )+ h = self.norm1(x)+ h = h * (1 + scale_msa.unsqueeze(1)) + shift_msa.unsqueeze(1)+ h = self.self_attn(h)+ h = h * gate_msa.unsqueeze(1)+ x = x + h+ h = self.norm2(x)+ h = self.cross_attn(h, context)+ x = x + h+ h = self.norm3(x)+ h = h * (1 + scale_mlp.unsqueeze(1)) + shift_mlp.unsqueeze(1)+ h = self.mlp(h)+ h = h * gate_mlp.unsqueeze(1)+ x = x + h+ return xdiff --git a/models/trellis_ss/sampler.py b/models/trellis_ss/sampler.pynew file mode 100644index 0000000..913ab40--- /dev/null+++ b/models/trellis_ss/sampler.py@@ -0,0 +1,41 @@+import numpy as np+import torch+++class SSFlowEulerSampler:+ """Euler flow sampler with classifier-free guidance limited to a t-interval.++ Same update rule as TRELLIS' FlowEulerGuidanceIntervalSampler: guidance is+ applied only while t is inside ``cfg_interval``; elsewhere the conditional+ prediction is used as is.+ """++ def _pred_v(self, model, x_t, t, cond):+ t_vec = torch.full(+ (x_t.shape[0],), 1000.0 * t, device=x_t.device, dtype=torch.float32+ )+ return model(x_t, t_vec, cond)++ @torch.no_grad()+ def sample(+ self,+ model,+ noise,+ cond,+ neg_cond,+ steps=25,+ cfg_strength=5.0,+ cfg_interval=(0.5, 1.0),+ rescale_t=3.0,+ ):+ x = noise+ t_seq = np.linspace(1.0, 0.0, steps + 1)+ t_seq = rescale_t * t_seq / (1 + (rescale_t - 1) * t_seq)+ for i in range(steps):+ t, t_prev = float(t_seq[i]), float(t_seq[i + 1])+ v = self._pred_v(model, x, t, cond)+ if cfg_interval[0] <= t <= cfg_interval[1]:+ v_uncond = self._pred_v(model, x, t, neg_cond)+ v = (1 + cfg_strength) * v - cfg_strength * v_uncond+ x = x - (t - t_prev) * v+ return xdiff --git a/readme.md b/readme.mdindex 55b1f1e..eed2a9a 100644--- a/readme.md+++ b/readme.md@@ -45,6 +45,11 @@- **Part-wise generation** (bottom middle).- **Topology-adaptive editing** (bottom right).+## News++- **2026.11.19**: Released the image-to-mesh pipeline.+- **2026.11.18**: Released updated V-Flow and T-Flow weights, further improved with post-training refinement.+## Installation1. Clone the repo:@@ -72,7 +77,7 @@ python scripts/ckpt_download.py## Inference-All inference scripts take a directory of input meshes (`--mesh_dir`) and write results to `--out_dir`. Three bundled examples live in [`assets/example_mesh/`](./assets/example_mesh).+All inference scripts take a directory of input meshes (`--mesh_dir`; `image_e2e_inference.py` takes images via `--image_dir`) and write results to `--out_dir`. Three bundled examples live in [`assets/example_mesh/`](./assets/example_mesh).### Quick start@@ -96,6 +101,19 @@ python scripts/e2e_inference.py \[--batch_size 4]```+### Image to mesh (`image_e2e_inference.py`)++Same pipeline, but the coarse voxel scaffold is generated from an image instead of taken from an input mesh: image → [TRELLIS](https://github.com/Microsoft/TRELLIS) sparse-structure stage → V-Flow → T-Flow.+Outputs per image: the same meshes / vertices as `e2e_inference.py`, plus `<id>_cond.png` (the conditioning image) and `<id>_ss.ply` (the generated 64³ scaffold).++```bash+python scripts/image_e2e_inference.py \+ --image_dir <dir> \+ --out_dir outputs/image_e2e_run/<dir> \+ --vert_num <vert_num> \+ [--batch_size 4]+```+### V-Flow (`vflow_inference.py`)First stage only — generates vertices from the conditioning view (optionally also reconstructs them via the VAE with `--reconstruct`). Outputs the generated / GT / reconstructed vertex PLYs plus the render.@@ -138,7 +156,7 @@ The V-Flow stage (`e2e_inference.py` / `vflow_inference.py`) generates a control- **Fixed target** (default): `--vert_num <N>` (default `2000`).- **Scaled from the input**: `--use_gt_vert_count --scaler <s>` uses the input mesh's own vertex count multiplied by `<s>`.-Either way the count is clamped to `[--min_verts, --max_verts]` (defaults `200`–`5000`).+Either way the count is clamped to `[--min_verts, --max_verts]` (defaults `200`–`5000`). `image_e2e_inference.py` has no input mesh, so it only takes `--vert_num`.### Notes@@ -146,7 +164,8 @@ Either way the count is clamped to `[--min_verts, --max_verts]` (defaults `200`> Generated meshes may still contain holes and incorrect connectivity. We believe these artifacts can be largely resolved by scaling up.- **Hardware**: runs in ~8 GB VRAM; end-to-end generation takes ~5 s per mesh on a single H800.-- **Image-to-structure**: to obtain the coarse voxel scaffold from a single image (instead of an existing mesh), you can directly reuse [TRELLIS](https://github.com/Microsoft/TRELLIS)'s sparse-structure stage.+- **Image-to-structure**: `image_e2e_inference.py` obtains the coarse voxel scaffold from a single image (instead of an existing mesh) by reusing [TRELLIS](https://github.com/Microsoft/TRELLIS)'s sparse-structure stage. Swapping in the sparse-structure flow from [TRELLIS.2](https://github.com/microsoft/TRELLIS.2) would give better results, but it depends on DINOv3.+- **Background removal**: `image_e2e_inference.py` mattes every input image with [BiRefNet](https://github.com/ZhengPeng7/BiRefNet) to extract the foreground.## Acknowledgementsdiff --git a/scripts/e2e_inference.py b/scripts/e2e_inference.pyindex 2366c25..6d429d4 100644--- a/scripts/e2e_inference.py+++ b/scripts/e2e_inference.py@@ -33,7 +33,6 @@ os.environ.setdefault("EGL_PLATFORM", "surfaceless")import numpy as npimport torch-import trimeshfrom PIL import Imagefrom torch.utils.data import DataLoader@@ -51,7 +50,7 @@ from models import ()from modules.sparse import SparseTensorimport utils.logging as logging-from utils.export import export_vertex+from utils.export import export_mesh, export_vertexfrom utils.inference import (build_voxel_fields,compute_density,@@ -143,22 +142,6 @@ def parse_args():return args-def export_mesh(out_dir, base_name, vert_int, vert_offsets, faces, resolution):- """OBJ pair matching export_vertex's PLY conventions (offset verts / int coords)."""- res = float(resolution)- vert_with_offset = (- vert_int.astype(np.float64) / res- - 0.5- + vert_offsets.astype(np.float64) / (res * 2.0)- )- trimesh.Trimesh(vertices=vert_with_offset, faces=faces).export(- os.path.join(out_dir, f"{base_name}_pred.obj")- )- trimesh.Trimesh(vertices=vert_int.astype(np.float64), faces=faces).export(- os.path.join(out_dir, f"{base_name}_pred_coords.obj")- )--def main():logging.info("End-to-end inference starting...")diff --git a/scripts/image_e2e_inference.py b/scripts/image_e2e_inference.pynew file mode 100644index 0000000..1d47b7c--- /dev/null+++ b/scripts/image_e2e_inference.py@@ -0,0 +1,462 @@+"""+Image -> mesh: TRELLIS sparse-structure stage -> V-Flow -> T-Flow.++Outputs into --out_dir:+ <image_id>_cond.png the conditioning image (foreground crop on black) fed to DINO-v2+ <image_id>_ss.ply generated 64^3 sparse structure (voxel centers) in [-0.5, 0.5]+ <image_id>_pred.ply generated vertices (+offset head) in [-0.5, 0.5]+ <image_id>_pred_coords.ply generated vertex voxel coords in [0, 1024)+ <image_id>_pred.obj generated mesh (offset vertices, faces) in [-0.5, 0.5]+ <image_id>_pred_coords.obj generated mesh on integer voxel coords in [0, 1024)++Every image is matted with BiRefNet to find its foreground; an alpha channel+already in the file is ignored (flattened onto white).++Usage:+ python scripts/image_e2e_inference.py --image_dir <dir> --out_dir outputs/image_e2e_run/<dir> \+ [--vert_num 2000] [--ss_steps 25] [--ss_cfg_strength 5.0] \+ [--cfg_strength 3.0] [--vflow_steps 24] [--tflow_steps 50] \+ [--no-fill_open_rings] [--max_ring_size 12]+"""++import argparse+import os+import sys+import time+from collections import Counter++import tqdm++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+sys.path.insert(0, ROOT)+os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")++import numpy as np+import torch+import trimesh+from PIL import Image++from models import (+ BackgroundRemover,+ DinoV2Encoder,+ OffsetHead,+ TopoFlowEulerSampler,+ TopologySiTFlow,+ TopologyVAE,+ VertexSLatFlowModel,+ VertFlowEulerCfgSampler,+ VertexVAE,+ VoxelFieldConditioner,+)+from models.trellis_ss import (+ SS_COND_MODEL,+ SS_COND_RESOLUTION,+ SS_DECODER_NAME,+ SS_FLOW_NAME,+ SSFlowEulerSampler,+ load_trellis_model,+)+from modules.sparse import SparseTensor+import utils.logging as logging+from utils.export import export_mesh, export_vertex+from utils.image import IMAGE_EXTENSIONS, crop_foreground, load_rgba+from utils.inference import (+ build_voxel_fields,+ decode_vertices,+ edges_to_faces,+ pad_verts,+)+from utils.load import load_latov2_model+++def parse_args():+ p = argparse.ArgumentParser(+ description="image -> sparse structure -> vertex + topology generation"+ )+ p.add_argument("--image_dir", required=True, help="directory of input images")+ p.add_argument(+ "--out_dir", required=True, help="output directory for the PLYs / OBJs"+ )+ p.add_argument("--vflow_ckpt", default=os.path.join(ROOT, "ckpt", "vflow.pt"))+ p.add_argument("--vvae_ckpt", default=os.path.join(ROOT, "ckpt", "vvae.pt"))+ p.add_argument(+ "--offset_head_ckpt", default=os.path.join(ROOT, "ckpt", "offset_head.pt")+ )+ p.add_argument("--tflow_ckpt", default=os.path.join(ROOT, "ckpt", "tflow.pt"))+ p.add_argument("--tvae_ckpt", default=os.path.join(ROOT, "ckpt", "tvae.pt"))+ p.add_argument(+ "--voxel_encoder_ckpt",+ default=os.path.join(ROOT, "ckpt", "voxel_encoder.pt"),+ )+ p.add_argument(+ "--trellis_dir",+ default=os.path.join(ROOT, "ckpt", "trellis"),+ help=(+ "TRELLIS sparse-structure flow / decoder checkpoints; reused when "+ "present, downloaded otherwise"+ ),+ )+ p.add_argument(+ "--rembg_dir",+ default=os.path.join(ROOT, "ckpt", "rembg"),+ help=(+ "BiRefNet background-removal model applied to every image; reused "+ "when present, downloaded otherwise (its bundled code is executed)"+ ),+ )+ p.add_argument("--batch_size", type=int, default=1)+ p.add_argument(+ "--num_samples", type=int, default=None, help="only run the first N images"+ )+ p.add_argument("--inference_threshold", type=float, default=0.5)+ p.add_argument("--seed", type=int, default=42)+ # conditioning image+ p.add_argument(+ "--crop_padding",+ type=float,+ default=1.2,+ help="crop side relative to the foreground bounding box (training value: 1.2)",+ )+ # sparse-structure flow sampling (TRELLIS defaults)+ p.add_argument("--ss_steps", type=int, default=25, help="SS-Flow Euler steps")+ p.add_argument("--ss_cfg_strength", type=float, default=5.0)+ p.add_argument(+ "--ss_cfg_interval",+ type=float,+ nargs=2,+ default=(0.5, 1.0),+ metavar=("T_MIN", "T_MAX"),+ help="apply SS-Flow guidance only while t is inside this interval",+ )+ p.add_argument("--ss_rescale_t", type=float, default=3.0)+ # vertex flow sampling+ p.add_argument("--vflow_steps", type=int, default=24, help="V-Flow Euler steps")+ p.add_argument("--cfg_strength", type=float, default=3.0)+ p.add_argument("--rescale_t", type=float, default=1.0)+ p.add_argument("--vert_num", type=int, default=2000, help="target vertex count")+ # topology flow sampling / decoding+ p.add_argument("--tflow_steps", type=int, default=50, help="T-Flow Euler steps")+ p.add_argument("--edge_threshold", type=float, default=0.0)+ p.add_argument("--chunk_size", type=int, default=20000)+ p.add_argument(+ "--fill_open_rings",+ action=argparse.BooleanOptionalAction,+ default=True,+ help=(+ "post-process: triangulate chordless rings of open edges (edges with "+ "fewer than two faces) by minimum area, not the voxel support filter"+ ),+ )+ p.add_argument(+ "--max_ring_size",+ type=int,+ default=12,+ help="largest open-edge ring (in edges) that --fill_open_rings closes",+ )+ p.add_argument(+ "--dino_hub_dir",+ default=os.path.join(ROOT, "ckpt", "dinov2"),+ help="torch.hub cache for DINO-v2; reused when present, downloaded otherwise",+ )+ args = p.parse_args()+ if args.num_samples is not None and args.num_samples <= 0:+ args.num_samples = None # <= 0 means "all", not python slice semantics+ return args+++def ss_to_lato_voxels(occupancy: torch.Tensor) -> torch.Tensor:+ """(B, 1, R, R, R) TRELLIS occupancy -> sorted (N, 4) int [batch, x, y, z].++ TRELLIS grids are Z-up while LATO.2 meshes are Y-up (glTF), so voxels are+ rotated by (x, y, z) -> (x, z, -y).+ """+ res = occupancy.shape[-1]+ c = torch.argwhere(occupancy[:, 0]) # (N, 4): batch, x, y, z+ c = torch.stack([c[:, 0], c[:, 1], c[:, 3], res - 1 - c[:, 2]], dim=1)+ order = torch.argsort(((c[:, 0] * res + c[:, 1]) * res + c[:, 2]) * res + c[:, 3])+ return c[order].int()+++def main():+ logging.info("Image end-to-end inference starting...")++ args = parse_args()+ device = torch.device("cuda")+ torch.manual_seed(args.seed)+ np.random.seed(args.seed)+ os.makedirs(args.out_dir, exist_ok=True)++ # stage 0: sparse structure generation (TRELLIS)+ ss_flow = load_trellis_model(SS_FLOW_NAME, args.trellis_dir, device)+ ss_decoder = load_trellis_model(SS_DECODER_NAME, args.trellis_dir, device)+ # stage 1: vertex generation+ vflow, vflow_cfg = load_latov2_model(VertexSLatFlowModel, args.vflow_ckpt, device)+ vvae, vvae_cfg = load_latov2_model(VertexVAE, args.vvae_ckpt, device)+ offset_head, _ = load_latov2_model(OffsetHead, args.offset_head_ckpt, device)+ # stage 2: topology generation+ tflow, tflow_cfg = load_latov2_model(TopologySiTFlow, args.tflow_ckpt, device)+ tvae, _ = load_latov2_model(TopologyVAE, args.tvae_ckpt, device)+ voxel_encoder, venc_cfg = load_latov2_model(+ VoxelFieldConditioner, args.voxel_encoder_ckpt, device+ )++ res = vvae_cfg["resolution"]+ min_res = vvae_cfg["min_resolution"]+ latent_dim = vflow_cfg["latent_dim"]+ density_max = vflow_cfg["max_vertex_num"]+ img_res = vflow_cfg["image_resolution"]+ z_dim = int(tflow_cfg["args"]["z_dim"])+ num_discrete = int(tflow_cfg["args"]["num_discrete"])+ max_vertices = int(tflow_cfg["args"]["max_vertices"])+ latent_scale = float(tflow_cfg["latent_scale"])+ voxel_res = int(venc_cfg["resolution"])+ if num_discrete != res:+ raise ValueError(+ f"T-Flow num_discrete={num_discrete} != V-VAE resolution={res}; "+ "the generated vertex voxels would be in the wrong coordinate space."+ )+ if voxel_res != min_res:+ raise ValueError(+ f"voxel encoder resolution={voxel_res} != V-VAE min_resolution={min_res}; "+ "both stages must share the same active-voxel conditioning grid."+ )+ if (vflow_cfg["dino_version"], img_res) != (SS_COND_MODEL, SS_COND_RESOLUTION):+ raise ValueError(+ f"V-Flow is conditioned on {vflow_cfg['dino_version']}@{img_res} but the "+ f"TRELLIS SS-Flow needs {SS_COND_MODEL}@{SS_COND_RESOLUTION}; the two "+ "stages can no longer share one conditioning image."+ )++ dino = (+ DinoV2Encoder(+ model_name=vflow_cfg["dino_version"],+ hub_dir=args.dino_hub_dir,+ img_res=img_res,+ )+ .to(device)+ .eval()+ )+ logging.info(f"loaded {vflow_cfg['dino_version']} from {args.dino_hub_dir}")+ remove_background = BackgroundRemover(args.rembg_dir, device)+ logging.info(f"loaded background remover from {remove_background.model_dir}")+ ss_sampler = SSFlowEulerSampler()+ vertex_sampler = VertFlowEulerCfgSampler()+ topo_sampler = TopoFlowEulerSampler()++ files = sorted(+ f+ for f in os.listdir(args.image_dir)+ if os.path.splitext(f)[1].lower() in IMAGE_EXTENSIONS+ )+ if args.num_samples is not None:+ files = files[: args.num_samples]+ if not files:+ raise ValueError(f"no image files ({IMAGE_EXTENSIONS}) under {args.image_dir}")+ dupes = sorted(+ s for s, c in Counter(os.path.splitext(f)[0] for f in files).items() if c > 1+ )+ if dupes:+ logging.warning(+ f"WARNING: {len(dupes)} duplicate image basename(s) — later samples will overwrite earlier outputs."+ )+ logging.info(+ f"{len(files)} images from {args.image_dir} "+ f"(ss_steps={args.ss_steps}, ss_cfg={args.ss_cfg_strength}, "+ f"vflow_steps={args.vflow_steps}, cfg={args.cfg_strength}, "+ f"vert_num={args.vert_num}, density_max={density_max}, "+ f"tflow_steps={args.tflow_steps}, seed={args.seed}) -> {args.out_dir}"+ )++ n_ok = n_no_topo = n_fail = 0+ t_start = time.time()+ qbar = tqdm.tqdm(+ range(0, len(files), args.batch_size),+ desc="inference",+ unit="batch",+ dynamic_ncols=True,+ )+ for start in qbar:+ names, images = [], []+ for f in files[start : start + args.batch_size]:+ name = os.path.splitext(f)[0]+ try:+ rgba = load_rgba(os.path.join(args.image_dir, f), remove_background)+ images.append(crop_foreground(rgba, args.crop_padding, img_res))+ names.append(name)+ except Exception as e:+ n_fail += 1+ logging.error(f"{name}: FAILED during preprocessing: {e}")+ if not names:+ continue++ # ---- stage 0: SS-Flow on the image -> SS decoder -> 64^3 active voxels ----+ with torch.no_grad():+ cond = dino(np.stack(images)).float()+ neg_cond = torch.zeros_like(cond)+ ss_res = ss_flow.resolution+ z_ss = ss_sampler.sample(+ model=ss_flow,+ noise=torch.randn(+ len(names), ss_flow.in_channels, ss_res, ss_res, ss_res, device=device+ ),+ cond=cond,+ neg_cond=neg_cond,+ steps=args.ss_steps,+ cfg_strength=args.ss_cfg_strength,+ cfg_interval=args.ss_cfg_interval,+ rescale_t=args.ss_rescale_t,+ )+ occupancy = ss_decoder(z_ss) > 0 # (B, 1, R, R, R)+ if occupancy.shape[-1] != min_res:+ raise ValueError(+ f"SS decoder resolution={occupancy.shape[-1]} != V-VAE "+ f"min_resolution={min_res}; V-Flow expects {min_res}^3 active voxels."+ )+ coords = ss_to_lato_voxels(occupancy).cpu()+ voxels = [coords[coords[:, 0] == b, 1:] for b in range(len(names))]+ keep = [b for b, v in enumerate(voxels) if v.shape[0] > 0]+ for b in sorted(set(range(len(names))) - set(keep)):+ n_fail += 1+ logging.error(f"{names[b]}: empty sparse structure; skipping.")+ if not keep:+ continue+ names = [names[b] for b in keep]+ images = [images[b] for b in keep]+ voxels = [voxels[b] for b in keep]+ cond, neg_cond = cond[keep], neg_cond[keep]+ min_active = torch.cat(+ [+ torch.cat(+ [torch.full((v.shape[0], 1), i, dtype=torch.int32), v], dim=1+ )+ for i, v in enumerate(voxels)+ ],+ dim=0,+ )+ for name, image, vox in zip(names, images, voxels):+ Image.fromarray(image).save(os.path.join(args.out_dir, f"{name}_cond.png"))+ trimesh.PointCloud(+ (vox.numpy().astype(np.float64) + 0.5) / min_res - 0.5+ ).export(os.path.join(args.out_dir, f"{name}_ss.ply"))++ # ---- stage 1: V-Flow on the 64^3 active voxels -> V-VAE vertex decode ----+ density = torch.full(+ (len(names),),+ float(args.vert_num) / density_max * 1000.0,+ dtype=torch.float32,+ device=device,+ )+ with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16):+ min_active_coords = min_active.to(device)+ noise = SparseTensor(+ coords=min_active_coords.int(),+ feats=torch.randn(+ min_active_coords.shape[0], latent_dim, device=device+ ),+ )+ z_pred = vertex_sampler.sample(+ model=vflow,+ noise=noise,+ cond=cond,+ neg_cond=neg_cond,+ steps=args.vflow_steps,+ cfg_strength=args.cfg_strength,+ rescale_t=args.rescale_t,+ density=density,+ )+ pred_coords, pred_offsets = decode_vertices(+ vvae, offset_head, z_pred, args.inference_threshold+ )++ keep_idx, verts_list, offsets_list = [], [], []+ for b, name in enumerate(names):+ pred_sel = pred_coords[:, 0] == b+ vert_int = pred_coords[pred_sel, 1:].long()+ vert_off = pred_offsets[pred_sel]+ export_vertex(+ args.out_dir,+ name,+ type_name="pred",+ vert_int=vert_int.numpy(),+ vert_offsets=vert_off.numpy(),+ resolution=res,+ )+ num_pred = int(vert_int.shape[0])+ if num_pred < 3:+ n_no_topo += 1+ logging.warning(+ f"{name}: only {num_pred} generated vertices; skipping topology."+ )+ elif num_pred > max_vertices:+ n_no_topo += 1+ logging.warning(+ f"{name}: {num_pred} generated vertices exceed T-Flow "+ f"max_vertices={max_vertices}; skipping topology."+ )+ else:+ keep_idx.append(b)+ verts_list.append(vert_int)+ offsets_list.append(vert_off)+ if not keep_idx:+ continue++ # ---- stage 2: T-Flow on the generated vertices -> T-VAE edge decode ----+ with torch.no_grad():+ verts, mask, lengths = pad_verts(verts_list, device)+ voxel_list = [voxels[b].long() for b in keep_idx]+ field = build_voxel_fields(voxel_list, voxel_res, device) # (B', R, R, R)+ cond_vox = voxel_encoder(field) # (B', R'^3, cond_in_dim)++ z0 = torch.randn(verts.shape[0], verts.shape[1], z_dim, device=device)+ z_flow = topo_sampler.sample(+ model=tflow,+ noise=z0,+ verts=verts,+ mask=mask,+ cond=cond_vox,+ steps=args.tflow_steps,+ )+ z = z_flow.float() / latent_scale++ with torch.autocast("cuda", dtype=torch.bfloat16):+ edges_list = tvae.decode(+ z,+ verts=verts,+ verts_mask=mask,+ chunk_size=args.chunk_size,+ threshold=args.edge_threshold,+ )++ for k, b in enumerate(keep_idx):+ name = names[b]+ faces = edges_to_faces(+ edges_list[k],+ lengths[k],+ verts_list[k].numpy(),+ fill_open_rings=args.fill_open_rings,+ max_ring_size=args.max_ring_size,+ )+ if faces.shape[0] == 0:+ n_no_topo += 1+ logging.warning(+ f"{name}: no faces decoded; the _pred PLYs are the only outputs."+ )+ continue+ export_mesh(+ args.out_dir,+ name,+ vert_int=verts_list[k].numpy(),+ vert_offsets=offsets_list[k].numpy(),+ faces=faces,+ resolution=res,+ )+ n_ok += 1++ logging.info(+ f"done: {n_ok} ok, {n_no_topo} without topology, {n_fail} failed "+ f"in {time.time() - t_start:.0f}s -> {args.out_dir}"+ )+++if __name__ == "__main__":+ main()diff --git a/utils/export.py b/utils/export.pyindex 1441d4f..6c208f7 100644--- a/utils/export.py+++ b/utils/export.py@@ -17,3 +17,19 @@ def export_vertex(out_dir, base_name, type_name, vert_int, vert_offsets, resoluttrimesh.PointCloud(vert_int).export(os.path.join(out_dir, f"{base_name}_{type_name}_coords.ply"))+++def export_mesh(out_dir, base_name, vert_int, vert_offsets, faces, resolution):+ """OBJ pair matching export_vertex's PLY conventions (offset verts / int coords)."""+ res = float(resolution)+ vert_with_offset = (+ vert_int.astype(np.float64) / res+ - 0.5+ + vert_offsets.astype(np.float64) / (res * 2.0)+ )+ trimesh.Trimesh(vertices=vert_with_offset, faces=faces).export(+ os.path.join(out_dir, f"{base_name}_pred.obj")+ )+ trimesh.Trimesh(vertices=vert_int.astype(np.float64), faces=faces).export(+ os.path.join(out_dir, f"{base_name}_pred_coords.obj")+ )diff --git a/utils/image.py b/utils/image.pynew file mode 100644index 0000000..83c4916--- /dev/null+++ b/utils/image.py@@ -0,0 +1,51 @@+import numpy as np+from PIL import Image++IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}+++def load_rgba(path: str, remove_background) -> Image.Image:+ """Open an image and matte it with ``remove_background`` (RGB -> RGBA).++ Any transparency the file already has is flattened onto white first, so every+ input takes the same path; the image is limited to 1024 px on its longer side+ as in TRELLIS' preprocess_image.+ """+ image = Image.open(path)+ if image.mode != "RGB":+ rgba = image.convert("RGBA")+ image = Image.new("RGB", rgba.size, (255, 255, 255))+ image.paste(rgba, (0, 0), rgba)+ scale = min(1.0, 1024 / max(image.size))+ if scale < 1:+ image = image.resize(+ (int(image.width * scale), int(image.height * scale)),+ Image.Resampling.LANCZOS,+ )+ return remove_background(image)+++def crop_foreground(+ rgba: Image.Image, padding: float = 1.2, size: int = 518+) -> np.ndarray:+ """Square-crop an RGBA image around its foreground and composite it on black.++ This is TRELLIS' preprocess_image and also the framing of the LATO.2+ conditioning renders (WhiteModelRenderer crop_to_object): the crop side is+ the larger side of the alpha > 0.8 bounding box times ``padding``, resized to+ ``size``. Returns a uint8 (size, size, 3) array.+ """+ alpha = np.array(rgba)[:, :, 3]+ ys, xs = np.nonzero(alpha > 0.8 * 255)+ if xs.size == 0:+ raise ValueError("no foreground found (alpha > 0.8)")+ x0, y0, x1, y1 = xs.min(), ys.min(), xs.max(), ys.max()+ cx, cy = (x0 + x1) / 2, (y0 + y1) / 2+ side = int(max(x1 - x0, y1 - y0) * padding)+ if side < 2:+ raise ValueError("foreground is too small to crop")+ box = (cx - side // 2, cy - side // 2, cx + side // 2, cy + side // 2)+ out = rgba.crop(box).resize((size, size), Image.Resampling.LANCZOS)+ out = np.array(out).astype(np.float32) / 255+ out = out[:, :, :3] * out[:, :, 3:4]+ return (out * 255).astype(np.uint8)