
Diffusers 中 Shap-E 3D 资产生成完全指南Text-to-3D、Image-to-3D 与网格导出实战【免费下载链接】diffusers Diffusers: State-of-the-art diffusion models for image, video, and audio generation in PyTorch.项目地址: https://gitcode.com/GitHub_Trending/di/diffusersShap-E 是 OpenAI 提出的条件生成式 3D 模型论文《Shap-E: Generating Conditional 3D Implicit Functions》与直接生成点云的 Point-E 不同它直接输出隐式函数的参数可同时渲染为带纹理的网格textured mesh和神经辐射场NeRF。在 Diffusers 中Shap-E 以ShapEPipeline文本驱动和ShapEImg2ImgPipeline图像驱动两条内置 pipeline 的形式集成于 src/diffusers/pipelines/shap_e本文将从安装、两大生成场景到网格导出与格式转换结合仓库源码完整讲解其使用方式与底层实现读完即可上手生成自己的 3D 资产。前置环境与依赖运行 Shap-E pipeline 需要以下库# uncomment to install the necessary libraries in Colab #!pip install -q diffusers transformers accelerate trimeshdiffusers提供ShapEPipeline/ShapEImg2ImgPipelinetransformers提供文本编码器CLIPTextModelWithProjection、CLIPTokenizer与图像编码器CLIPVisionModelaccelerate支持多设备执行与 CPU 卸载pipeline 源码中的model_cpu_offload_seq机制依赖它trimesh用于网格文件的格式转换如ply→glb与旋转变换。若需要把多个 pipeline 共享同一批组件例如同时加载 Shap-E 与其他模型时复用文本编码器可参考仓库中 loading 文档 中 “reuse components across pipelines” 一节用components参数高效复用已加载的模型权重避免重复占用显存。认识 Shap-E从文本/图像到 3D 隐式函数根据论文摘要Shap-E 采用两阶段训练编码器阶段训练一个编码器把 3D 资产确定性地映射为隐式函数的参数扩散模型阶段在编码器输出之上训练条件扩散模型给定文本或图像条件即可在数秒内生成复杂多样的 3D 资产。与显式建模点云的 Point-E 相比Shap-E 虽然建模了更高维、多表示的输出空间但收敛更快样本质量相当或更优。从 pipeline_shap_e.py 的类定义可以看到ShapEPipeline由以下组件构成组件类型作用prior[PriorTransformer]unCLIP 风格的先验模型从文本/图像 embedding 近似出 3D 隐表示text_encoderCLIPTextModelWithProjection冻结的 CLIP 文本编码器tokenizerCLIPTokenizer文本分词器schedulerHeunDiscreteScheduler与prior配合使用的 Heun 离散采样器shap_e_rendererShapERenderer把生成的潜变量投影为 MLP 参数用 NeRF 方法渲染出 3D 对象两个 pipeline 都声明了model_cpu_offload_seqShapEPipeline为text_encoder-priorShapEImg2ImgPipeline为image_encoder-prior并把shap_e_renderer排除在 CPU 卸载之外_exclude_from_cpu_offload [shap_e_renderer]渲染器始终留在 GPU 上执行。Text-to-3D文本提示生成 3D 对象将文本提示传入 [ShapEPipeline]pipeline 会生成一组合成 3D 对象的图像帧从 20 个环绕视角渲染再用工具函数把帧列表转成 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使用~utils.export_to_gif将图像帧列表转换为 3D 对象的 giffrom diffusers.utils import export_to_gif export_to_gif(images[0], firecracker_3d.gif) export_to_gif(images[1], cake_3d.gif)生成参数详解来自__call__签名ShapEPipeline.__call__的完整参数定义见 pipeline_shap_e.py各参数含义与默认值如下参数默认值说明prompt必填str或list[str]支持一次生成多个对象num_images_per_prompt1每个提示生成的图像数量num_inference_steps25去噪步数越多质量越高但推理更慢官方示例常用 64generatorNonetorch.Generator传入可使生成结果可复现latentsNone预生成的噪声潜变量可用于用不同提示微调同一生成guidance_scale4.0无分类器引导CFG强度越高越贴合提示但质量可能下降文本生成官方示例建议 15.0frame_size64每帧图像的宽高渲染分辨率示例中设为 256output_typepilpilPIL 图像、npnumpy 数组、latent原始潜变量或mesh网格return_dictTrue为True时返回ShapEPipelineOutput否则返回元组底层调用链CFG 与潜变量形状从源码可以还原整个生成流程pipeline_shap_e.py提示编码_encode_prompt将 tokenizer 的pad_token_id置为 0用 CLIP 文本编码器提取text_embeds归一化后在 CFG 开启时与全零的负向 embedding 拼接do_classifier_free_guidance guidance_scale 1.0潜变量初始化prepare_latents生成形状为(batch_size, num_embeddings * embedding_dim)的高斯噪声并乘以scheduler.init_noise_sigma随后 reshape 为(batch_size, num_embeddings, embedding_dim)去噪循环prior模型预测噪声去除方差通道后按 CFG 公式noise_pred_uncond guidance_scale * (noise_pred - noise_pred_uncond)合并交由HeunDiscreteScheduler.step推进渲染output_typemesh时调用shap_e_renderer.decode_to_mesh否则调用decode_to_image逐潜变量渲染。Image-to-3D从图像生成 3D 表示ShapEImg2ImgPipeline接受一张现有图像或现场生成的新图作为输入输出其 3D 表示。文档示例先用 Kandinsky 2.1 生成一张“白色背景上的芝士汉堡”图片再交给 Shap-E 转 3Dfrom diffusers import DiffusionPipeline import torch prior_pipeline DiffusionPipeline.from_pretrained(kandinsky-community/kandinsky-2-1-prior, dtypetorch.float16, use_safetensorsTrue).to(cuda) # or mps, xpu, cpu 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)将芝士汉堡图片传入 [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) # or mps, xpu, cpu 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)注意Image-to-3D 场景建议把guidance_scale设为较低的 3.0而非文本场景的 15.0因为输入图像本身已提供了强条件信号输入图像会被 resize 到与frame_size匹配的尺寸。ShapEImg2ImgPipeline的组件与文本版不同见 pipeline_shap_e_img2img.py它以image_encoderCLIPVisionModel和image_processorCLIPImageProcessor替代文本编码器。其_encode_image方法用 CLIP 视觉模型提取last_hidden_state并截取[:, 1:, :]去掉 [CLS] token 后作为条件 embeddingCFG 时同样与全零负向 embedding 拼接。去噪与渲染循环则与ShapEPipeline完全一致。生成网格Mesh并导出Shap-E 同时支持生成带纹理的网格输出便于下游应用渲染。在ShapEPipeline与ShapEImg2ImgPipeline的调用中把output_type指定为mesh即可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用 [~utils.export_to_ply] 把网格保存为ply文件[!TIP] 也可以使用 [~utils.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})用 trimesh 转换为 glb 并调整视角用 trimesh 库把ply转换为glb文件 Datasets 的数据集查看器支持渲染glb文件便于直接预览网格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)把网格文件上传到自己的数据集仓库后即可用 Dataset viewer 直接可视化预览。网格导出的底层实现export_to_ply/export_to_obj的实现位于 src/diffusers/utils/export_utils.pyexport_to_ply以二进制 little-endian 格式写出顶点坐标x/y/z与 RGB 顶点色、面片索引export_to_obj则以文本形式写出v顶点与f面片记录。二者都依赖MeshDecoderOutput的verts、faces与vertex_channels字段。而output_typemesh时的网格生成在 renderer.py 的decode_to_mesh中完成params_proj把生成的 1024 维潜变量投影为 MLP 各层权重对应ShapEParamsProjModel中param_names/param_shapes定义的四层线性层参数在 128³ 的规则网格上查询 SDF符号距离场值volume_query_points在包围盒[-1,1]³内采样用 Marching Cubes 算法MeshDecoder从 SDF 场重建三角网格在网格每个顶点上查询纹理颜色头把 sRGB 转为线性后写入vertex_channels。渲染原理NeRF 体渲染与环绕相机NeRF 图像帧渲染decode_to_imagerenderer.py采用两阶段粗-细coarse-to-fine体渲染先用StratifiedRaySampler在光线路径上做分层均匀采样64 个粗样本再用ImportanceRaySampler根据粗渲染得到的密度-透射率权重在可能含有物体的区域加密采样128 个细样本integrate_samples按体渲染公式累加每条光线的颜色未命中包围盒的光线由VoidNeRFModel填充背景色。渲染时默认的 NeRF MLPMLPNeRSTFModel对位置做 0~15 频带的 NeRF 式位置编码posenc_nerf方向编码为 0~8 频带在insert_direction_at4层插入方向向量最终输出密度、SDF 与颜色通道12 维按map_indices_to_keys切分为 sdf / density_coarse / density_fine / stf / nerf_coarse / nerf_fine。20 视角环绕相机生成 gif 所需的“多视角帧”来自 camera.py 的create_pan_cameras在0~2π范围内均匀取 20 个角度theta构建针孔相机环绕物体一周的视线方向每帧视场角x_fovy_fov0.7帧宽高由frame_size决定。因此每个提示词默认输出 20 帧图像export_to_gif按fps10默认把这些帧拼成循环 gif。输出对象与 API 参考两条 pipeline 的__call__均返回 [~pipelines.shap_e.pipeline_shap_e.ShapEPipelineOutput]return_dictTrue时其images字段为output_typepilPIL.Image.Image列表output_typenpnumpy 数组列表output_typelatent未渲染的潜变量张量形状为(batch_size, num_embeddings, embedding_dim)可用于自定义后续处理output_typemeshMeshDecoderOutput含verts、faces、vertex_channels。若return_dictFalse则返回只含images的元组。测试验证与扩展阅读仓库为两条 pipeline 提供了完整的测试覆盖tests/pipelines/shap_e/test_shap_e.pyShapEPipeline的组件装配、可选参数guidance_scale、frame_size等与输出形状验证tests/pipelines/shap_e/test_shap_e_img2img.pyShapEImg2ImgPipeline的图像条件生成测试。测试中用tiny-random-clip分词器与随机初始化的PriorTransformer构造最小可运行环境并验证ShapEPipelineOutput.images的形状可作为理解 pipeline 数据流与自行扩展的参考起点。若想在多个 pipeline 之间复用 Shap-E 已加载的组件或深入阅读文本/图像条件编码与 Heun 调度器细节可继续阅读加载与复用组件指南ShapEPipeline 实现ShapEImg2ImgPipeline 实现ShapERenderer 渲染实现【免费下载链接】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),仅供参考