Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Inserting alpha value to a 4-dimentsional RGB numpy array

Following this tutorial, I am trying to build a color cube in matplotlib.

        spatialAxes = [self.step, self.step, self.step]
        r, g, b= np.indices((self.step+1, self.step+1, self.step+1)) / 16.0
        rc = self.midpoints(r)
        gc = self.midpoints(g)
        bc = self.midpoints(b)

        cube = np.ones(spatialAxes, dtype=np.bool)

        # combine the color components
        colors = np.zeros(cube.shape + (3,))
        colors[..., 0] = rc
        colors[..., 1] = gc
        colors[..., 2] = bc
        
        self.axes.voxels(r, g, b, cube,
              facecolors = colors, 
              linewidth = 0)

midpoints is from the link above and is defined as

def midpoints(self, x):
    sl = ()
    for i in range(x.ndim):
        x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0
        sl += np.index_exp[:]
    return x

This does produce a color cube, but it is completely opaque. So I tried to add opacity by:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        colors = np.dstack( (colors, np.ones(spatialAxes) * .5) ) # .5 opacity

Which did not work.

Given that colors is a 4-dimensional array with a shape of (X, X, X, 3), where X is the value of self.step. How do I append the alpha channel to this array?

>Solution :

You can make colors an array with a forth component like this:

# combine the color components
colors = np.zeros(sphere.shape + (4, ))
colors[..., 0] = rc
colors[..., 1] = gc
colors[..., 2] = bc
colors[..., 3] = 0.2   # opacity (alpha)

BTW, I (half unconsciously) used the matplotlib example that you linked to. The challenge with your code is that it’s not complete, so I cannot run it myself (hint ;)).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading