pythondata-visualizationmayavimayavi.mlab

Assign colors to each points in points3d using mayavi python


I have some points in 3D space. Each point has a color which is calculated using the following formulation-

// pack r/g/b into rgb
uint8_t r = 255, g = 0, b = 0;    // Example: Red color
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);

As shown above, the RGB color is packed into one value. I am trying to visualize these points using mayavi python. Please see below the code snippet-

from mayavi.mlab import *
import numpy as np

N = 10
# generate random points and colors (just for debugging)
(x, y, z) = np.random.random((3, N))
colors = np.random.random(N)

nodes = points3d(x, y, z, scale_factor=0.1)
nodes.glyph.scale_mode = 'scale_by_vector'
nodes.mlab_source.dataset.point_data.scalars = colors

show()

The above code is using random colors and it shows the following output-

output with random color

However, I want to specify colors instead of using random values. Please note that each point has a color. In this post, in order to make it easier, I am generating same colored points using the following function-

def pack_rgb(r, g, b):
    rgb = (r<<16) + (g<<8) + b
    return rgb

colors = [pack_rgb(0, 255, 0) for _ in range(N)]

This generates red colored points, instead of green colored points as shown below-

specified colors

What's going on here? My goal is to visualize colored points in mayavi python where each point has an RGB color.


Solution

  • Points in 3D space can easily be visualized using Mayavi. It is possible to assign RGB colors to each point individually. We can also set a scaling factor for each point. I found the following solution from the Mayavi community and I would like to share it here-

    from mayavi import mlab
    import numpy as np
    
    n = 100 # number of points
    x, y, z = np.random.random((3, n))
    rgba = np.random.randint(0, 256, size=(n, 4), dtype=np.uint8)
    rgba[:, -1] = 255 # no transparency
    pts = mlab.pipeline.scalar_scatter(x, y, z) # plot the points
    pts.add_attribute(rgba, 'colors') # assign the colors to each point
    pts.data.point_data.set_active_scalars('colors')
    g = mlab.pipeline.glyph(pts)
    g.glyph.glyph.scale_factor = 0.1 # set scaling for all the points
    g.glyph.scale_mode = 'data_scaling_off' # make all the points same size
    
    mlab.show()
    

    Please note that the above code requires Mayavi version 4.6.1 or greater.