Hunyuan3D-2 代码集成指南:用 diffusers 风格 API 调用 Shape 生成与纹理合成流水线
【免费下载链接】Hunyuan3D-2High-Resolution 3D Assets Generation with Large Scale Hunyuan3D Diffusion Models.项目地址: https://gitcode.com/GitHub_Trending/hu/Hunyuan3D-2
本文基于仓库文档 code.md 展开,讲解 Hunyuan3D-2 的 Python 代码级接入方式:如何通过Hunyuan3DDiTFlowMatchingPipeline从单张或多视角图片生成 3D 网格,再通过Hunyuan3DPaintPipeline为网格自动合成纹理。读完本文,你可以直接在项目脚本中复用官方流水线完成「图片 → 白模 → 带纹理 GLB」的完整生成链路,并理解每个关键参数(推理步数、八叉树分辨率、CFG 引导强度、模型缓存路径等)背后的源码实现。
1. API 设计思路:diffusers 风格的 Pipeline
Hunyuan3D-2 的核心推理能力封装在hy3dgen包中,分为两大模块(见 hy3dgen/shapegen/init.py 与 hy3dgen/texgen/init.py):
hy3dgen.shapegen:shape 生成模块,导出Hunyuan3DDiTPipeline、Hunyuan3DDiTFlowMatchingPipeline两个主类,同时导出后处理器FaceReducer、FloaterRemover、DegenerateFaceRemover、MeshSimplifier和图像预处理器ImageProcessorV2等;hy3dgen.texgen:纹理合成模块,导出Hunyuan3DPaintPipeline与Hunyuan3DTexGenConfig。
两个 Pipeline 都遵循 diffusers 的使用范式:from_pretrained(model_path, ...)加载模型 →pipeline(...)调用推理。模型权重默认从 Hugging Face 的tencent/Hunyuan3D-2仓库按需下载并缓存到本地,首次运行后即可离线加载。
2. Shape 生成:Hunyuan3D-DiT 的最小调用
文档给出的最小可用示例如下,输入一张图片,输出一个trimesh对象:
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2') mesh = pipeline(image='assets/demo.png')[0]输出 mesh 是标准的 trimesh 对象(文档原文指向其官方文档),可以直接保存为 glb/obj 等格式:
mesh.export('demo.glb')2.1 from_pretrained 的关键参数
from_pretrained定义在 hy3dgen/shapegen/pipelines.py,签名与默认值如下:
| 参数 | 默认值 | 说明 |
|---|---|---|
model_path | - | 模型仓库名或本地路径,如'tencent/Hunyuan3D-2' |
device | 'cuda' | 推理设备 |
dtype | torch.float16 | 权重精度 |
use_safetensors | True | 是否以 safetensors 格式加载权重 |
variant | 'fp16' | 权重变体,加载model.fp16.safetensors |
subfolder | 'hunyuan3d-dit-v2-0' | 仓库中 shape DiT 模型所在子目录 |
其中subfolder决定了实际加载的模型:默认hunyuan3d-dit-v2-0是单视角模型;若加载多视角模型(Hunyuan3D-2mv),应指定subfolder='hunyuan3d-dit-v2-mv',可参考 examples/shape_gen_multiview.py。
2.2 推理调用参数详解
Hunyuan3DDiTFlowMatchingPipeline.__call__的完整签名(pipelines.py)及其默认值:
| 参数 | 默认值 | 说明 |
|---|---|---|
image | - | 支持路径字符串、路径列表、PIL.Image;多视角模型支持{"front": ..., "left": ..., "back": ...}字典 |
num_inference_steps | 50 | 采样步数 |
timesteps/sigmas | None | 自定义时间步/噪声调度,flow matching 下默认用np.linspace(0, 1, num_inference_steps) |
guidance_scale | 5.0 | 无分类器引导(CFG)强度;设为负数则关闭 |
generator | None | 随机数生成器,如torch.manual_seed(12345),用于结果可复现 |
box_v | 1.01 | 表面提取时包围盒半径(归一化空间) |
octree_resolution | 384 | 自适应八叉树提取的分辨率,决定网格精度 |
mc_level | 0.0 | marching cubes 的等值面水平 |
num_chunks | 8000 | 体素网格分块大小,显存不足时调小 |
mc_algo | None | 表面提取算法(已废弃,改用pipeline.vae.surface_extractor = SurfaceExtractors[algo](),可选mc/dmc) |
output_type | 'trimesh' | 可传'latent'直接返回潜变量 |
enable_pbar | True | 是否显示采样进度条 |
官方 examples/shape_gen.py 展示了典型的生产调用:对 RGB 图片先用BackgroundRemover去背景,再传入 pipeline:
from hy3dgen.rembg import BackgroundRemover from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline from PIL import Image import torch image = Image.open('assets/demo.png').convert("RGBA") rembg = BackgroundRemover() image = rembg(image) # 去除背景 pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( 'tencent/Hunyuan3D-2', subfolder='hunyuan3d-dit-v2-0', variant='fp16' ) mesh = pipeline( image=image, num_inference_steps=50, octree_resolution=380, num_chunks=20000, generator=torch.manual_seed(12345), output_type='trimesh', )[0] mesh.export('demo.glb')2.3 采样流程与显存优化
从call实现 可以看到 flow matching 采样的核心循环:每步把潜变量按 CFG 复制两份、经 DiT 预测噪声后做线性组合noise_pred = uncond + scale * (cond - uncond),再由 scheduler 更新样本。若模型自身带 guidance embedding(guidance_embed=True),则不走 CFG 而是把guidance_scale作为条件输入。
采样结束后,_export将潜变量经 VAE 解码为 SDF 体,再调用vae.latents2mesh做八叉树表面提取,最终export_to_trimesh翻转面片法向顺序并构造trimesh.Trimesh(pipelines.py)。
针对显存受限场景,Pipeline 提供了两种机制(实现均移植自 diffusers):
# 整模型级 CPU offload(conditioner -> model -> vae 顺序换入换出) pipeline.enable_model_cpu_offload()该类属性model_cpu_offload_seq = "conditioner->model->vae"决定了 offload 顺序(pipelines.py)。此外,enable_flashvdm可替换为 turbo 版 VAE 并启用 FlashVDM 解码加速,相关完整示例见 examples/fast_shape_gen_with_flashvdm.py。
3. 纹理合成:Hunyuan3D-Paint
文档中的纹理合成示例——先生成 mesh,再为同一张图做纹理烘焙:
from hy3dgen.texgen import Hunyuan3DPaintPipeline from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline # let's generate a mesh first pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2') mesh = pipeline(image='assets/demo.png')[0] pipeline = Hunyuan3DPaintPipeline.from_pretrained('tencent/Hunyuan3D-2') mesh = pipeline(mesh, image='assets/demo.png')Hunyuan3DPaintPipeline.from_pretrained支持subfolder参数,默认hunyuan3d-paint-v2-0-turbo(还有hunyuan3d-paint-v2-0两个变体,映射关系见 Hunyuan3DTexGenConfig)。若本地缺少权重,会依次尝试HY3DGEN_MODELS环境变量指定的缓存目录(默认~/.cache/hy3dgen),再回退到 Hugging Facesnapshot_download(pipelines.py)。
3.1 Paint 流水线的内部流程
从 Hunyuan3DPaintPipeline.call的源码实现可以还原出完整的纹理合成链路:
- 图像居中与 delight:输入图先经
recenter_image裁剪居中,再交给Light_Shadow_Remover(加载hunyuan3d-delight-v2-0子目录权重)去除光照阴影,得到中性外观的条件图; - UV 展开与网格加载:
mesh_uv_wrap对网格做 UV 展开,MeshRender(可微分渲染器,render_size=2048、texture_size=2048)加载网格; - 多视角条件渲染:在 6 个候选相机位姿(方位角
[0, 90, 180, 270, 0, 180],俯仰角[0, 0, 0, 0, 90, -90],对应权重[1, 0.1, 0.5, 0.1, 0.05, 0.05],见 Hunyuan3DTexGenConfig)下渲染法线贴图与位置贴图; - 多视角扩散生成:
Multiview_Diffusion_Net(即 hunyuanpaint 的 UNet + diffusers 管线)以 delight 图 + 法线/位置图为条件,生成各视角的纹理贴图; - 烘焙与补洞:
bake_from_multiview将各视角纹理反向投影到 UV 空间,按视角权重与余弦因子(bake_exp=4)加权融合(merge_method='fast'),未覆盖区域经texture_inpaint修补,最终render.save_mesh返回带纹理网格。
4. 进阶用法:examples 目录
文档最后指出,更多高级用法见 examples 目录,重点是多视角图片生成 3D和为手工网格(handcrafted mesh)做纹理生成。结合仓库实际文件:
- examples/shape_gen_multiview.py:使用
tencent/Hunyuan3D-2mv+subfolder='hunyuan3d-dit-v2-mv',输入{"front": ..., "left": ..., "back": ...}三个视角图片(示例图片见assets/example_mv_images/1/),生成一致性更好的多视角模型; - examples/textured_shape_gen_multiview.py:多视角 shape 生成 + 以 front 视角图做纹理合成的端到端组合;
- examples/textured_shape_gen.py:单视角白模 + 纹理合成的最短链路,与文档示例对应;
- examples/fast_shape_gen_with_flashvdm.py、examples/fast_shape_gen_multiview.py:基于 FlashVDM 的加速采样;
examples/shape_gen_mini.py、examples/textured_shape_gen_mini.py:小显存(mini)模型版本。
多视角 shape 生成的调用方式与单视角一致,只是image参数从单图换成视角字典:
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( 'tencent/Hunyuan3D-2mv', subfolder='hunyuan3d-dit-v2-mv', variant='fp16' ) mesh = pipeline( image={"front": front, "left": left, "back": back}, # PIL.Image 列表或字典 num_inference_steps=50, octree_resolution=380, num_chunks=20000, generator=torch.manual_seed(12345), output_type='trimesh', )[0]5. 模型加载与缓存机制
两个 Pipeline 的from_pretrained共享一套加载逻辑。shape 侧由smart_load_model(hy3dgen/shapegen/utils.py)实现,行为如下:
- 先拼接
HY3DGEN_MODELS(默认~/.cache/hy3dgen)+ 仓库名 +subfolder查找本地模型; - 本地不存在时,用
huggingface_hub.snapshot_download仅下载该subfolder子目录(allow_patterns=[f"{subfolder}/*"]),节省带宽; - 按
variant与use_safetensors拼接权重文件名(model.fp16.safetensors或model.fp16.ckpt),并加载同目录的config.yaml。
因此,from_single_file会依据config.yaml中的model/vae/conditioner/image_processor/scheduler五个 target 动态实例化组件(pipelines.py)。如果你只想调试耗时,可设置环境变量HY3DGEN_DEBUG=1,synchronize_timer会在日志中打印「Model Loading / Encode cond / Diffusion Sampling / Export to trimesh」各阶段耗时(utils.py)。
6. 小结
Hunyuan3D-2 的 Python 接入面非常收敛:
| 能力 | 入口 | 关键参数 |
|---|---|---|
| 单视角 shape 生成 | Hunyuan3DDiTFlowMatchingPipeline | num_inference_steps、octree_resolution、guidance_scale、generator |
| 多视角 shape 生成 | 同上 +tencent/Hunyuan3D-2mv | image传 front/left/back 字典 |
| 纹理合成 | Hunyuan3DPaintPipeline | subfolder(turbo / 标准),内部固定 6 视角烘焙 |
| 加速采样 | pipeline.enable_flashvdm() | turbo VAE + FlashVDM 解码 |
| 显存优化 | pipeline.enable_model_cpu_offload() | 组件级 CPU offload |
以上调用链与参数均与仓库源码一一对应:shape 侧核心在 hy3dgen/shapegen/pipelines.py,纹理侧核心在 hy3dgen/texgen/pipelines.py,端到端脚本可直接参考 examples 目录,环境搭建请参见 docs/source/installation/index.md 与 README。
【免费下载链接】Hunyuan3D-2High-Resolution 3D Assets Generation with Large Scale Hunyuan3D Diffusion Models.项目地址: https://gitcode.com/GitHub_Trending/hu/Hunyuan3D-2
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考