Skip to content

SUPRA-Tex: 3D Generation with Super-Aligned Texture

Add local Gradio app and enable depth pre-filter by default

chensjtu5e40ab4a4a84
diff --git a/README.md b/README.md
index 8cf0c65..3b3c3e3 100644
--- a/README.md
+++ b/README.md
@@ -52,6 +52,7 @@ Learn more on the [project page](https://supra-3d.github.io/supratex/), or try t
## Release Notes
+- 🛡️ **[2026-10-29]** Added a default-on depth pre-filter for single-view image-to-3D, improving robustness to texture leakage near occlusion boundaries. See the [comparison and usage](docs/texturing.md#depth-pre-filter).
- 🔥 **[2026-10-19]** Inference code released for [image-to-3D](docs/end_to_end.md) and [mesh texturing](docs/texturing.md), along with a [training overview](docs/train.md).
- 🎨 **[2026-10-18]** The [SUPRA-Tex Studio](https://supra-3d.github.io/supratex/studio/studio.html) is open for a tour.
- 📄 **[2026-10-16]** [Project page](https://supra-3d.github.io/supratex/) and [paper](https://arxiv.org/abs/2610.22352) released.
@@ -137,6 +138,19 @@ the RMBG-2 or BiRefNet model from step 1; replace `--input` with your own image.
The output is a GLB with base color, metallic, and roughness textures. A sibling
work directory keeps intermediate files and a `run.json` receipt.
+**Local web app.** After installing the runtime and preparing the models above,
+start the Gradio interface on a single GPU:
+
+```bash
+pip install -e '.[app]'
+python app.py
+```
+
+Upload an RGB/RGBA image, choose a seed, then preview and download the GLB.
+Low-memory mode and the depth pre-filter are enabled by default; texture
+refinement is optional. RGB inputs need RMBG-2 or BiRefNet from step 1.
+See the [local web app guide](docs/app.md) for settings and remote access.
+
**Texture an existing mesh.** Given a mesh, its camera, a foreground image, and
reference-view material maps, complete the PBR textures directly. The repository
bundles the project-page pitcher plant mesh with its inputs in
@@ -155,6 +169,18 @@ for the input format.
The defaults suit most inputs. When a result falls short, these options help;
for run time, see [Inference Speed](#inference-speed).
+- **Reduce texture leakage.** The depth pre-filter is enabled by default for
+ single-view image-to-3D. It rejects unreliable material observations near
+ occlusion boundaries before completion. In the eel-machine example below,
+ the yellow streak extending from the motor support onto the dark base is
+ removed while the brass motor retains its color. Use `--no-filter` to disable
+ it; see [details and its relation to refinement](docs/texturing.md#depth-pre-filter).
+
+ ![Depth pre-filter comparison: filter off on the left, filter on on the right, with matching close-ups of the yellow texture leakage beneath the motor.](assets/docs/depth_prefilter_eel.png)
+
+ Same input geometry, camera, reference materials, and seed 42; both results
+ are shown before `--refine`. The close-ups highlight the motor/base boundary.
+
- **Refine fine detail.** For very small, intricate text and textures, add
`--refine`. After export, it further refines the visible texture and aligns it
with the input image. Refinement adds about two minutes on an RTX 3090, so it is
@@ -226,6 +252,7 @@ staged commands.
| Guide | Contents |
| --- | --- |
| [Quick start](docs/quickstart.md) | Installation, model preparation, and the first run in detail |
+| [Local web app](docs/app.md) | Gradio interface, single-GPU settings, and remote access |
| [Method overview](docs/method.md) | Pipeline stages and where each is implemented |
| [Training overview](docs/train.md) | Data preparation and training workflow |
| [End-to-end inference](docs/end_to_end.md) | All `infer.py` options |
diff --git a/README_zh-CN.md b/README_zh-CN.md
index 1055550..2c51fac 100644
--- a/README_zh-CN.md
+++ b/README_zh-CN.md
@@ -47,6 +47,7 @@ https://github.com/user-attachments/assets/ecc9e9ec-e91f-4eba-927d-86322796459a
## 更新日志
+- 🛡️ **[2026-10-29]** 加入默认启用的深度预过滤,减少遮挡边界附近的纹理串色,提升单视角生成的鲁棒性。查看[效果对比与用法](docs/texturing.md#depth-pre-filter)。
- 🔥 **[2026-10-19]** 发布推理代码,支持[图像生成 3D](docs/end_to_end.md)和[网格纹理生成](docs/texturing.md),并公开[训练流程概述](docs/train.md)。
- 🎨 **[2026-10-18]** [SUPRA-Tex 工作室](https://supra-3d.github.io/supratex/studio/studio.html)开放参观。
- 📄 **[2026-10-16]** 发布[项目主页](https://supra-3d.github.io/supratex/)和[论文](https://arxiv.org/abs/2610.22352)。
@@ -120,6 +121,17 @@ python scripts/run_example.py --input assets/metalwork_candle_jar.png \
RMBG-2 或 BiRefNet。换成你自己的图像,只需修改 `--input`。
输出是一个包含基础色、金属度和粗糙度贴图的 GLB,旁边的工作目录会保留中间文件和运行记录 `run.json`。
+**本地网页界面。** 按上面的步骤安装环境、准备模型后,可在单张 GPU 上启动 Gradio 界面:
+
+```bash
+pip install -e '.[app]'
+python app.py
+```
+
+上传 RGB/RGBA 图像、设置 seed,即可预览并下载 GLB。默认开启低显存模式和深度预过滤,
+纹理细化可按需勾选。RGB 输入需要第 1 步中的 RMBG-2 或 BiRefNet。
+启动参数和远程访问方式见[本地网页界面指南](docs/app.md)。
+
**为已有网格生成纹理。** 如果已经有网格,再提供对应的相机、前景图像和参考视角的材质图,就能直接补全 PBR 纹理。
仓库在 [`assets/examples/pitcher_plant`](assets/examples/pitcher_plant) 中附带了项目主页上的猪笼草网格及其输入,
这也是 `texturing.py` 的默认输入:
@@ -134,6 +146,14 @@ python texturing.py --pipeline supra3d/supra-tex --output outputs/pitcher_plant_
大多数输入用默认设置即可。如果效果不够理想,可以试试下面的方法;想提升运行速度,请看[推理速度](#推理速度)。
+- **减少纹理串色**:单视角图像生成 3D 默认启用深度预过滤,在补全前剔除遮挡边界附近不可靠的材质观测。
+ 下方鳗鱼机器案例中,从电机支脚延伸到深色底座的黄色拖尾被消除,电机本身的黄铜色仍然保留。
+ 加 `--no-filter` 可关闭;具体用法及其与 refine 的关系见[深度预过滤](docs/texturing.md#depth-pre-filter)。
+
+ ![深度预过滤对比:左侧关闭,右侧开启;下方放大图展示电机下方的黄色纹理串色变化。](assets/docs/depth_prefilter_eel.png)
+
+ 两组使用相同的输入几何、相机、参考材质和 seed 42,均为 `--refine` 之前的结果;局部放大展示电机与底座的交界处。
+
- **细化纹理**:遇到非常细小、精密的文字和纹理时,可以加上 `--refine`。它会在导出后进一步细化可见区域的纹理,
并与输入图像对齐。由于会多花一些时间(RTX 3090 上约两分钟),默认不开启。
下面的例子里,工业隔离开关的接线表在一张标签上挤满了规格表、电路符号和细小的警示文字:
@@ -182,6 +202,7 @@ python texturing.py --pipeline supra3d/supra-tex --output outputs/pitcher_plant_
| 指南 | 内容 |
| --- | --- |
| [快速开始](docs/quickstart.md) | 安装、准备模型和首次运行的详细步骤 |
+| [本地网页界面](docs/app.md) | Gradio 界面、单卡设置和远程访问 |
| [方法概述](docs/method.md) | 各个阶段的原理及对应代码 |
| [训练流程概述](docs/train.md) | 数据准备与训练流程 |
| [端到端推理](docs/end_to_end.md) | `infer.py` 的全部选项 |
diff --git a/app.py b/app.py
new file mode 100644
index 0000000..caddb50
--- /dev/null
+++ b/app.py
@@ -0,0 +1,221 @@
+#!/usr/bin/env python3
+"""Serve SUPRA-Tex locally with Gradio and the prepared-model inference pipeline."""
+from __future__ import annotations
+
+import argparse
+import atexit
+from contextlib import closing
+import json
+import math
+import os
+from pathlib import Path
+import signal
+import subprocess
+import tempfile
+import threading
+import time
+from types import SimpleNamespace
+
+from scripts.run_example import ROOT, build_command, read_config
+
+
+class LocalRunner:
+ """One GPU job at a time, with a fresh subprocess and directory per request."""
+
+ def __init__(self, config: Path, output_dir: Path, *, low_vram: bool = True):
+ if not config.is_file():
+ raise FileNotFoundError(f"Prepared models are missing: {config}. Run scripts/prepare_models.py first.")
+ self.config = read_config(config)
+ self.output_dir = output_dir.expanduser().resolve()
+ self.output_dir.mkdir(parents=True, exist_ok=True)
+ self.low_vram = low_vram
+ self._lock = threading.Lock()
+ self._process: subprocess.Popen | None = None
+
+ def close(self) -> None:
+ """Stop only this app's inference process and its frontend workers."""
+ process = self._process
+ if process is None or process.poll() is not None:
+ return
+ try:
+ if os.name == "posix":
+ os.killpg(process.pid, signal.SIGTERM)
+ else:
+ process.terminate()
+ process.wait(timeout=10)
+ except ProcessLookupError:
+ pass
+ except subprocess.TimeoutExpired:
+ if os.name == "posix":
+ os.killpg(process.pid, signal.SIGKILL)
+ else:
+ process.kill()
+ process.wait()
+
+ @staticmethod
+ def _receipt(work: Path) -> dict:
+ path = work / "run.json"
+ return json.loads(path.read_text()) if path.is_file() else {}
+
+ def generate(self, image_path: str, seed: int, use_filter: bool = True, refine: bool = False):
+ """Yield progress and completed files; closing the iterator cancels the job."""
+ if not image_path or not Path(image_path).is_file():
+ raise ValueError("Upload a reference image first.")
+ if isinstance(seed, bool) or not isinstance(seed, (int, float)) or not math.isfinite(seed) or int(seed) != seed or not 0 <= seed <= 2**32 - 1:
+ raise ValueError("Seed must be an integer between 0 and 4294967295.")
+ # Gradio can release its queue slot before a cancelled iterator has
+ # finished closing. Wait for our GPU owner instead of dropping that job.
+ while not self._lock.acquire(timeout=.5):
+ yield {"status": "Waiting for the previous task to finish…"}
+ try:
+ from PIL import Image, ImageOps
+
+ job = Path(tempfile.mkdtemp(prefix="run-", dir=self.output_dir))
+ source, output, work, log = job / "input.png", job / "mesh.glb", job / "work", job / "inference.log"
+ # Own a copy of the upload; Gradio can expire its temporary file.
+ with Image.open(image_path) as uploaded:
+ oriented = ImageOps.exif_transpose(uploaded)
+ mode = "RGBA" if "A" in oriented.getbands() or "transparency" in oriented.info else "RGB"
+ oriented.convert(mode).save(source)
+ args = SimpleNamespace(input=source, output=output, attention=None,
+ low_vram=self.low_vram, use_input_alpha=False)
+ extra = ["--work-dir", str(work), "--seed", str(int(seed)),
+ "--texture-size", "4096", "--texture-format", "png"]
+ if not use_filter:
+ extra.append("--no-filter")
+ if refine:
+ extra.append("--refine")
+ command, environment = build_command(args, extra, self.config)
+ request = {"seed": int(seed), "image_depth_filter": bool(use_filter),
+ "refine": bool(refine), "low_vram": self.low_vram}
+ (job / "request.json").write_text(json.dumps(request, indent=2) + "\n")
+ started = time.monotonic()
+ yield {"status": "Preparing your image…"}
+ with log.open("x", encoding="utf-8") as stream:
+ self._process = subprocess.Popen(command, cwd=ROOT, env=environment, stdout=stream,
+ stderr=subprocess.STDOUT, start_new_session=os.name == "posix")
+ while True:
+ try:
+ returncode = self._process.wait(timeout=2)
+ break
+ except subprocess.TimeoutExpired:
+ stage = self._receipt(work).get("stage")
+ phase = "Generating the PBR model" if stage == "completion" else "Preparing image, geometry and materials"
+ elapsed = int(time.monotonic() - started)
+ yield {"status": f"{phase}… {elapsed // 60}m {elapsed % 60:02d}s"}
+ receipt = self._receipt(work)
+ if returncode or receipt.get("status") != "complete" or not output.is_file():
+ yield {"status": "Generation failed. See the run log for details.", "log": str(log)}
+ raise RuntimeError(receipt.get("error") or f"Inference failed (exit code {returncode}). See {log}")
+ with output.open("rb") as mesh:
+ if mesh.read(4) != b"glTF":
+ raise RuntimeError(f"Inference did not produce a GLB: {output}")
+ elapsed = int(time.monotonic() - started)
+ yield {"status": f"Ready · seed {int(seed)} · {elapsed // 60}m {elapsed % 60:02d}s",
+ "model": str(output), "log": str(log),
+ "foreground": str(work / "input/condition_rgba.png"),
+ "albedo": str(work / "input/albedo.png")}
+ finally:
+ self.close()
+ self._process = None
+ self._lock.release()
+
+
+def build_ui(runner: LocalRunner, *, use_filter: bool = True):
+ import gradio as gr
+
+ with gr.Blocks(title="SUPRA-Tex · Local", analytics_enabled=False) as demo:
+ gr.Markdown("# SUPRA-Tex\n3D Generation with Super-Aligned Texture")
+ with gr.Row(equal_height=False):
+ with gr.Column(scale=1, min_width=300):
+ image = gr.Image(label="Reference image", type="filepath", image_mode="RGBA", format="png", height=400)
+ with gr.Accordion("Generation settings", open=True):
+ seed = gr.Number(value=42, label="Seed", precision=0, minimum=0, maximum=2**32 - 1)
+ depth_filter = gr.Checkbox(value=use_filter, label="Depth pre-filter",
+ info="Reduce texture bleed near depth boundaries.")
+ refine = gr.Checkbox(value=False, label="Refine visible textures",
+ info="Sharpen reference-view details after generation; takes extra time.")
+ with gr.Row():
+ generate = gr.Button("Generate 3D", variant="primary")
+ stop = gr.Button("Stop")
+ examples = [str(ROOT / "assets" / name) for name in
+ ("spiny_whelk_shell.png", "metalwork_candle_jar.png", "cinema_signage.png")
+ if (ROOT / "assets" / name).is_file()]
+ if examples:
+ gr.Examples(examples=examples, inputs=image, label="Examples")
+ with gr.Column(scale=2, min_width=400):
+ model = gr.Model3D(label="PBR model", interactive=False, height=540,
+ clear_color=(.08, .08, .08, 1))
+ download = gr.DownloadButton("Download GLB", value=None, interactive=False)
+ status = gr.Markdown("Upload an image to begin. Jobs run one at a time.")
+ with gr.Accordion("Reference materials and run log", open=False):
+ with gr.Row():
+ foreground = gr.Image(label="Foreground", interactive=False)
+ albedo = gr.Image(label="Albedo", interactive=False)
+ log = gr.File(label="Run log", interactive=False)
+
+ def generate_mesh(image_path, seed_value, filter_enabled, refine_enabled):
+ try:
+ with closing(runner.generate(image_path, seed_value, filter_enabled, refine_enabled)) as updates:
+ for update in updates:
+ result = update.get("model")
+ yield (result, gr.update(value=result, interactive=result is not None), update["status"],
+ update.get("foreground"), update.get("albedo"), update.get("log"))
+ except (OSError, ValueError, RuntimeError) as error:
+ raise gr.Error(str(error)) from error
+
+ event = generate.click(generate_mesh, [image, seed, depth_filter, refine],
+ [model, download, status, foreground, albedo, log],
+ api_name="generate", concurrency_limit=1, concurrency_id="gpu", trigger_mode="once")
+ stop.click(lambda: "Stopped.", outputs=status, cancels=[event], queue=False, api_visibility="private")
+ demo.queue(default_concurrency_limit=1, max_size=8)
+ return demo
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
+ parser.add_argument("--config", type=Path, default=ROOT / "ckpts/ready/models.json", help="prepared models.json")
+ parser.add_argument("--host", default="127.0.0.1", help="bind address; use 0.0.0.0 for LAN access")
+ parser.add_argument("--port", type=int, default=7860)
+ parser.add_argument("--output-dir", type=Path, default=ROOT / "outputs/gradio", help="persistent per-run files")
+ parser.add_argument("--low-vram", action=argparse.BooleanOptionalAction, default=True,
+ help="CPU offload for a single 24 GB GPU (default: on)")
+ parser.add_argument("--no-filter", "--no-image-depth", action="store_true",
+ help="start with the depth pre-filter unchecked (default: enabled)")
+ args = parser.parse_args(argv)
+ if not 1 <= args.port <= 65535:
+ parser.error("--port must be between 1 and 65535")
+ return args
+
+
+def main() -> None:
+ args = parse_args()
+ try:
+ import gradio as gr
+ except ImportError as error:
+ raise SystemExit('Install the web UI first: pip install -e ".[app]"') from error
+ try:
+ runner = LocalRunner(args.config.expanduser(), args.output_dir, low_vram=args.low_vram)
+ except (OSError, ValueError) as error:
+ raise SystemExit(str(error)) from error
+ atexit.register(runner.close)
+ def shutdown(signum, _frame):
+ runner.close()
+ raise SystemExit(128 + signum)
+ signal.signal(signal.SIGTERM, shutdown)
+ demo = build_ui(runner, use_filter=not args.no_filter)
+ # Keep the Space's dark/gold presentation without its cloud account services.
+ theme = gr.themes.Base(font=["Arial", "sans-serif"]).set(
+ body_background_fill="#101010", body_background_fill_dark="#101010",
+ body_text_color="#f4f0e7", body_text_color_dark="#f4f0e7",
+ block_background_fill="#191919", block_background_fill_dark="#191919",
+ input_background_fill="#121212", input_background_fill_dark="#121212",
+ button_primary_background_fill="#f2cd70", button_primary_background_fill_dark="#f2cd70",
+ button_primary_text_color="#19150e", button_primary_text_color_dark="#19150e")
+ demo.launch(server_name=args.host, server_port=args.port, share=False, ssr_mode=False,
+ theme=theme, css=".gradio-container {max-width: 1200px !important; margin: auto;}",
+ allowed_paths=[str(runner.output_dir), str(ROOT / "assets")])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/assets/docs/depth_prefilter_eel.png b/assets/docs/depth_prefilter_eel.png
new file mode 100644
index 0000000..15fcdc2
Binary files /dev/null and b/assets/docs/depth_prefilter_eel.png differ
diff --git a/docs/app.md b/docs/app.md
new file mode 100644
index 0000000..8b74b0f
--- /dev/null
+++ b/docs/app.md
@@ -0,0 +1,87 @@
+# Local web app
+
+`app.py` runs the image-to-3D pipeline through a local Gradio interface on one
+NVIDIA GPU. It uses the same prepared models as `scripts/run_example.py`.
+
+## Setup and launch
+
+Complete [installation](installation.md) and [model preparation](quickstart.md)
+first, then run these commands from the repository root in the inference
+environment:
+
+```bash
+pip install -e '.[app]'
+python app.py
+```
+
+The `app` extra installs Gradio 6.10.0. Open
+[http://127.0.0.1:7860](http://127.0.0.1:7860) in your browser. The default model
+configuration is `ckpts/ready/models.json`.
+
+Upload an RGB image or an RGBA image with foreground alpha. Opaque RGB inputs
+need RMBG-2 or BiRefNet included in the prepared configuration; see
+[foreground model preparation](quickstart.md). Choose a seed (default `42`),
+then generate, preview the GLB, and download it.
+
+The **Depth pre-filter** checkbox is enabled by default. It applies the image/geometry
+depth pre-filter before material completion. **Refine** is optional and off by
+default; enabling it adds reference-view texture refinement after completion.
+See [the filter description](frontend.md) and [refinement](end_to_end.md) for
+details.
+
+The app processes one generation at a time. Low-memory mode is enabled by
+default for a single RTX 3090 with 24 GB VRAM. Each run creates a new directory
+under `outputs/gradio`; results stay on the machine running the app. The app
+does not automatically remove old run directories, so clean them up manually
+when they are no longer needed.
+
+## Launch options
+
+- `--config PATH`: use another prepared `models.json`.
+- `--host ADDRESS`: bind address; default `127.0.0.1`.
+- `--port PORT`: listening port; default `7860`.
+- `--output-dir PATH`: parent directory for new runs; default `outputs/gradio`.
+- `--no-filter`: start with the Depth pre-filter checkbox off.
+- `--no-low-vram`: disable the app's default low-memory mode.
+
+For example:
+
+```bash
+python app.py --config /path/to/models.json --port 7861 \
+ --output-dir /path/to/results
+```
+
+For command-line inference, both `infer.py` and `scripts/run_example.py` accept
+`--no-filter` to disable the depth pre-filter; `--no-image-depth` is an alias:
+
+```bash
+python scripts/run_example.py --input /path/to/image.png \
+ --output outputs/example.glb --no-filter
+```
+
+## Remote GPU access
+
+To use a remote GPU through SSH, start the app on that machine with its default
+loopback binding:
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python app.py
+```
+
+On your own computer, forward the port:
+
+```bash
+ssh -N -L 7860:127.0.0.1:7860 user@gpu-host
+```
+
+Open [http://127.0.0.1:7860](http://127.0.0.1:7860) on your own computer.
+`CUDA_VISIBLE_DEVICES=0` selects one physical GPU for the app.
+
+For direct access over a reachable network, bind the server to all interfaces:
+
+```bash
+CUDA_VISIBLE_DEVICES=0 python app.py --host 0.0.0.0 --port 7860
+```
+
+Then open `http://<gpu-host-address>:7860`. Model execution and output files
+remain on the GPU host.
diff --git a/docs/end_to_end.md b/docs/end_to_end.md
index 5015768..f8d93c4 100644
--- a/docs/end_to_end.md
+++ b/docs/end_to_end.md
@@ -63,6 +63,10 @@ overridden through this launcher. Use `infer.py` directly for those changes.
- `--gutter` adds one texel of base-color padding outside UV charts. It is
disabled by default and preserves covered texels, alpha, metallic/roughness,
geometry, and UVs.
+- The depth pre-filter is on by default for single-view runs. It rejects
+ unreliable observations near depth edges before completion to reduce texture
+ leakage. `--no-filter` (alias `--no-image-depth`) disables it. Dual-view runs
+ omit it automatically. See the [comparison and usage](texturing.md#depth-pre-filter).
- Floater removal is on by default: before completion, disconnected geometry
pieces that project mostly outside the image foreground are dropped, and a
`Floaters:` line reports the count. `--no-remove-floaters` keeps them.
diff --git a/docs/frontend.md b/docs/frontend.md
index fa2dced..986116c 100644
--- a/docs/frontend.md
+++ b/docs/frontend.md
@@ -44,12 +44,26 @@ For the same options on `infer.py`, use `--material-revision` instead of
`--revision` (which selects the completion model there).
Use a fresh output directory. The handoff contains `condition_rgba.png`,
`condition_rgb.png`, `camera.json`, `image_depth.npy`, `albedo.png`, and `mra.png`.
-`image_depth.npy` is the MoGe-2 camera-z depth on the condition pixel grid
-(NaN where invalid). Single-view completion uses it to exclude source pixels
-whose depth disagrees with the generated geometry near depth edges, and it skips
-this gate when the depth is missing or degenerate. Pass `--no-image-depth` to
-omit it; `--record-material-provenance` omits it because dual-view completion
-does not support the gate.
+`image_depth.npy` stores float32 MoGe-2 camera-z depth on the condition pixel grid,
+with NaN for invalid pixels. Its dimensions must match `condition_rgba.png`;
+completion resizes it to the 1024-square observation grid with nearest-neighbor
+sampling, preserving invalid pixels. Single-view completion uses it to exclude
+source pixels whose depth disagrees with the generated geometry near depth edges.
+The gate is skipped when depth is absent or a valid fit cannot be obtained;
+malformed depth files are rejected.
+
+The depth pre-filter is enabled by default for single-view `infer.py` and
+`python -m supratex.frontend.pipeline` runs. Pass `--no-filter` (alias
+`--no-image-depth`) to either command to disable it by omitting the depth file.
+`infer.py --dual-view` and frontend `--record-material-provenance` omit the file
+because dual-view completion does not support the pre-filter and rejects inputs
+containing `image_depth.npy`. The standalone camera command exports depth only
+when given `--depth-output`, as shown below.
+
+The `infer.py` work directory's `run.json` records `image_depth_filter.requested`,
+`enabled`, and `disabled_reason` (`user_disabled` or `dual_view_unsupported`).
+These fields describe whether the depth input is enabled for the run; a later
+degenerate fit can still skip the gate. An enabled run has a null disabled reason.
For an existing non-opaque foreground RGBA, omit `--with-rmbg` during preparation
and replace `--rmbg-model` with `--use-input-alpha` in the frontend command.
diff --git a/docs/texturing.md b/docs/texturing.md
index da23953..af46b2b 100644
--- a/docs/texturing.md
+++ b/docs/texturing.md
@@ -19,6 +19,10 @@ The input directory must contain:
- `albedo.png` and `mra.png`: RGB images at 1024 by 1024. MRA stores metallic,
roughness, and alpha in R, G, and B respectively.
+Optionally include `image_depth.npy`, a float32 MoGe-2 camera-z depth map aligned
+with `condition_rgba.png`, to enable the single-view [depth pre-filter](#depth-pre-filter).
+The [material frontend](frontend.md) produces it by default for single-view runs.
+
## Run
From the repository root after [installation](quickstart.md):
@@ -102,6 +106,50 @@ Optional `--gutter` adds one texel of base-color padding outside UV charts.
It is disabled by default and preserves covered texels, alpha, metallic/roughness,
geometry, and UVs. See the [image-to-3D guide](end_to_end.md) for export controls.
+## Depth pre-filter
+
+Image and generated geometry can disagree at occlusion boundaries. A material
+observation can then land on the wrong surface, carrying a foreground color into
+the completed texture behind it. Before material encoding, the depth pre-filter
+aligns the image depth with the geometry depth and rejects observations where
+they disagree near depth edges. It also checks the bilinear sampling footprint,
+so a retained sample cannot blend in pixels rejected by this depth gate.
+Completion fills the regions left without observations; the filter does not
+remove geometry.
+
+![Filter off and on for the eel machine, with matching close-ups of the motor/base boundary.](../assets/docs/depth_prefilter_eel.png)
+
+In this example, the yellow streak from the motor support onto the dark base
+disappears with the filter, while the brass motor retains its color. Both results
+use the same input geometry, camera, reference materials, and seed 42, and are
+shown **before texture refinement**. The filter removes 10,483 of 355,164 surface
+observations (2.95%). This is a qualitative example of local leakage reduction;
+the independently exported meshes can differ in triangulation and UV layout.
+
+The filter is **on by default** for single-view image-to-3D, including the local
+web app. After [model preparation](quickstart.md#2-prepare-the-models), use:
+
+```bash
+# Default: depth pre-filter enabled.
+python scripts/run_example.py --input path/to/image.png --output outputs/object.glb
+
+# Disable the depth pre-filter explicitly.
+python scripts/run_example.py --input path/to/image.png --output outputs/object_no_filter.glb --no-filter
+```
+
+`infer.py` and the standalone material frontend also accept `--no-filter`
+(`--no-image-depth` is an alias). For `texturing.py`, the filter is applied when
+the input directory contains `image_depth.npy`; omit that optional file to skip
+it. A controlled comparison should reuse the geometry, camera, and reference
+materials rather than regenerate them for each variant. The filter is skipped
+when a valid depth fit cannot be obtained, and is not supported for dual-view
+inputs. See [the frontend guide](frontend.md) for the depth format and run records.
+
+The pre-filter and `--refine` act at different stages: the filter improves the
+observations **before completion**, while refinement restores visible texture
+detail **after export**. They can be used together; refinement is optional and
+remains off by default.
+
## Texture refinement
`--refine` further refines the texture that the reference view sees and aligns
diff --git a/infer.py b/infer.py
index f79281f..0f2c6fb 100644
--- a/infer.py
+++ b/infer.py
@@ -112,6 +112,8 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser.add_argument("--moge-model", help="local MoGe-2 checkpoint/directory or HF repo ID")
parser.add_argument("--rmbg-model", help="local RMBG-2 directory or HF repo ID; required for RGB input")
parser.add_argument("--use-input-alpha", action="store_true", help="require and reuse foreground RGBA alpha")
+ parser.add_argument("--no-filter", "--no-image-depth", dest="no_filter", action="store_true",
+ help="disable the default single-view image/geometry depth pre-filter; dual-view does not use it")
parser.add_argument("--resolution-level", type=int, default=9, help="MoGe-2 resolution level")
parser.add_argument("--geometry-package", type=Path, help="native or paper geometry source checkout; see docs/geometry.md")
parser.add_argument("--geometry-model", help="local geometry weights directory or HF repo ID")
@@ -278,12 +280,18 @@ def run(args: argparse.Namespace) -> Path:
from supratex.inference import run_completion
work.mkdir(parents=True, exist_ok=True)
handoff = work / "input"
+ filter_requested = not getattr(args, "no_filter", False)
+ filter_enabled = filter_requested and not args.dual_view
+ filter_disabled_reason = ("user_disabled" if not filter_requested else
+ "dual_view_unsupported" if args.dual_view else None)
receipt = {"status": "running", "stage": "frontend", "input": str(image), "output": str(output),
"work_dir": str(work), "seed": args.seed, "gutter": args.gutter,
"material_backend": args.material_backend, "material_seed": 42,
"runtime": runtime,
"model_config": str(config), "checkpoint": str(checkpoint), "dual_view": args.dual_view,
- "refine": args.refine, "remove_floaters": args.remove_floaters}
+ "refine": args.refine, "remove_floaters": args.remove_floaters,
+ "image_depth_filter": {"requested": filter_requested, "enabled": filter_enabled,
+ "disabled_reason": filter_disabled_reason}}
def record() -> None:
temporary = work / ".run.json.tmp"
temporary.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8")
@@ -293,6 +301,7 @@ def run(args: argparse.Namespace) -> Path:
print(f"[1/2] Foreground, MoGe-2, geometry, material maps -> {handoff}", flush=True)
result = run_frontend(image, handoff, moge_model=args.moge_model, rmbg_model=args.rmbg_model,
use_input_alpha=args.use_input_alpha, resolution_level=args.resolution_level,
+ export_image_depth=filter_enabled,
geometry_package=args.geometry_package.expanduser().resolve(), geometry_model=args.geometry_model,
geometry_revision=args.geometry_revision, geometry_seed=args.seed,
geometry_initial_mesh_scale=args.geometry_initial_mesh_scale,
diff --git a/pyproject.toml b/pyproject.toml
index 1317ea2..cfa1f08 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -17,6 +17,7 @@ dependencies = [
[project.optional-dependencies]
frontend = ["transformers==4.57.3", "diffusers==0.37.1", "accelerate", "requests", "timm"]
+app = ["gradio==6.10.0"]
[tool.setuptools]
license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]
diff --git a/supratex/frontend/pipeline.py b/supratex/frontend/pipeline.py
index c6169c8..845538a 100644
--- a/supratex/frontend/pipeline.py
+++ b/supratex/frontend/pipeline.py
@@ -169,10 +169,9 @@ def run(input_image: Path, output: Path, *, moge_model: str | Path,
if estimator is not None:
estimator.close()
# Depth gating is single-view only; a dual-view front packet must omit it.
- export_image_depth = export_image_depth and not record_material_provenance
- depth_path = output / "image_depth.npy"
+ depth_path = output / "image_depth.npy" if export_image_depth and not record_material_provenance else None
camera = estimate(rgb, moge_model, moge_module, resolution_level, device,
- **({"depth_output": depth_path} if export_image_depth else {}))
+ depth_output=depth_path)
camera["foreground_source"] = foreground_source
camera_path = output / "camera.json"
camera_path.write_text(json.dumps(camera, indent=2) + "\n", encoding="utf-8")
@@ -226,7 +225,7 @@ def run(input_image: Path, output: Path, *, moge_model: str | Path,
result = {"condition_rgba": str(rgba), "condition_rgb": str(rgb), "camera": str(camera_path),
"albedo": str(final_albedo), "mra": str(final_mra), "foreground_source": foreground_source,
"material_backend": material_backend}
- if export_image_depth:
+ if depth_path is not None:
result["image_depth"] = str(depth_path)
if geometry_result:
result.update(geometry=str(geometry_path), geometry_receipt=geometry_result["receipt"])
@@ -267,8 +266,8 @@ def main() -> None:
parser.add_argument("--material-checkpoint-manifest", type=Path)
parser.add_argument("--key", default="input")
parser.add_argument("--record-material-provenance", action="store_true", help="write material bindings for optional dual-view inference")
- parser.add_argument("--no-image-depth", action="store_true",
- help="omit the optional image_depth.npy filtering input (implied by --record-material-provenance)")
+ parser.add_argument("--no-filter", "--no-image-depth", dest="no_image_depth", action="store_true",
+ help="disable the default depth pre-filter by omitting image_depth.npy (implied by --record-material-provenance)")
parser.add_argument("--device", default="cuda")
parser.add_argument("--attention", choices=("auto", "flash_attn_3", "flash_attn", "sdpa", "xformers"), default="auto")
parser.add_argument("--low-vram", action=argparse.BooleanOptionalAction, default=None,
diff --git a/supratex/inference/native_observation.py b/supratex/inference/native_observation.py
index 24a2faf..0753cbb 100644
--- a/supratex/inference/native_observation.py
+++ b/supratex/inference/native_observation.py
@@ -236,15 +236,16 @@ def _admitted_pixels(depth: np.ndarray, missed: np.ndarray, focal: tuple[float,
def pixel_first_occupied(camera: dict[str, Any], occupancy: np.ndarray, trusted: torch.Tensor, depth_edge_rtol: float = 0.04,
stats: dict | None = None, image_depth: np.ndarray | None = None,
- admitted_out: dict | None = None) -> torch.Tensor:
+ depth_gate_out: dict | None = None) -> torch.Tensor:
"""Map trusted pixels to first occupied cells, optionally excluding depth conflicts.
- ``admitted_out['pixels']`` is the complementary image-depth-conflict mask
- for reprojection, not the union of all observation admission rules.
+ With image depth, ``depth_gate_out['keep_mask']`` contains only the depth
+ gate's keep mask for material sampling and reprojection. Alpha and geometry
+ admission remain separate. Diagnostics are written to ``stats['image_depth']``.
"""
if "extrinsic" in camera:
return pixel_first_occupied_cv(camera, occupancy, trusted, depth_edge_rtol, stats=stats,
- image_depth=image_depth, admitted_out=admitted_out)
+ image_depth=image_depth, depth_gate_out=depth_gate_out)
if trusted.shape != (RESOLUTION, RESOLUTION):
raise ValueError("trusted alpha mask must be 1024 by 1024")
if "camera_angle_x" not in camera or "distance" not in camera:
@@ -270,7 +271,7 @@ def pixel_first_occupied(camera: dict[str, Any], occupancy: np.ndarray, trusted:
retained = hit_mask.copy()
retained[hit_mask] &= admitted[y[hit_mask], x[hit_mask]]
if image_depth is not None:
- mismatch = _image_depth_mask(camera, occupancy, image_depth, stats, admitted_out)
+ mismatch = _image_depth_mask(camera, occupancy, image_depth, stats, depth_gate_out)
rejected = retained & mismatch[y, x]
retained &= ~mismatch[y, x]
if stats is not None:
@@ -341,16 +342,15 @@ def first_hit_depth(camera: dict[str, Any], occupancy: np.ndarray) -> np.ndarray
def _image_depth_mask(camera: dict[str, Any], occupancy: np.ndarray, image_depth: np.ndarray,
- stats: dict | None, admitted_out: dict | None) -> np.ndarray:
+ stats: dict | None, depth_gate_out: dict | None) -> np.ndarray:
if np.asarray(image_depth).shape != (RESOLUTION, RESOLUTION):
raise ValueError("image depth must be an observation-resolution map")
diagnostic: dict[str, Any] = {}
mismatch = image_depth_disagreement(first_hit_depth(camera, occupancy), image_depth, stats=diagnostic)
if stats is not None:
stats["image_depth"] = diagnostic
- if admitted_out is not None:
- admitted_out["pixels"] = ~mismatch
- admitted_out["image_depth"] = diagnostic
+ if depth_gate_out is not None:
+ depth_gate_out["keep_mask"] = ~mismatch
return mismatch
@@ -368,7 +368,7 @@ def pixel_hits_cv(camera: dict[str, Any], occupancy: np.ndarray, mask: np.ndarra
def pixel_first_occupied_cv(camera: dict[str, Any], occupancy: np.ndarray, trusted: torch.Tensor,
depth_edge_rtol: float = .04, stats: dict | None = None,
- image_depth: np.ndarray | None = None, admitted_out: dict | None = None) -> torch.Tensor:
+ image_depth: np.ndarray | None = None, depth_gate_out: dict | None = None) -> torch.Tensor:
"""Apply the production first-hit admission rules to a full CV camera."""
if trusted.shape != (RESOLUTION, RESOLUTION) or trusted.dtype != torch.bool:
raise ValueError("trusted alpha must be a boolean observation-resolution image")
@@ -394,7 +394,7 @@ def pixel_first_occupied_cv(camera: dict[str, Any], occupancy: np.ndarray, trust
focal = (float(intrinsic[0, 0]) * RESOLUTION, float(intrinsic[1, 1]) * RESOLUTION)
retained = hits & _admitted_pixels(depth, missed, focal, depth_edge_rtol, stats=stats)[ys, xs]
if image_depth is not None:
- mismatch = _image_depth_mask(camera, occupancy, image_depth, stats, admitted_out)
+ mismatch = _image_depth_mask(camera, occupancy, image_depth, stats, depth_gate_out)
rejected = retained & mismatch[ys, xs]
retained &= ~mismatch[ys, xs]
if stats is not None:
diff --git a/supratex/inference/pipeline.py b/supratex/inference/pipeline.py
index 1ca1c7f..91befdb 100644
--- a/supratex/inference/pipeline.py
+++ b/supratex/inference/pipeline.py
@@ -302,7 +302,8 @@ def _source_footprint_safe(keep: Any, grid: Any, runtime: Mapping[str, Any], dev
return contribution <= 1e-6
-def _partial(surface: Any, shape: Any, case: dict[str, Any], external: Any, projection: Any, encoder: Any, normalization: Mapping[str, Any], runtime: Mapping[str, Any], device: str) -> Any:
+def _partial(surface: Any, shape: Any, case: Mapping[str, Any], external: Any, projection: Any, encoder: Any, normalization: Mapping[str, Any], runtime: Mapping[str, Any], device: str) -> tuple[Any, dict[str, Any]]:
+ """Encode observations and return the depth-gate handoff for front refine."""
torch, F, np, image, image_filter, sparse = runtime["torch"], runtime["F"], runtime["np"], runtime["Image"], runtime["ImageFilter"], runtime["sparse"]
coords = surface.coords[:, 1:].long(); points = (coords.float() + .5) / RESOLUTION - .5
camera = (torch.cat((points, torch.ones_like(points[:, :1])), dim=1) @ external.T)[:, :3]
@@ -316,12 +317,13 @@ def _partial(surface: Any, shape: Any, case: dict[str, Any], external: Any, proj
trusted = torch.from_numpy(np.asarray(mask, dtype=np.uint8).copy() == 255)
bits, ordered, order = native_observation.build_occupancy_index(coords)
admission: dict[str, Any] = {}
- admitted: dict[str, Any] = {}
+ depth_gate: dict[str, Any] = {}
+ completion_metadata: dict[str, Any] = {}
if case.get("image_depth") is None:
owners = native_observation.pixel_first_occupied(dict(case["camera"]), bits, trusted, stats=admission)
else:
owners = native_observation.pixel_first_occupied(dict(case["camera"]), bits, trusted, stats=admission,
- image_depth=case["image_depth"], admitted_out=admitted)
+ image_depth=case["image_depth"], depth_gate_out=depth_gate)
_alignment_report(uv, alpha, admission, np, image, image_filter)
if admission.get("image_depth"):
diagnostic = admission["image_depth"]
@@ -330,19 +332,19 @@ def _partial(surface: Any, shape: Any, case: dict[str, Any], external: Any, proj
f"{diagnostic['valid_pixels']} paired depth pixels, "
f"{diagnostic['rejected_pixels']} mismatch pixels", flush=True)
visible = native_observation.owner_rows(coords, owners, ordered, order)
- if "pixels" in admitted:
- keep = np.asarray(admitted["pixels"], dtype=bool)
- case["observation_keep"] = keep
- safe = _source_footprint_safe(keep, grid, runtime, device)
+ if "keep_mask" in depth_gate:
+ depth_keep = np.asarray(depth_gate["keep_mask"], dtype=bool)
+ safe = _source_footprint_safe(depth_keep, grid, runtime, device)
admission["rejected_image_depth_footprint_owners"] = int((visible & ~safe).sum())
visible &= safe
admission["observed_voxels"] = int(visible.sum())
- case["observation_admission"] = admission
+ completion_metadata = {"observation_keep": depth_keep, "observation_admission": admission}
print(f"Observation image depth: excluded {admission['rejected_image_depth_footprint_owners']} "
f"additional voxel samples crossing the mismatch mask; {admission['observed_voxels']} observed voxels", flush=True)
if not bool(visible.any()): raise RuntimeError("the trusted alpha gate leaves no observed material surface")
with torch.no_grad():
- return native_observation.encode_partial(encoder, coords, visible, sampled(case["albedo"]), sampled(case["mra"]), shape.coords[:, 1:], dict(normalization), sparse, device)
+ observation = native_observation.encode_partial(encoder, coords, visible, sampled(case["albedo"]), sampled(case["mra"]), shape.coords[:, 1:], dict(normalization), sparse, device)
+ return observation, completion_metadata
def _export(output: Path, representation: Any, texture_size: int, decimation_target: int, texture_format: str, runtime: Mapping[str, Any], *, gutter: bool = False, low_vram: bool = False) -> None:
@@ -434,15 +436,14 @@ def _run_completion_low_vram(*, case: Mapping[str, Any], back_case: Mapping[str,
shape = _stage_sparse(shape, device)
del shape_encoder
texture_encoder = _load_vae(models, _stem(ckpts / "tex_enc_next_dc_f16c32_fp16", "material encoder"))
- dual_stats = {}
with _completion_stage(texture_encoder, torch, device):
if back_case is None:
external, projection = _camera(case["camera"], device, torch, runtime["utils3d"])
- observation = _partial(surface, shape, case, external, projection, texture_encoder, partial_stats, runtime, device)
+ observation, completion_metadata = _partial(surface, shape, case, external, projection, texture_encoder, partial_stats, runtime, device)
del external, projection
else:
from .dual_view import encode_two_views
- observation, dual_stats = encode_two_views(surface, shape, case, back_case, texture_encoder,
+ observation, completion_metadata = encode_two_views(surface, shape, case, back_case, texture_encoder,
partial_stats, runtime, device)
del texture_encoder, surface
torch.cuda.empty_cache()
@@ -488,9 +489,7 @@ def _run_completion_low_vram(*, case: Mapping[str, Any], back_case: Mapping[str,
representation = runtime["MeshWithVoxel"](case["vertices"], case["faces"], [-.5, -.5, -.5], 1. / RESOLUTION, decoded_cpu.coords[:, 1:].int(), decoded_cpu.feats.float().clamp(0, 1), torch.Size([1, 6, RESOLUTION, RESOLUTION, RESOLUTION]), layout=LAYOUT)
del decoded_cpu
_export(Path(output), representation, texture_size, decimation_target, texture_format, runtime, gutter=gutter, low_vram=True)
- if back_case is None and case.get("observation_keep") is not None:
- return {"observation_keep": case["observation_keep"], "observation_admission": case.get("observation_admission", {})}
- return dual_stats
+ return completion_metadata
def _run_completion(*, input_dir: str | Path, output: str | Path, model_config: str | Path, checkpoint: str | Path, trellis_root: str | Path, seed: int = 42, device: str = "cuda", texture_size: int = 4096, decimation_target: int = 500000, texture_format: str = "png", gutter: bool = False, back_case: Mapping[str, Any] | None = None, remove_floaters: bool = False) -> dict[str, Any]:
@@ -519,12 +518,11 @@ def _run_completion(*, input_dir: str | Path, output: str | Path, model_config:
external, projection = _camera(case["camera"], device, torch, runtime["utils3d"])
shape, surface = _shape(case["vertices"], case["faces"], shape_encoder, runtime, device)
shape_encoder.to("cpu"); torch.cuda.empty_cache()
- dual_stats = {}
if back_case is None:
- observation = _partial(surface, shape, case, external, projection, texture_encoder, partial_stats, runtime, device)
+ observation, completion_metadata = _partial(surface, shape, case, external, projection, texture_encoder, partial_stats, runtime, device)
else:
from .dual_view import encode_two_views
- observation, dual_stats = encode_two_views(surface, shape, case, back_case, texture_encoder,
+ observation, completion_metadata = encode_two_views(surface, shape, case, back_case, texture_encoder,
partial_stats, runtime, device)
texture_encoder.to("cpu"); torch.cuda.empty_cache()
from supratex.pipelines.observation_guided_completion import build_completion_model, sample_material_latents
@@ -551,9 +549,7 @@ def _run_completion(*, input_dir: str | Path, output: str | Path, model_config:
if decoded.feats.shape[1] != 6: raise RuntimeError("material decoder must emit six PBR channels")
representation = runtime["MeshWithVoxel"](case["vertices"].to(device), case["faces"].to(device), [-.5, -.5, -.5], 1. / RESOLUTION, decoded.coords[:, 1:].int(), decoded.feats.float().clamp(0, 1), torch.Size([1, 6, RESOLUTION, RESOLUTION, RESOLUTION]), layout=LAYOUT)
_export(Path(output), representation, texture_size, decimation_target, texture_format, runtime, gutter=gutter)
- if back_case is None and case.get("observation_keep") is not None:
- return {"observation_keep": case["observation_keep"], "observation_admission": case.get("observation_admission", {})}
- return dual_stats
+ return completion_metadata
def _require_reprojection_atlas(texture_size: int, texture_format: str) -> None: