TexSet / examples /read_one_sample.py
Tome1212's picture
TexSet 1.0.0: dataset card, terms, manifests, example reader
2f7eca2 verified
Raw History Blame Contribute Delete
4.7 kB
"""Read one object from a TexSet shard and put a UV layout onto its mesh.
pip install numpy trimesh pillow
python examples/read_one_sample.py data/val/val-00000-of-00001.tar [uid]
Members of one object are adjacent in the tar and share the uid as key:
<uid>.glb <uid>.uv.npz <uid>.tex_A.png <uid>.tex_B.png <uid>.tex_C.png <uid>.meta.json
"""
import hashlib, io, json, sys, tarfile
import numpy as np
def read_sample(tar_path, want_uid=None):
with tarfile.open(tar_path, "r:") as tf:
key, out = None, {}
for m in tf:
if not m.isfile():
continue
uid, ext = m.name.split(".", 1)
if want_uid is not None and uid != want_uid:
if key is not None:
break
continue
if key is None:
key = uid
if uid != key:
break
out[ext] = tf.extractfile(m).read()
if key is None:
raise KeyError(want_uid)
return key, out
def load_mesh_like_texset(glb_bytes):
"""Exactly the vertex welding the UV sets were built against (loader
`TextureTools.load_whole_mesh+Texture.from_trimesh`, reproduced with plain trimesh 5.1):
load with process=False, bake the scene graph, concatenate, then three merge_vertices passes."""
import trimesh
from trimesh.visual.texture import TextureVisuals
s = trimesh.load(io.BytesIO(glb_bytes), file_type="glb", process=False)
if isinstance(s, trimesh.Scene):
g = s.dump()
m = g[0] if len(g) == 1 else trimesh.util.concatenate(g)
else:
m = s
m.merge_vertices(merge_tex=False, merge_norm=True)
m = m.copy(include_cache=True)
if isinstance(m.visual, TextureVisuals):
m.visual.vertex_attributes.update(m.visual.vertex_attributes.data)
m.merge_vertices(merge_tex=False, merge_norm=True)
m = m.copy(include_cache=True)
m.merge_vertices(merge_tex=True, merge_norm=True)
return np.asarray(m.vertices, np.float32), np.asarray(m.faces, np.int32)
def fingerprint(V, F):
h = hashlib.sha256()
h.update(np.ascontiguousarray(V, np.float32).tobytes())
h.update(np.ascontiguousarray(F, np.int32).tobytes())
return h.hexdigest()
if __name__ == "__main__":
uid, raw = read_sample(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)
meta = json.loads(raw["meta.json"])
uv = np.load(io.BytesIO(raw["uv.npz"]))
print(f"uid {uid}: {meta['n_faces']:,} faces, {meta['n_vertices']:,} vertices, loader {meta['loader']}")
for name in ("A", "B", "C"):
uv_vertices = uv[f"{name}/uv_vertices"].astype(np.float32) / 65535.0 # (K,2) in [0,1]
uv_faces = uv[f"{name}/uv_faces"] # (F,3), row i <-> mesh face i
v = meta["variants"][name]
print(f" variant {name}: {len(uv_vertices):,} uv vertices, {v['charts']} charts, "
f"utilization {v['utilization']:.3f}, faces without texel {v['faces_without_texel']}")
# the atlas: RGBA, alpha = chart-coverage mask (NOT transparency); row 0 is v = 0 (no flip)
try:
from PIL import Image
tex = np.asarray(Image.open(io.BytesIO(raw["tex_A.png"])))
print(f" tex_A {tex.shape} {tex.dtype}, covered texels {(tex[..., 3] > 0).mean():.1%}")
except ImportError:
print(" (install pillow to decode the atlases)")
# bind UV set A to the mesh and check the fingerprint
try:
V, F = load_mesh_like_texset(raw["glb"])
if meta["fingerprint"] is None: # a pruned object: sealed faces were deleted after baking
ok = len(F) == meta["n_faces"]
print(f" mesh from glb: {len(F):,} faces; pruned object ({meta['pruned']['faces_removed']} faces removed), "
f"no fingerprint - face count {'OK' if ok else 'MISMATCH'}")
else:
ok = fingerprint(V, F) == meta["fingerprint"]
print(f" mesh from glb: {len(F):,} faces; fingerprint {'OK' if ok else 'MISMATCH'}")
if ok:
uv_a = uv["A/uv_vertices"].astype(np.float32) / 65535.0
corner_uv = uv_a[uv["A/uv_faces"]] # (F,3,2) per-corner UV
H, W = tex.shape[:2]
centre = corner_uv.mean(1)
col = np.clip((centre[:, 0] * W).astype(int), 0, W - 1)
row = np.clip((centre[:, 1] * H).astype(int), 0, H - 1) # row = v*H, no flip
print(f" albedo at face centres, first 3 faces: {tex[row[:3], col[:3], :3].tolist()}")
except ImportError:
print(" (install trimesh to load the mesh and verify the fingerprint)")