Download preprocessing/ScanNet200/utils.py from Yezixiao/ScanQA_voxel_data: direct link, hf CLI and curl.
- Browser
- Download file 5.49 kB
-
https://huggingface.co/datasets/Yezixiao/ScanQA_voxel_data/resolve/main/preprocessing/ScanNet200/utils.py
- Command line
-
hf download hf://datasets/Yezixiao/ScanQA_voxel_data/preprocessing/ScanNet200/utils.py
-
curl -L -o utils.py https://huggingface.co/datasets/Yezixiao/ScanQA_voxel_data/resolve/main/preprocessing/ScanNet200/utils.py
5.49 kB
| import os | |
| import numpy as np | |
| from plyfile import PlyData, PlyElement | |
| import pandas as pd | |
| from scannet200_constants import * | |
| def read_plymesh(filepath): | |
| """Read ply file and return it as numpy array. Returns None if emtpy.""" | |
| with open(filepath, 'rb') as f: | |
| plydata = PlyData.read(f) | |
| if plydata.elements: | |
| vertices = pd.DataFrame(plydata['vertex'].data).values | |
| faces = np.array([f[0] for f in plydata["face"].data]) | |
| return vertices, faces | |
| def save_plymesh(vertices, faces, filename, verbose=True, with_label=True): | |
| """Save an RGB point cloud as a PLY file. | |
| Args: | |
| points_3d: Nx6 matrix where points_3d[:, :3] are the XYZ coordinates and points_3d[:, 4:] are | |
| the RGB values. If Nx3 matrix, save all points with [128, 128, 128] (gray) color. | |
| """ | |
| assert vertices.ndim == 2 | |
| if with_label: | |
| if vertices.shape[1] == 7: | |
| python_types = (float, float, float, int, int, int, int) | |
| npy_types = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('red', 'u1'), ('green', 'u1'), | |
| ('blue', 'u1'), ('label', 'u4')] | |
| if vertices.shape[1] == 8: | |
| python_types = (float, float, float, int, int, int, int, int) | |
| npy_types = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('red', 'u1'), ('green', 'u1'), | |
| ('blue', 'u1'), ('label', 'u4'), ('instance_id', 'u4')] | |
| else: | |
| if vertices.shape[1] == 3: | |
| gray_concat = np.tile(np.array([128], dtype=np.uint8), (vertices.shape[0], 3)) | |
| vertices = np.hstack((vertices, gray_concat)) | |
| elif vertices.shape[1] == 6: | |
| python_types = (float, float, float, int, int, int) | |
| npy_types = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('red', 'u1'), ('green', 'u1'), | |
| ('blue', 'u1')] | |
| else: | |
| pass | |
| vertices_array = np.empty(vertices.shape[0], dtype=npy_types) | |
| vertices_array['x'] = vertices[:, 0].astype(np.float32, copy=False) | |
| vertices_array['y'] = vertices[:, 1].astype(np.float32, copy=False) | |
| vertices_array['z'] = vertices[:, 2].astype(np.float32, copy=False) | |
| vertices_array['red'] = vertices[:, 3].astype(np.uint8, copy=False) | |
| vertices_array['green'] = vertices[:, 4].astype(np.uint8, copy=False) | |
| vertices_array['blue'] = vertices[:, 5].astype(np.uint8, copy=False) | |
| if with_label: | |
| vertices_array['label'] = vertices[:, 6].astype(np.uint32, copy=False) | |
| if vertices.shape[1] == 8: | |
| vertices_array['instance_id'] = vertices[:, 7].astype(np.uint32, copy=False) | |
| elements = [PlyElement.describe(vertices_array, 'vertex')] | |
| if faces is not None: | |
| faces_array = np.empty(len(faces), dtype=[('vertex_indices', 'i4', (3,))]) | |
| faces_array['vertex_indices'] = faces | |
| elements += [PlyElement.describe(faces_array, 'face')] | |
| # Write | |
| PlyData(elements).write(filename) | |
| if verbose is True: | |
| print('Saved point cloud to: %s' % filename) | |
| # Map the raw category id to the point cloud | |
| def point_indices_from_group(seg_indices, group, label_map, CLASS_IDs): | |
| group_segments = np.array(group['segments']) | |
| label = group['label'] | |
| # Map the category name to id | |
| label_id = int(label_map.get(label, 0)) | |
| # Only store for the valid categories | |
| if not label_id in CLASS_IDs: | |
| label_id = 0 | |
| # get points, where segment indices (points labelled with segment ids) are in the group segment list | |
| point_ids = np.where(np.isin(seg_indices, group_segments))[0] | |
| return point_ids, label_id | |
| # Uncomment out if mesh voxelization is required | |
| # Uncomment out if mesh voxelization is required | |
| import trimesh | |
| from trimesh.voxel import creation | |
| from sklearn.neighbors import KDTree | |
| import numpy as np # 确保导入了 numpy | |
| # VOXELIZE the scene from sampling on the mesh directly instead of vertices | |
| def voxelize_pointcloud(points, colors, labels, instances, faces, voxel_size=0.2): | |
| # voxelize mesh first and determine closest labels with KDTree search | |
| trimesh_scene_mesh = trimesh.Trimesh(vertices=points, faces=faces) | |
| voxel_grid = creation.voxelize(trimesh_scene_mesh, voxel_size) | |
| voxel_cloud = np.asarray(voxel_grid.points) | |
| orig_tree = KDTree(points, leaf_size=8) | |
| _, voxel_pc_matches = orig_tree.query(voxel_cloud, k=1) | |
| voxel_pc_matches = voxel_pc_matches.flatten() | |
| # match colors to voxel ids | |
| # 注意:原代码在这里已经将点除以了 voxel_size,将其缩放到了体素网格的尺度 | |
| scaled_points = points[voxel_pc_matches] / voxel_size | |
| colors = colors[voxel_pc_matches] | |
| labels = labels[voxel_pc_matches] | |
| instances = instances[voxel_pc_matches] | |
| # --- 使用纯 NumPy 替代 ME.utils.sparse_quantize --- | |
| # 1. 将缩放后的浮点坐标向下取整,转换为离散的整数体素坐标 | |
| discrete_coords = np.floor(scaled_points).astype(np.int32) | |
| # 2. 获取唯一的体素坐标,以及它们在原数组中第一次出现时的索引 (return_index=True) | |
| quantized_scene, scene_inds = np.unique(discrete_coords, axis=0, return_index=True) | |
| # -------------------------------------------------- | |
| # 根据索引获取对应的颜色、标签和实例 | |
| quantized_scene_colors = colors[scene_inds] | |
| quantized_labels = labels[scene_inds] | |
| quantized_instances = instances[scene_inds] | |
| return quantized_scene, quantized_scene_colors, quantized_labels, quantized_instances |