ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Diffusers 中的 Shap-E 实战指南:用文本与图像生成 3D 资产(NeRF 渲染与网格导出全流程)

Diffusers 中的 Shap-E 实战指南:用文本与图像生成 3D 资产(NeRF 渲染与网格导出全流程) Diffusers 中的 Shap-E 实战指南用文本与图像生成 3D 资产NeRF 渲染与网格导出全流程【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers导读Shap-E 是 OpenAI 提出的条件式 3D 资产生成模型与只输出单一表示如点云的早期工作不同它直接生成隐式函数implicit function的参数这些参数既可以渲染为带纹理的网格textured mesh也可以渲染为神经辐射场NeRF。在 Diffusers 仓库中Shap-E 通过ShapEPipeline文本转 3D与ShapEImg2ImgPipeline图像转 3D两条管线实现并配套提供 GIF 帧导出、PLY/OBJ 网格导出等实用工具。读完本文你将掌握在 Diffusers 中安装并运行 Shap-E 的完整流程、文本与图像两种输入方式的核心参数与调用链、以及将生成结果导出为gif/ply/obj/glb等下游可直接使用的文件格式。Shap-E 模型原理与 Diffusers 中的实现架构两阶段训练范式Shap-E 采用两阶段训练可参考英文 API 文档 docs/source/en/api/pipelines/shap_e.md编码器阶段训练一个编码器将 3D 资产的点云与渲染视图作为输入输出能够表示该资产的隐式函数参数即 NeRF/STF 网络的 MLP 权重参数扩散模型阶段在编码器输出的 latent 上训练条件扩散模型。推理时只需几秒即可生成复杂多样的 3D 资产且相比显式生成点云的 Point-E它建模的是更高维、多表示mesh 与 NeRF 兼顾的输出空间。Diffusers 中的组件构成从源码结构看Diffusers 将 Shap-E 拆分为 5 个文件位于 src/diffusers/pipelines/shap_e文件职责pipeline_shap_e.py定义ShapEPipeline文本 → latent → 渲染pipeline_shap_e_img2img.py定义ShapEImg2ImgPipeline图像 → latent → 渲染renderer.pyShapERendererlatent 投影为 MLP 权重执行 NeRF 体渲染与 Marching Cubes 网格解码camera.pycreate_pan_cameras生成环绕物体的虚拟相机默认 20 个视角__init__.py导出ShapEPipeline、ShapEImg2ImgPipeline、ShapEParamsProjModel、ShapERendererShapEPipeline由四类模块组成见 pipeline_shap_e.pypriorPriorTransformerunCLIP 风格的先验模型将文本/图像嵌入映射为 3D latenttext_encoder/image_encoderCLIP 文本编码器CLIPTextModelWithProjection或 CLIP 视觉编码器CLIPVisionModel配合对应的 tokenizer/processorschedulerHeunDiscreteScheduler用于去噪采样shap_e_rendererShapERenderer将 latent 投影为 MLP 参数并通过 NeRF 方法渲染出 3D 对象的图像帧或网格。两个管线均声明了model_cpu_offload_seq分别为text_encoder-prior与image_encoder-prior并把shap_e_renderer排除在 CPU 卸载之外说明渲染器在推理时通常常驻显存。环境准备运行 Shap-E 需要以下 Python 库Colab 中取消注释即可安装# Colab 中取消注释以安装必要依赖 #!pip install -q diffusers transformers accelerate trimesh其中trimesh仅用于网格格式转换PLY → GLBtransformers提供 CLIP 文本/图像编码器accelerate用于设备管理与可能的 CPU 卸载。若只需渲染 GIF 帧可暂不安装trimesh。文本转 3DText-to-3D基本用法将文本提示词传入ShapEPipeline管线会生成一组 3D 对象的图像帧再通过export_to_gif合成 GIFimport torch from diffusers import ShapEPipeline device torch.device(cuda if torch.cuda.is_available() else cpu) pipe ShapEPipeline.from_pretrained(openai/shap-e, dtypetorch.float16, variantfp16) pipe pipe.to(device) guidance_scale 15.0 prompt [A firecracker, A birthday cupcake] images pipe( prompt, guidance_scaleguidance_scale, num_inference_steps64, frame_size256, ).images将图像帧列表导出为 3D 对象的 GIFfrom diffusers.utils import export_to_gif export_to_gif(images[0], firecracker_3d.gif) export_to_gif(images[1], cake_3d.gif)核心参数解析源码级ShapEPipeline.__call__的完整签名见 pipeline_shap_e.py各参数语义如下参数默认值说明prompt必填str或list[str]支持批量生成num_images_per_prompt1每个提示词生成的图像数量num_inference_steps25去噪步数越多质量越高但推理更慢官方示例常用64generatorNonetorch.Generator用于可复现的确定性生成latentsNone预生成的高斯噪声 latent可用于同一 latent 配合不同提示词微调生成guidance_scale4.0无分类器引导强度 1.0时启用 CFG见下文frame_size64每个 3D 输出图像帧的宽高示例常用256output_typepil可选pil、np、latent、meshreturn_dictTrue为False时返回普通 tuple值得注意的底层行为可从源码验证CFG 编码当guidance_scale 1.0时_encode_prompt会将负向嵌入置零并与正向嵌入拼接为同一 batchpipeline_shap_e.py从而在一次前向中同时得到无条件与条件预测去噪循环中再按noise_pred_uncond guidance_scale * (noise_pred - noise_pred_uncond)融合同文件 L292-L294。官方示例中文本转 3D 使用15.0。latent 形状latent 初始化为(batch_size, num_embeddings * embedding_dim)随后 reshape 为(batch_size, num_embeddings, embedding_dim)参与去噪L264-L274num_embeddings与embedding_dim取自prior.config。XLA 支持检测到torch_xla时会在每一步调用xm.mark_step()表明该管线支持在 TPU 等 XLA 设备上运行。渲染背后的 NeRF 流程ShapERenderer.decode_to_imagerenderer.py的工作流程为用ShapEParamsProjModel将生成 latent 投影为nerstf.mlp.*.weight等 MLP 参数对应ChannelsProj的线性投影 LayerNorm见同文件 L733-L780通过create_pan_cameras(size)创建 20 个环绕视角的针孔相机camera.py相机距离物体 4 个单位对每个视角的光线先用StratifiedRaySampler做 64 个粗采样n_coarse_samples64再基于粗渲染权重用ImportanceRaySampler做 128 个精采样n_fine_samples128光线按ray_batch_size4096分批沿光线按integrate_samples做体渲染积分density 累积透明度、channels 加权求和最终拼合为size × size的 RGB 帧。这解释了为什么frame_size越大单帧渲染耗时越长——每帧需要采样frame_size²条光线。图像转 3DImage-to-3D用 Kandinsky 2.1 生成输入图像ShapEImg2ImgPipeline接受任意图像作为输入。你可以使用现有图片也可以先用扩散模型生成一张新图。官方示例选用 Kandinsky 2.1对应 API 文档 docs/source/en/api/pipelines/kandinsky.mdfrom diffusers import DiffusionPipeline import torch prior_pipeline DiffusionPipeline.from_pretrained(kandinsky-community/kandinsky-2-1-prior, dtypetorch.float16, use_safetensorsTrue).to(cuda) pipeline DiffusionPipeline.from_pretrained(kandinsky-community/kandinsky-2-1, dtypetorch.float16, use_safetensorsTrue).to(cuda) prompt A cheeseburger, white background image_embeds, negative_image_embeds prior_pipeline(prompt, guidance_scale1.0).to_tuple() image pipeline( prompt, image_embedsimage_embeds, negative_image_embedsnegative_image_embeds, ).images[0] image.save(burger.png)将图像送入 Shap-E把生成的奶酪汉堡图传给ShapEImg2ImgPipeline得到 3D 表示from PIL import Image from diffusers import ShapEImg2ImgPipeline from diffusers.utils import export_to_gif pipe ShapEImg2ImgPipeline.from_pretrained(openai/shap-e-img2img, dtypetorch.float16, variantfp16).to(cuda) guidance_scale 3.0 image Image.open(burger.png).resize((256, 256)) images pipe( image, guidance_scaleguidance_scale, num_inference_steps64, frame_size256, ).images gif_path export_to_gif(images[0], burger_3d.gif)与文本管线的差异对比 pipeline_shap_e_img2img.py 与文本管线主要差异在于条件编码部分输入为PIL.Image.Image、torch.Tensor、np.ndarray或它们的列表用CLIPImageProcessor预处理图像再经CLIPVisionModel得到last_hidden_state并丢弃[CLS]位置image_embeds[:, 1:, :]作为条件L157-L158CFG 的负向条件同样置零L162-L168官方示例中图像转 3D 的guidance_scale明显更低3.0因为图像条件本身已包含丰富的形状与语义信息无需过强的文本引导。网格生成与文件导出Mesh OutputShap-E 的一个关键优势是不仅能渲染 NeRF 图像帧还能直接输出带纹理的三角网格供下游应用游戏、渲染、3D 打印使用。设置output_typemesh即可文本与图像两条管线均支持import torch from diffusers import ShapEPipeline device torch.device(cuda if torch.cuda.is_available() else cpu) pipe ShapEPipeline.from_pretrained(openai/shap-e, dtypetorch.float16, variantfp16) pipe pipe.to(device) guidance_scale 15.0 prompt A birthday cupcake images pipe(prompt, guidance_scaleguidance_scale, num_inference_steps64, frame_size256, output_typemesh).images导出为 PLY使用export_to_ply将网格保存为ply文件[!TIP] 也可以使用export_to_obj将网格输出保存为obj文件支持多种格式存储网格输出下游使用更加灵活from diffusers.utils import export_to_ply ply_path export_to_ply(images[0], 3d_cake.ply) print(fSaved to folder: {ply_path})从 export_utils.py 的实现看export_to_ply会读取mesh.verts、mesh.faces与mesh.vertex_channels[R/G/B]写入二进制小端格式的 PLY顶点包含 xyz 坐标与 RGB 颜色属性并附上element face与vertex_index列表保证颜色随网格一并保留。转换为 GLB 并在数据集查看器中可视化用trimesh将ply转换为glb文件——GLB 被 Datasets 的 Dataset viewer 原生支持可直接在浏览器中预览网格import trimesh mesh trimesh.load(3d_cake.ply) mesh_export mesh.export(3d_cake.glb, file_typeglb)默认情况下网格输出以下方视角为焦点。若想调整默认视角可以对网格施加旋转变换import trimesh import numpy as np mesh trimesh.load(3d_cake.ply) rot trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0]) mesh mesh.apply_transform(rot) mesh_export mesh.export(3d_cake.glb, file_typeglb)将glb文件上传到数据集仓库即可通过 Dataset viewer 直接在线可视化网格。网格解码原理ShapERenderer.decode_to_meshrenderer.py走的是 STFsigned distance field texture field渲染路径将同一批 latent 投影为 MLP 权重与图像渲染共用ShapEParamsProjModel在128³grid_size128的规则网格上查询 SDF 值按query_batch_size4096分批并强制在边界外填充-1.0以封闭模型表面使用Marching Cubes 算法MeshDecoder见 renderer.py从符号距离场构造三角网格顶点坐标通过场值在体素棱边上的线性插值精确定位在每个网格顶点处查询 MLP 的颜色头得到 RGB 纹理texture_channels(R,G,B)经 sRGB → linear 转换后写入vertex_channels最终返回MeshDecoderOutput(verts, faces, vertex_channels)。因此export_to_ply与export_to_obj之所以能直接写入颜色正是因为decode_to_mesh已在顶点上附带 RGB 通道。测试与验证仓库提供了两条管线的单元测试可验证参数校验、输出形状与渲染正确性tests/pipelines/shap_e/test_shap_e.py文本转 3D 管线的测试包括output_type合法性校验非pil/np/latent/mesh时抛ValueError、batch 数量推断等tests/pipelines/shap_e/test_shap_e_img2img.py图像转 3D 管线的测试覆盖PIL.Image.Image、torch.Tensor、列表等输入类型及其 batch 推断逻辑。运行测试前需确保已安装diffusers开发依赖及transformers、accelerate等可选依赖并保持与文档一致的模型仓库路径openai/shap-e与openai/shap-e-img2img。小结文本转 3DShapEPipeline.from_pretrained(openai/shap-e)推荐guidance_scale15.0、num_inference_steps64、frame_size256输出为多视角 GIF 帧或网格图像转 3DShapEImg2ImgPipeline.from_pretrained(openai/shap-e-img2img)推荐guidance_scale3.0可与 Kandinsky 2.1 等文生图模型组合成文本 → 图像 → 3D链路网格导出output_typemesh后经export_to_ply/export_to_obj落盘再用trimesh转为glb并上传 Dataset viewer 在线预览源码深读入口管线实现在 src/diffusers/pipelines/shap_eNeRF/STF 渲染与 Marching Cubes 解码在 renderer.py环绕相机在 camera.py导出工具在 src/diffusers/utils/export_utils.py。掌握以上链路即可在 Diffusers 中一键完成提示词 / 图片 → 可旋转的 3D 对象 → 可直接渲染的网格资产的完整生产流程。【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表