Home > Software design >  Inserting alpha value to a 4-dimentsional RGB numpy array
Inserting alpha value to a 4-dimentsional RGB numpy array

Time:12-04

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:

        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?

CodePudding user response:

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 ;)).

  • Related