Write a PLY file for a mesh.
(mesh, output_ply_path: str = None)
| 430 | |
| 431 | |
| 432 | def export_to_ply(mesh, output_ply_path: str = None): |
| 433 | """ |
| 434 | Write a PLY file for a mesh. |
| 435 | """ |
| 436 | if output_ply_path is None: |
| 437 | output_ply_path = tempfile.NamedTemporaryFile(suffix=".ply").name |
| 438 | |
| 439 | coords = mesh.verts.detach().cpu().numpy() |
| 440 | faces = mesh.faces.cpu().numpy() |
| 441 | rgb = np.stack([mesh.vertex_channels[x].detach().cpu().numpy() for x in "RGB"], axis=1) |
| 442 | |
| 443 | with buffered_writer(open(output_ply_path, "wb")) as f: |
| 444 | f.write(b"ply\n") |
| 445 | f.write(b"format binary_little_endian 1.0\n") |
| 446 | f.write(bytes(f"element vertex {len(coords)}\n", "ascii")) |
| 447 | f.write(b"property float x\n") |
| 448 | f.write(b"property float y\n") |
| 449 | f.write(b"property float z\n") |
| 450 | if rgb is not None: |
| 451 | f.write(b"property uchar red\n") |
| 452 | f.write(b"property uchar green\n") |
| 453 | f.write(b"property uchar blue\n") |
| 454 | if faces is not None: |
| 455 | f.write(bytes(f"element face {len(faces)}\n", "ascii")) |
| 456 | f.write(b"property list uchar int vertex_index\n") |
| 457 | f.write(b"end_header\n") |
| 458 | |
| 459 | if rgb is not None: |
| 460 | rgb = (rgb * 255.499).round().astype(int) |
| 461 | vertices = [ |
| 462 | (*coord, *rgb) |
| 463 | for coord, rgb in zip( |
| 464 | coords.tolist(), |
| 465 | rgb.tolist(), |
| 466 | ) |
| 467 | ] |
| 468 | format = struct.Struct("<3f3B") |
| 469 | for item in vertices: |
| 470 | f.write(format.pack(*item)) |
| 471 | else: |
| 472 | format = struct.Struct("<3f") |
| 473 | for vertex in coords.tolist(): |
| 474 | f.write(format.pack(*vertex)) |
| 475 | |
| 476 | if faces is not None: |
| 477 | format = struct.Struct("<B3I") |
| 478 | for tri in faces.tolist(): |
| 479 | f.write(format.pack(len(tri), *tri)) |
| 480 | |
| 481 | return output_ply_path |
| 482 | |
| 483 | |
| 484 | def export_to_obj(mesh, output_obj_path: str = None): |
nothing calls this directly
no test coverage detected