Write a PLY file for a mesh.
(mesh, output_ply_path: str = None)
| 528 | |
| 529 | |
| 530 | def export_to_ply(mesh, output_ply_path: str = None): |
| 531 | """ |
| 532 | Write a PLY file for a mesh. |
| 533 | """ |
| 534 | if output_ply_path is None: |
| 535 | output_ply_path = tempfile.NamedTemporaryFile(suffix=".ply").name |
| 536 | |
| 537 | coords = mesh.verts.detach().cpu().numpy() |
| 538 | faces = mesh.faces.cpu().numpy() |
| 539 | rgb = np.stack([mesh.vertex_channels[x].detach().cpu().numpy() for x in "RGB"], axis=1) |
| 540 | |
| 541 | with buffered_writer(open(output_ply_path, "wb")) as f: |
| 542 | f.write(b"ply\n") |
| 543 | f.write(b"format binary_little_endian 1.0\n") |
| 544 | f.write(bytes(f"element vertex {len(coords)}\n", "ascii")) |
| 545 | f.write(b"property float x\n") |
| 546 | f.write(b"property float y\n") |
| 547 | f.write(b"property float z\n") |
| 548 | if rgb is not None: |
| 549 | f.write(b"property uchar red\n") |
| 550 | f.write(b"property uchar green\n") |
| 551 | f.write(b"property uchar blue\n") |
| 552 | if faces is not None: |
| 553 | f.write(bytes(f"element face {len(faces)}\n", "ascii")) |
| 554 | f.write(b"property list uchar int vertex_index\n") |
| 555 | f.write(b"end_header\n") |
| 556 | |
| 557 | if rgb is not None: |
| 558 | rgb = (rgb * 255.499).round().astype(int) |
| 559 | vertices = [ |
| 560 | (*coord, *rgb) |
| 561 | for coord, rgb in zip( |
| 562 | coords.tolist(), |
| 563 | rgb.tolist(), |
| 564 | ) |
| 565 | ] |
| 566 | format = struct.Struct("<3f3B") |
| 567 | for item in vertices: |
| 568 | f.write(format.pack(*item)) |
| 569 | else: |
| 570 | format = struct.Struct("<3f") |
| 571 | for vertex in coords.tolist(): |
| 572 | f.write(format.pack(*vertex)) |
| 573 | |
| 574 | if faces is not None: |
| 575 | format = struct.Struct("<B3I") |
| 576 | for tri in faces.tolist(): |
| 577 | f.write(format.pack(len(tri), *tri)) |
| 578 | |
| 579 | return output_ply_path |
| 580 | |
| 581 | |
| 582 | def export_to_obj(mesh, output_obj_path: str = None): |
nothing calls this directly
no test coverage detected