user_cr
user_cr

Reputation: 120

how to convert binary voxelgrid (numpy 3d array) to open3d voxel format?

I have the 3d array np.zeros((24, 24, 100)), fill it with some '1's, and can visualize it (in 3d) using pyplot:

pyplot

open3d is more suitable to view this in 3d, and update it realtime, so I want to visualize this with open3d. But I don't understand how to visualize my binary voxelgrid using open3d.

This example is what I want (the voxel bunny); How can I convert my binary 3d array to the open3d voxelgrid format?

Converting to pointcloud is also an option, but there applies the same question.

Upvotes: 1

Views: 1046

Answers (1)

Henry
Henry

Reputation: 11

I created a function that writes a 3D numpy array's contents into a VoxelGrid object. See the code sample below for the conversion function and a possible use case. You may want to change the coloring to your convenience.

As far as I know, there is no way of copying a numpy array to a VoxelGrid since Open3D was originally written in C++ and doesn't use numpy data structures in the background. Hence, this snippet uses a nested for-loop.

def np_to_voxels(grid: np.ndarray):
    # Create new voxel grid object and set voxel_size to some value
    # --> otherwise it will default to 0 and the grid will be invisible
    voxel_grid = o3d.geometry.VoxelGrid()
    voxel_grid.voxel_size = 1
    # Iterate over numpy grid
    for z in range(grid.shape[2]):
        for y in range(grid.shape[1]):
            for x in range(grid.shape[0]):
                if grid[x, y, z] == 0:
                    continue
                # Create a voxel object
                voxel = o3d.geometry.Voxel()
                voxel.color = np.array([0.0, 0.0, 0.0]) * (1.0 - grid[x, y, z])
                voxel.grid_index = np.array([x, y, z])
                # Add voxel object to grid
                voxel_grid.add_voxel(voxel)
    return voxel_grid

# Visualize the voxel grid
grid = np.random.random(size=(10, 20, 30))
voxel_grid = np_to_voxels(grid)
o3d.visualization.draw_geometries([voxel_grid])

Upvotes: 1

Related Questions