如何在Python中更新GLB/GLTF 3D模型的纹理

6

我想在Python中加载一个GLB模型,用另一张贴图替换现有的贴图,并保存它。

目前我已经能够加载,修改和导出模型。同时,我找到了一种方法将本地图像附加到模型上。 但是,我不确定如何找到并替换现有的贴图。

一个具有一个纹理文件的示例3D模型:https://modelviewer.dev/shared-assets/models/Astronaut.glb

from pygltflib import GLTF2
from pygltflib.utils import ImageFormat, Image

filename = "Astronaut.glb"
gltf = GLTF2().load(filename)

image = Image()
image.uri = "new-texture.png"

gltf.images.append(image) 
gltf.convert_images(ImageFormat.DATAURI)
gltf.images[0].uri
gltf.images[0].name

# How to find and replace the existing texture?
# ...

filename2 = "updated-3D-model.glb"
gltf.save(filename2)

你好Tom,你找到解决方案了吗? :) 谢谢! - JAD
我们使用Blender将GLB转换为带有外部文件纹理的GLTF文件,并在服务器上动态替换这些文件。 GLTF文件始终指向相同的纹理文件,因此这是更改纹理而不是3D模型的最简单和最快速的解决方案。 - Tom
2个回答

0

你可以使用字符串替换在gltf文件中实现。我尝试过用Python和字符串替换,效果非常顺畅和快速。


1
你的回答可以通过提供额外的支持信息来改进。请编辑以添加更多细节,例如引用或文档,以便其他人可以确认你的回答是正确的。您可以在帮助中心中找到有关如何撰写好回答的更多信息。 - Community
你好,能否请您添加一个关于如何执行此操作的示例呢? - SameeraR

0
这是一个示例,说明如何做到这一点。
from pygltflib import GLTF2
from pygltflib.utils import ImageFormat, Image, Texture, Material

filename = "Astronaut.glb"
gltf = GLTF2().load(filename)

# Step 1: Find the index of the existing texture you want to replace
# Let's assume the texture you want to replace is at index 1 (you need to replace 1 with the actual index)
existing_texture_index = 1

# Step 2: Remove the old texture and its associated image from the GLB
# Remove the texture
gltf.textures.pop(existing_texture_index)

# Remove the image associated with the texture
existing_image_index = gltf.materials[0].pbrMetallicRoughness.baseColorTexture["index"]
gltf.images.pop(existing_image_index)

# Step 3: Add the new image and texture to the GLB
# Create and add a new image to the glTF (same as before)
new_image = Image()
new_image.uri = "new-texture.png"
gltf.images.append(new_image)

# Create a new texture and associate it with the added image
new_texture = Texture()
new_texture.source = len(gltf.images) - 1  # Index of the newly added image
gltf.textures.append(new_texture)

# Step 4: Assign the new texture to the appropriate material(s) or mesh(es)
# Assuming you have a mesh/primitive that was using the old texture and you want to apply the new texture to it, you need to set the material index for that mesh/primitive.
# Replace 0 with the actual index of the mesh/primitive you want to update.
gltf.meshes[0].primitives[0].material = len(gltf.materials) - 1

# Now you can convert the images to data URIs and save the updated GLB
gltf.convert_images(ImageFormat.DATAURI)

filename2 = "updated-3D-model.glb"
gltf.save(filename2)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接