Example #1
0
def draw2DView(figure, raw, seg, index, color=(1,0,0)):
    """
    Draw a 2D maximum intensity projection of the raw data and create 
    a segmentation overlay
    """
    raw2d = np.max(raw, axis = 2)
    mlab.imshow(raw2d, colormap='gray', figure=figure)
    sother = np.multiply( (seg != 0).astype(np.int32),(seg != index).astype(np.int32) )
    ##max1 = np.max(np.where(np.max(np.max((seg == index).astype(np.int32), axis = 0), axis = 0)!=0))+1
    ##min1 = np.min(np.where(np.max(np.max((seg == index).astype(np.int32), axis = 0), axis = 0)!=0))
    ##max2 = np.max(np.where(np.max(np.max((seg == index).astype(np.int32), axis = 0), axis = 1)!=0))+1
    ##min2 = np.min(np.where(np.max(np.max((seg == index).astype(np.int32), axis = 0), axis = 1)!=0))
    ##d1 = int(min(max1-min1-15,0))
    ##d2 = int(min(max2-min2-15,0))
    ##min1 += d1
    ##max1 -= d1
    ##min2 += d2
    ##max2 -= d2
    ##sother = (seg == index).astype(np.int32)
    ##seg2dother = np.max(sother, axis = 0)
    ##seg2dother[min2:max2,min1:max1]=1
    sindex = (seg == index).astype(np.int32)
    seg2dother = np.max(sother, axis = 2)
    seg2dindex = np.max(sindex, axis = 2)
    mlab.contour_surf(seg2dother, color = (0,0,1), contours = 2, warp_scale = 0, figure=figure)
    mlab.contour_surf(seg2dindex, color = color, contours = 2, warp_scale = 0, figure=figure)
def test1():
    '''G8函数显示'''
    # f = lambda x,y:-(np.sin(2*np.pi*x)**3*np.sin(2*np.pi*y))/(x**3*(x+y))
    f = lambda x: -(np.sin(2 * np.pi * x[0])**3 * np.sin(2 * np.pi * x[1])) / (
        x[0]**3 * (x[0] + x[1]))
    g1 = lambda x: x[0]**2 - x[1] + 1
    g2 = lambda x: 1 - x[0] + (x[1] - 4)**2

    # min = [0.001,0.001]
    # max = [10,10]

    min = [1, 3]
    max = [2, 5]

    mesh_x, mesh_y = np.mgrid[min[0]:max[0]:500j, min[1]:max[1]:500j]
    v = np.zeros_like(mesh_x)

    for i in range(mesh_x.shape[0]):
        for j in range(mesh_x.shape[1]):
            p = np.array([mesh_x[i, j], mesh_y[i, j]])
            v[i, j] = np.log(f(p) + 10000)
            # if g1(p)<0 and g2(p)<0:
            #     v[i,j] = f(p)
            # else:
            #     v[i,j] = 0

    mlab.figure(size=[1024, 800])
    mlab.imshow(mesh_x, mesh_y, v)
    mlab.show()
    def test12(self):

        data = np.loadtxt(
            'C:\\Users\\Administrator\\Documents\\GitHub\\DifferentialEvolution\\map.csv',
            delimiter=',')
        mlab.imshow(data, colormap='gist_earth', interpolate=False)
        mlab.show()
Example #4
0
def mayavi_imshow():
    """
    绘制mayavi imshow图
    :return:
    """
    s = np.random.rand(3, 3)  # 生成随机的3*3数组
    mlab.imshow(s)
    mlab.colorbar()
    mlab.show()
Example #5
0
    def update_volume(self):
        y, x, z = self.points
        r = (y - self.y)**2 + (x - self.x)**2 + (z - self.z)**2
        b = np.ones_like(y)
        b[r > self.r**2] = 0
        self.src.mlab_source.scalars = b

        img = (self.H * b.reshape((-1, 1))).reshape((sensor_res, sensor_res))
        mlab.clf(figure=self.scene2.mayavi_scene)
        mlab.imshow(img, colormap='gray', figure=self.scene2.mayavi_scene)
        mlab.colorbar()
def mlab_imshowColor(im, alpha=255, **kwargs):
    """
    Plot a color image with mayavi.mlab.imshow.
    im is a ndarray with dim (n, m, 3) and scale (0->255]
    alpha is a single number or a ndarray with dim (n*m) and scale (0->255]
    **kwargs is passed onto mayavi.mlab.imshow(..., **kwargs)
    """
    try:
        alpha[0]
    except:
        alpha = pl.ones(im.shape[0] * im.shape[1]) * alpha
    if len(alpha.shape) != 1:
        alpha = alpha.flatten()

    # The lut is a Nx4 array, with the columns representing RGBA
    # (red, green, blue, alpha) coded with integers going from 0 to 255,
    # we create it by stacking all the pixles (r,g,b,alpha) as rows.
    myLut = pl.c_[im.reshape(-1, 3), alpha]
    myLutLookupArray = pl.arange(im.shape[0] * im.shape[1]).reshape(im.shape[0], im.shape[1])

    #We can display an color image by using mlab.imshow, a lut color list and a lut lookup table.
    theImshow = mlab.imshow(myLutLookupArray, colormap='binary', **kwargs) #temporary colormap
    theImshow.module_manager.scalar_lut_manager.lut.table = myLut
    mlab.draw()

    return theImshow
def mcrtmv(frames,
           dt,
           mesh,
           d_nodes,
           map,
           savemovie=False,
           mvname='test',
           vmin=-1,
           vmax=1):
    """
	Creates move from numpyfied results in 2d, using mencoder. Prolly does not work on mac!
	"""

    size = 500, 500

    fig = ml.figure(size=size, bgcolor=(1., 1., 1.))

    #fig.scene.anti_aliasing_frames=07

    #extent = [0,Nx-1,0,Ny-1,-30,30]
    xaxis = np.linspace(0, 1, d_nodes[0] + 1)
    yaxis = np.linspace(0, 1, d_nodes[1] + 1)
    ml.clf(figure=fig)
    u = np.load('solution_%06d.npy' % 1)
    u = numpyfy(u, mesh, d_nodes, map)
    fname = '_tmp%07d.png' % 1
    s = ml.imshow(xaxis, yaxis, u, figure=fig, vmin=vmin, vmax=vmax)
    #scale = 1./np.max(np.abs(u))
    u = u
    ml.axes(extent=[0, 1, 0, 1, 0, 2])
    ml.colorbar()
    ml.xlabel('x position')
    ml.ylabel('y position')
    ml.zlabel('wave amplitude')

    if savemovie == True:
        pl.ion()
        arr = ml.screenshot()
        img = pl.imshow(arr)
        pl.axis('off')

    for i in range(2, frames):

        u = np.load('solution_%06d.npy' % i)
        u = numpyfy(u, mesh, d_nodes, map)
        s.mlab_source.scalars = u
        fname = '_tmp%07d.png' % i
        if savemovie == True:
            arr = ml.screenshot()
            img.set_array(arr)
            pl.savefig(filename=fname)  #,figure=fig)
            print 'Saving frame', fname
            pl.draw()

    fig.scene.disable_render = False
    if savemovie:
        os.system(
            "mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg"
            % mvname)
    def test_imshow_colormap(self):
        # Check if the pipeline is refreshed when we change colormap.
        # See issue #262
        a = np.random.randint(0, 10 + 1, (100, 100))

        actor = mlab.imshow(a, colormap="cool")

        with self.assertTraitChanges(actor, 'pipeline_changed'):
            actor.module_manager.scalar_lut_manager.lut_mode = 'jet'
    def test_imshow_colormap(self):
        # Check if the pipeline is refreshed when we change colormap.
        # See issue #262
        a = np.random.randint(0, 10 + 1, (100, 100))

        actor = mlab.imshow(a, colormap="cool")

        with self.assertTraitChanges(actor, 'pipeline_changed'):
            actor.module_manager.scalar_lut_manager.lut_mode = 'jet'
Example #10
0
def test_quiver3d(a, b, c):
    dphi, dtheta = np.pi / 30.0, np.pi / 30.0
    [phi, theta] = np.mgrid[0:np.pi + dphi * 1.5:dphi,
                            0:2 * np.pi + dtheta * 1.5:dtheta]
    x = a * np.sin(phi) * np.cos(theta)
    y = b * np.sin(phi) * np.sin(theta)
    z = c * np.cos(phi)

    # outward pointing unit vectors
    u = x
    u = np.array([e / np.linalg.norm(e, ord=2) for e in u])
    v = y
    v = np.array([e / np.linalg.norm(e, ord=2) for e in v])
    w = z
    w = np.array([e / np.linalg.norm(e, ord=2) for e in w])

    obj = mlab.quiver3d(x, y, z, u, v, w, line_width=1, scale_factor=1)
    mlab.axes(obj)
    mlab.outline(obj)
    mlab.imshow(10)
    return obj
Example #11
0
def draw_layer(path, position):
    # load a png with a scale 0->1 and four color channels (an extra alpha channel for transparency).
    im = pl.imread(path, format='png') * 255

    colors = tvtk.UnsignedCharArray()
    colors.from_array(im.transpose((1, 0, 2)).reshape(-1, 4))

    m_image = mlab.imshow(
        np.ones(im.shape[:2]),
        extent=[0, 0, 0, 0, position, position],
        opacity=0.6)

    m_image.actor.input.point_data.scalars = colors
def mcrtmv(frames, dt,mesh, d_nodes, map, savemovie=False, mvname='test', vmin=-1, vmax=1):
	"""
	Creates move from numpyfied results in 2d, using mencoder. Prolly does not work on mac!
	"""


	size = 500,500
	
	fig = ml.figure(size= size, bgcolor=(1.,1.,1.));

	#fig.scene.anti_aliasing_frames=07

	#extent = [0,Nx-1,0,Ny-1,-30,30]
	xaxis = np.linspace(0,1,d_nodes[0]+1)
	yaxis = np.linspace(0,1,d_nodes[1]+1)
	ml.clf(figure=fig)
	u = np.load('solution_%06d.npy'%1);
	u = numpyfy(u, mesh, d_nodes, map)
	fname = '_tmp%07d.png' % 1
	s = ml.imshow(xaxis, yaxis, u,figure=fig,vmin=vmin, vmax=vmax)
	#scale = 1./np.max(np.abs(u))
	u = u
	ml.axes(extent=[0,1,0,1,0,2])
	ml.colorbar()
	ml.xlabel('x position')
	ml.ylabel('y position')
	ml.zlabel('wave amplitude')

	if savemovie == True:
		pl.ion()
		arr = ml.screenshot()
		img = pl.imshow(arr)
		pl.axis('off')
	
	for i in range(2,frames):

		u = np.load('solution_%06d.npy'%i);
		u = numpyfy(u, mesh, d_nodes, map)
		s.mlab_source.scalars = u
		fname = '_tmp%07d.png' % i
		if savemovie == True:
			arr = ml.screenshot()
			img.set_array(arr)
			pl.savefig(filename=fname)#,figure=fig)
			print 'Saving frame', fname
			pl.draw()

	fig.scene.disable_render = False
	if savemovie:
		os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname);
def mlab_color_imshow(image, **kwargs):
    '''Imshow with color in mlab
    Adapted from [1]
        [1] http://stackoverflow.com/a/24471211/5451259
    '''
    alpha = np.ones(image.shape[0] * image.shape[1]) * 255

    image_LUT_array = np.c_[image.reshape(-1, 3), alpha]
    image_LUT_array[:, 0], image_LUT_array[:, 2] = np.copy(image_LUT_array[:, 2]), np.copy(image_LUT_array[:, 0])
    LUT_lookup = np.arange(image.shape[0] * image.shape[1]).reshape(image.shape[0], image.shape[1])

    mlab_imshow = mlab.imshow(LUT_lookup, colormap='binary', **kwargs)
    mlab_imshow.module_manager.scalar_lut_manager.lut.table = image_LUT_array
    return mlab_imshow
Example #14
0
def draw_groundtrack_surface(scene):
    """Load the Earth Texture image as the surface
    """
    # set scene to have simple interactor
    scene.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain()
    surface_image = ndimage.imread('./data/earthmap1k.jpg')
    surface_image = np.rot90(surface_image[:, :, 0], -1)
    surface = mlab.imshow(surface_image,
                          figure=scene.mayavi_scene,
                          extent=[-180, 180, -90, 90, 0, 0])
    mlab.axes(surface,
              extent=[-180, 180, -90, 90, 0, 0],
              z_axis_visibility=False)

    return surface
def mlab_color_imshow(image, **kwargs):
    '''Imshow with color in mlab
    Adapted from [1]
        [1] http://stackoverflow.com/a/24471211/5451259
    '''
    alpha = np.ones(image.shape[0] * image.shape[1]) * 255

    image_LUT_array = np.c_[image.reshape(-1, 3), alpha]
    image_LUT_array[:, 0], image_LUT_array[:, 2] = np.copy(
        image_LUT_array[:, 2]), np.copy(image_LUT_array[:, 0])
    LUT_lookup = np.arange(image.shape[0] * image.shape[1]).reshape(
        image.shape[0], image.shape[1])

    mlab_imshow = mlab.imshow(LUT_lookup, colormap='binary', **kwargs)
    mlab_imshow.module_manager.scalar_lut_manager.lut.table = image_LUT_array
    return mlab_imshow
Example #16
0
def draw_map(height,width):
    import pylab as pl
    im = pl.imread('worldmap.png', format='png')

    l = []
    for i in im:
        x = []
        for j in i:
            tmp = 0
            for k in j: tmp += k
            x.append(k)
        l.append(x)
    ims = mlab.imshow(l, colormap = 'binary')
    print "Map shape", len(l),len(l[0])
    
    ims.actor.position = [height/2,(width)/2,0]
    ims.actor.scale = [float(height)/len(l),float(width)/len(l[0]),0]
Example #17
0
def mlab_imshow_color(img_array, **kwargs):
    """
    Plot a color image with mayavi.mlab.imshow.
    img_array is a ndarray with dim (n, m, 4) and scale (0->255]
    **kwargs is passed onto mayavi.mlab.imshow(..., **kwargs)
    """
    my_lut = pl.c_[img_array.reshape(-1, 4)]
    my_lut_lookup_array = pl.arange(img_array.shape[0] *
                                    img_array.shape[1]).reshape(
                                        img_array.shape[0], img_array.shape[1])

    the_imshow = mlab.imshow(my_lut_lookup_array, colormap='binary',
                             **kwargs)  # temporary colormap
    the_imshow.module_manager.scalar_lut_manager.lut.table = my_lut
    mlab.draw()

    return the_imshow
def _plot_img(img, K, T, z=0.1):
    obj = mlab.imshow(img.T)
    quat = tf.quaternion_from_matrix(T)
    angle, axis = angle_axis_from_quaternion(quat)
    obj.actor.rotate_wxyz(angle * 180 / np.pi, *axis)
    h, w = img.shape
    xmax_pixel, ymax_pixel = w, h
    point3d = projectionto3d(K, (xmax_pixel, ymax_pixel))[0]
    origin3d = projectionto3d(K, (0, 0))[0]
    point3d = point3d * z / point3d[2]
    origin3d = origin3d * z / origin3d[2]
    center3d = (point3d + origin3d) / 2.
    xmax, ymax, _ = point3d - origin3d
    obj.actor.scale = np.array([xmax / xmax_pixel, ymax / ymax_pixel, 1.0])
    obj.actor.position = utils.apply_transform(T, center3d)
    mlab.view(distance=20 * z)
    return obj
Example #19
0
    def _plot_imshow(self, im, alpha,
                     position=(0, 0, 0),
                     orientation=(0, 0, 0),
                     scale=1.0, **kwargs):
        """
        Plot a color image with mayavi.mlab.imshow.
        im is a ndarray with dim (n, m, 3) and scale (0->255]
        alpha is a single number or a ndarray with dim (n*m) and scale (0->255]
        **kwargs is passed onto mayavi.mlab.imshow(..., **kwargs)
        """
        if len(alpha.shape) != 1:
            alpha = alpha.flatten()

        # The lut is a Nx4 array, with the columns representing RGBA
        # (red, green, blue, alpha) coded with integers going from 0 to 255,
        # we create it by stacking all the pixles (r,g,b,alpha) as rows.
#         lut = np.c_[im.reshape(-1, 3), alpha] / 255.0
#         lut_lookup_array = np.arange(
#             im.shape[0] * im.shape[1]).reshape(im.shape[0], im.shape[1])

        # We can display an color image by using mlab.imshow, a lut color list and
        # a lut lookup table.
        # temporary colormap
#         imshow = mlab.imshow(lut_lookup_array,
#                              colormap='binary',
#                              **kwargs)

        colors = tvtk.UnsignedCharArray()
        im_shape = im.shape
        im_rgba = np.concatenate((im,
                                  alpha.reshape(im_shape[0], im_shape[1], 1)),
                                 axis=-1)
        im_rgba_T = im_rgba.transpose((1, 0, 2))
        colors.from_array(im_rgba_T.reshape(-1, 4))
        image = mlab.imshow(np.ones(im_rgba_T.shape[:2]))
        image.actor.input.point_data.scalars = colors

        image.actor.scale = (scale, scale, 1.0)
        image.actor.position = position
        image.actor.orientation = orientation
        #imshow.module_manager.scalar_lut_manager.lut.table = lut
        # print 'xxx'
        # imshow.module_manager.scalar_lut_manager.load_lut_from_list(lut)
        # print 'yyy'
        return image
Example #20
0
def plot(x, y, z, nx, ny):
    from mayavi import mlab
    mlab.figure(size=(600, 600))
    xmin, xmax = np.min(x.data), np.max(x.data)
    ymin, ymax = np.min(y.data), np.max(y.data)
    s = mlab.imshow(z.data.reshape((nx, ny)),
                    extent=[xmin, xmax, ymin, ymax, 0, 0],
                    colormap='jet')
    s.scene.z_plus_view()
    n = 2000
    dt = 4 * np.pi / n
    for i in range(n):
        julia(z, x, y, -dt * i)
        z.pull()
        s.mlab_source.scalars = z.data.reshape((nx, ny))
        if i % 3 == 0:
            mlab.process_ui_events()
    mlab.show()
Example #21
0
def mlab_imshowColor(im, alpha = 255, **kwargs):
    """
    Plot a color image with mayavi.mlab.imshow.
    im is a ndarray with dim (n, m, 3) and scale (0->255]
    alpha is a single number or a ndarray with dim (n*m) and scale (0->255]
    **kwargs is passed onto mayavi.mlab.imshow(..., **kwargs)
    """
    from tvtk.api import tvtk
    
    # Homogenous coordinate conversion
    im = np.concatenate((im, alpha * np.ones((im.shape[0], im.shape[1], 1), dtype = np.uint8)), axis = -1)
    colors = tvtk.UnsignedCharArray()
    colors.from_array(im.reshape(-1, 4))
    m_image = mlab.imshow(np.ones(im.shape[:2][::-1]))
    m_image.actor.input.point_data.scalars = colors
    
    mlab.draw()
    mlab.show()

    return
def plot_frustum(Rt_list, img_list, f):
    fig = mlab.figure(figure=None,
                      bgcolor=(0, 0, 0),
                      fgcolor=(1, 1, 1),
                      engine=None,
                      size=(1600, 1000))
    for i in range(len(Rt_list)):
        R = Rt_list[i][:3, :3]
        t = Rt_list[i][:3, 3]
        C = -np.dot(R.T, t)
        pp = np.array([0, 0, f])
        img = img_list[i][:, :, 1]
        euler = rotation_to_euler(R[:3, :3])
        obj = mlab.imshow(img.T, figure=fig)
        obj.actor.orientation = np.rad2deg(euler)
        obj.actor.position = (np.dot(R, pp) + t) + C
        # obj.actor.scale = [0.01, 0.01, 0.01]
        # center
    mlab.orientation_axes()
    mlab.show()
def setup_visu():
    # Create a Mayavi figure
    fig = mlab.figure('Ball tracking visualization')

    # Measurements have to be whole numbers
    TABLE_WIDTH = 152  # cm
    TABLE_LENGTH = 274  # cm
    table_structure = np.ones((TABLE_WIDTH, TABLE_LENGTH))

    # Draw out the lines on the table
    # Creases
    table_structure[1:-2, 1] = 0
    table_structure[1:-2, -2] = 0
    table_structure[1, 1:-2] = 0
    table_structure[-2, 1:-2] = 0

    # Center line
    table_structure[TABLE_WIDTH // 2, 1:-2] = 0

    # Representing net
    table_structure[1:-2, TABLE_LENGTH // 2 - 1] = 0.4
    table_structure[1:-2, TABLE_LENGTH // 2] = 0.4
    table_structure[1:-2, TABLE_LENGTH // 2 + 1] = 0.4

    # Create the table layout in the figure
    table = mlab.imshow(table_structure, colormap='Blues', opacity=0.6)

    # Setup a 3D point plotter with
    # proper shapes, ie., no. of points
    # for the ball and its trail
    x = y = z = s = np.zeros(5)
    point_plt = mlab.points3d(x, y, z, s, scale_factor=1, color=(1, 0.4, 0))

    # Put text to indicate table orientation
    mlab.text3d(0, TABLE_LENGTH // 2 + 10, -40, 'Player 1',
                scale=10, orient_to_camera=True)
    mlab.text3d(0, -(TABLE_LENGTH // 2 + 10), -40,
                'Player 2', scale=10, orient_to_camera=True)

    return point_plt.mlab_source
Example #24
0
def drawMap(mlab, scalars, mapFile):
    ''' 3d Visualization of the data
    Parameters
    ----------
    mlab : mlab
    scalars : 3d np array
    mapFile : str
    
    Returns
    -------
    imshow object
    '''
    # Get the shape of axes
    shape = scalars.shape
    height = shape[0]
    width = shape[1]
    
    im = pl.imread(mapFile, format = 'png')
    
    l = []
    for i in im:
        x = []
        for j in i:
            tmp = 0
            for k in j: tmp += k
            x.append(tmp)
        l.append(x)
        
    #ims = mlab.imshow(l, colormap = 'binary')
    ims = mlab.imshow(l)
    print "Map shape", len(l),len(l[0])
    
    ims.actor.position = [height/2,(width)/2,0]
    ims.actor.scale = [float(height)/len(l),float(width)/len(l[0]),0]
    
    return ims
Example #25
0
z = 100 * np.sin((x - x[0]) / 50)

c = mlab.plot3d(x, y, z, tube_radius=5, color=(1, 1, 0))
##c.visible = False

# ----------------------------------------------------------------------
# Part 4 - add surface

# Create a surface
x, y = np.ogrid[:n:4, :n:4]
z = 80 + (0.15 * (-x - 0.015 * x ** 2 + 0.3 * y + 0.01 * y ** 2)).astype(int)

s = mlab.surf(x, y, z, representation='surface', colormap='summer')
# Initially hide the surface.
##s.visible = False

# ----------------------------------------------------------------------
# Part 5 - Evaluate the data cube on the surface, and plot it.

# Do a simple linear interpolation to evaluate the data cube on the
# surface.
low_index = np.floor(z).astype(int)
hi_index = np.ceil(z).astype(int)
low_vals = data[x, y, low_index]
hi_vals = data[x, y, hi_index]
vals = low_vals + (z - low_index) * (hi_vals - low_vals)

# Make what is effectively a 2D image plot in another figure.
mlab.figure()
mlab.imshow(x, y, vals, colormap='RdBu')
Example #26
0
 def test_imshow(self):
     s = np.random.random((10, 10))
     # This should work.
     obj = mlab.imshow(s)
Example #27
0
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 21:54:55 2020

@author: lenovouser
"""

import numpy
from mayavi import mlab
s = numpy.random.random((10, 10))
img = mlab.imshow(s, colormap='gist_earth')
mlab.show()
Example #28
0
                         testPC[:, 1],
                         testPC[:, 2],
                         mode="point",
                         figure=fig)
    node.glyph.scale_mode = 'scale_by_vector'
    node.mlab_source.dataset.point_data.scalars = Colors0
    node = mlab.points3d(keyPts[:, 0],
                         keyPts[:, 1],
                         keyPts[:, 2],
                         scale_factor=PtSize,
                         figure=fig)
    node.glyph.scale_mode = 'scale_by_vector'
    node.mlab_source.dataset.point_data.scalars = keyColors0

    fig = mlab.figure(bgcolor=(0, 0, 0), size=(1640, 500))
    mlab.imshow(RespondImage)
    mlab.view(270, 0, 1800, [0, 0, 0])

    fig = mlab.figure(bgcolor=(0, 0, 0), size=(1640, 500))
    mlab.imshow(KeyPixelsImage)
    mlab.view(270, 0, 1200, [0, 0, 0])

    fig = mlab.figure(bgcolor=(0, 0, 0), size=(1640, 1500))
    node = mayavi.mlab.points3d(decodedPC[:, 0],
                                decodedPC[:, 1],
                                decodedPC[:, 2],
                                mode="point",
                                figure=fig)

    mlab.show()
Example #29
0
# basic handling of tiff 2D and 3D images
# import tif and convert to numpy array
# then visualize using mayavi2

#import os
#import sys
from mayavi import mlab

#sys.path.append('C:\\dropbox\\My Dropbox\\codes\\python')
import tifffile as tff

#blobs.tif is a 2D sample image
#tiffimg = tff.TIFFfile('D:/examples/blobs.tif')
tiffimg = tff.TIFFfile('D:/examples/g1f.tif')
#tiffimg = tff.TIFFfile('D:\\examples\\flybrain3DG.tif')
#tiffimg = tff.TIFFfile('D:/examples/flybrain3DG.tif')

imgarray = tiffimg.asarray()

# showing 2D array (blobs) as a 2D plot in mayavi. 
imgwin = mlab.imshow(imgarray, colormap="gist_earth")

# showing 3D stack image 
#mlab.pipeline.volume(mlab.pipeline.scalar_field(imgarray))
 def test_imshow(self):
     s = np.random.random((10, 10))
     # This should work.
     obj = mlab.imshow(s)
# Plot the data
from mayavi import mlab

# A first plot in 3D
fig = mlab.figure(1)
mlab.clf()
mesh = mlab.mesh(x, y, z, scalars=s)
cursor3d = mlab.points3d(0., 0., 0., mode='axes',
                                color=(0, 0, 0),
                                scale_factor=0.5)
mlab.title('Sousa')

# A second plot, flat
fig2d = mlab.figure(2)
mlab.clf()
im = mlab.imshow(s)
cursor = mlab.points3d(0, 0, 0, mode='2dthick_cross',
                                color=(0, 0, 0),
                                scale_factor=10)
mlab.view(90, 0)

################################################################################
# Some logic to select 'mesh' and the data index when picking.

def picker_callback(picker_obj):
    picked = picker_obj.actors
    if mesh.actor.actor._vtk_obj in [o._vtk_obj for o in picked]:
        # m.mlab_source.points is the points array underlying the vtk
        # dataset. GetPointId return the index in this array.
        x_, y_ = np.lib.index_tricks.unravel_index(picker_obj.point_id,
                                                                s.shape)
# 10 contour lines (equally spaced contour levels) together with surf.
# Black color for contour lines.
plt.figure(7, fgcolor=(.0, .0, .0), bgcolor=(1.0, 1.0, 1.0))
plt.surf(xv, yv, hv, warp_scale=0.01)
plt.contour_surf(xv, yv, hv, contours=10, color=(0., 0., 0.), \
                 warp_scale=0.01)

# Specify the contour levels explicitly as a list.
plt.figure(8, fgcolor=(.0, .0, .0), bgcolor=(1.0, 1.0, 1.0))
levels = [500., 1000., 1500., 2000.]
plt.contour_surf(xv, yv, hv, contours=levels, warp_scale=0.01)

# View the contours by displaying as an image.
plt.figure(9, fgcolor=(.0, .0, .0), bgcolor=(1.0, 1.0, 1.0))
plt.imshow(hv)
#end contourplots


# Define a coarser grid for the vector field
x2 = y2 = np.linspace(-10.,10.,11)
x2v, y2v = np.meshgrid(x2, y2, indexing='ij', sparse=False)
h2v = h0/(1 + (x2v**2 + y2v**2)/(R**2)) # Surface on coarse grid
# endcoarsergrid

dhdx, dhdy = np.gradient(h2v)
# endgradient



# Draw contours and gradient field of h
Example #33
0
"""
Script to generate the preview images for the mayavi2 LUTs.

Requires ImageMagick.
"""
import os

from mayavi import mlab
from mayavi.core.lut_manager import lut_mode_list, lut_image_dir

import numpy as np

# Create some data
X = np.arange(0, 255)
X = X * np.ones((200, 1))

mlab.clf()
image = mlab.imshow(X.T)
mlab.view(0, 0, 118)
# Make a preview for each possible lut
for lut in lut_mode_list():
    filebasename = os.path.join(lut_image_dir, lut.lower())
    if not lut == 'file':
        image.module_manager.scalar_lut_manager.lut_mode = lut
        mlab.savefig(filebasename + '.png', size=(80, 20))
        #os.system('convert %s.png %s.gif &' %(filebasename, filebasename))
        os.system('montage -geometry -0-0 -label "%s"  %s.png   %s.gif &'
                        % (lut, filebasename, filebasename) )
Example #34
0
    # PtSize = 0.1
    # node = mlab.points3d(ExtendedKeyPts[:,0], ExtendedKeyPts[:,1], ExtendedKeyPts[:,2], scale_factor=PtSize, figure=fig)
    # node.glyph.scale_mode = 'scale_by_vector'
    # node.mlab_source.dataset.point_data.scalars = ExtendedKeyColors
    
    #PtSize = 0.1
    #node = mlab.points3d(PlanarPts[:,0], PlanarPts[:,1], PlanarPts[:,2], scale_factor=PtSize, figure=fig)
    #node.glyph.scale_mode = 'scale_by_vector'
    #node.mlab_source.dataset.point_data.scalars = PlanarColors
    #
    #mlab.quiver3d(PlanarPts[:,0], PlanarPts[:,1], PlanarPts[:,2], \
    #                     PlanarPts[:,3], PlanarPts[:,4], PlanarPts[:,5], \
    #                     figure=fig, line_width=0.5, scale_factor=1)
    
    fig = mlab.figure(bgcolor=(0, 0, 0), size=(1640, 500))
    mlab.imshow(RangeImage)    
    mlab.view(270, 0, 1800, [0,0,0])
    
    
    
    mlab.show()
    
    
     






print('cntkeyPts =', KeyPts.shape[0])
t1 = time()
print(round(t1 - t0, 2), 's, GetKeyPixels')

#t5 = time()
#print(round(t5-t4, 2), 's')

color0 = np.ones((PC.shape[0], 1), dtype=np.float32) * 0.0
color3 = np.ones((KeyPts.shape[0], 1), dtype=np.float32) * 0.9

#fig = mlab.figure(bgcolor=(0, 0, 0), size=(1640, 500))
#mlab.imshow(SphericalRingImage)
#mlab.view(270, 0, 1200, [0,0,0])

fig = mlab.figure(bgcolor=(0, 0, 0), size=(1640, 500))
mlab.imshow(RespondImage)
mlab.view(270, 0, 1200, [0, 0, 0])

fig = mayavi.mlab.figure(bgcolor=(0, 0, 0), size=(1640, 1500))
node_PC = mayavi.mlab.points3d(PC[:, 0],
                               PC[:, 1],
                               PC[:, 2],
                               mode="point",
                               figure=fig)
node_PC.mlab_source.dataset.point_data.scalars = color0

node_KeyPC = mayavi.mlab.points3d(KeyPts[:, 0],
                                  KeyPts[:, 1],
                                  KeyPts[:, 2],
                                  scale_factor=0.15,
                                  figure=fig)
 def test_imshow_extent(self):
     mlab.imshow(np.random.rand(10, 20), extent=[-1, 11, -1, 21, 0, 0])
u=numpy.zeros((N,N), dtype=float)
v=numpy.zeros((N,N), dtype=float)
u_y=numpy.zeros((N,N), dtype=float)
v_x=numpy.zeros((N,N), dtype=float)
omega=numpy.zeros((N,N), dtype=float)
# Initial conditions
for i in range(len(x)):
    for j in range(len(y)):
        u[i][j]=numpy.sin(2*math.pi*x[i])*numpy.cos(2*math.pi*y[j])
        v[i][j]=-numpy.cos(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j])
        u_y[i][j]=-2*math.pi*numpy.sin(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j])
        v_x[i][j]=2*math.pi*numpy.sin(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j])
        omega[i][j]=v_x[i][j]-u_y[i][j]

src = mlab.imshow(xx,yy,omega,colormap='jet')
mlab.scalarbar(object=src)
mlab.xlabel('x',object=src)
mlab.ylabel('y',object=src)


# Wavenumber
k_x = 2*math.pi*numpy.array([complex(0,1)*n for n in range(0,N/2) \
+ [0] + range(-N/2+1,0)])
k_y=k_x

kx=numpy.zeros((N,N), dtype=complex)
ky=numpy.zeros((N,N), dtype=complex)
kxx=numpy.zeros((N,N), dtype=complex)
kyy=numpy.zeros((N,N), dtype=complex)
ridge0 = final[789]
mlab.points3d(ridge0[:,0],ridge0[:,1],ridge0[:,2],4*ones(size(ridge0)/3),resolution=16,scale_factor=1,color=(0,0,0))


ridge1 = final[780]
mlab.points3d(ridge1[:,0],ridge1[:,1],ridge1[:,2],4*ones(size(ridge1)/3),resolution=16,scale_factor=1,color=(1,0,0))




filename = 'shellstack215.tif'
image1 = io.imread(filename)
image[image<12000]=False


obj = mlab.imshow(image1[0:,0:].T, opacity = .3, transparent = True)

#obj.actor.orientation = [0, 0, 0] # the required orientation 
obj.actor.position = [shape(image1)[0]/2.+20, shape(image1)[1]/2.-20, 215] # the required  position 
#obj.actor.scale = [0, 0, 0]


filename = 'shellstack345.tif'
image2 = io.imread(filename)
image[image<12000]=False


obj = mlab.imshow(image2[0:,0:].T, opacity = .3, transparent=True)

#obj.actor.orientation = [0, 0, 0] # the required orientation 
obj.actor.position = [shape(image2)[0]/2.+20, shape(image2)[1]/2.-20, 345] # the required  position 
Example #39
0
import numpy as np
from mayavi import mlab
#SHA3 state vizualizer
#1600 bit block size
#5 x 5 x 64 array
#this input string does not represent a message, but instead a value already stored in the state about to be fed through the permutation function
inString = "1100111010000001000010010101001110101010111011100010001101111000111111110000010111000111001101010101001010000111000010000001111001101101011011001111010101100001101111110011101011011110001100000000100100101011011101111101100001110110001001010100101001110101010110100110001100001001111000110110101100110111101111100100100111010110110111011110111011100101000011110010111100011100010111000101110001111101111101100101110011010110010111111010110101000110011101101111111010101101111100010011111101100101100111100100110011100101100011100011100101100111011010000110011000011010100101110100010101110010101000100001100101111010001110000000010101010110110010111100100000010000010101011011110011110111001111111001001000000100111110010101101001101110000011010000000011110110001101100110110001010110100000011000101011110101110011010101111101110101000110101100000100100111101000110100101010101001010011110011000100001100110101011100101001111100111010100101010100000110100111100011100000101110000010010001100011101010011101010010101110001011111110100110100110000001111011010010010100100011000000001111100111000100011110000001011011110010011101011001000110111000010010110001110010011101111000100101000100110011001001000011010011101110011111110000111011101011000011011111011101101101000011101110101010101101101000000101110110010101111001110101111011100110011110100100111110001001001010110111000100110010011001101000000100100111011101111111111110010011111001001111100011101011111001001101101011101000011010110100110111100011110100101111100011011000000001110000100101111110000001111001011100110110001001001010011100010101"
stateOneDimensionalList = list(inString)
#convert to digits from characters
for index in range(0, len(stateOneDimensionalList)):
    stateOneDimensionalList[index] = int(stateOneDimensionalList[index])
state = []
stateIterator = 0
for i in range(0, 64):
    twoDSlice = []
    for j in range(0, 5):
        oneDSlice = []
        for k in range(0, 5):
            oneDSlice.append(stateOneDimensionalList[stateIterator])
            stateIterator += 1
        twoDSlice.append(oneDSlice)
    state.append(twoDSlice)
stateNumpyArray = np.array(state)
print stateNumpyArray
print stateNumpyArray.shape
frame = 0
for i in stateNumpyArray:
    mlab.imshow(i, interpolate=False)
    mlab.savefig("frame" + str(frame) + ".png")
    frame += 1
Example #40
0
        sys.exit(-1)

data.shape = shape

nx = shape[0]
ny = shape[1]
nz = shape[2]

dx = nx / 2 + 1
dy = ny / 2 + 1
dz = nz / 2 + 1

if hslice:
    amp = np.sqrt(data[:, :, dz, 0]**2 + data[:, :, dz, 1]**2 +
                  data[:, :, dz, 2]**2)
    mlab.imshow(amp, opacity=0.6, reset_zoom=False)

mlab.quiver3d(data[:, :, :, 0],
              data[:, :, :, 1],
              data[:, :, :, 2],
              mask_points=mask_points,
              scale_factor=scale_factor,
              extent=[-dx, dx, -dy, dy, -dz, dz])

if axes:
    mlab.axes()

if colorbar:
    mlab.vectorbar()

mlab.show()
def plot_events(xs,
                ys,
                ts,
                ps,
                save_path=None,
                num_compress='auto',
                num_show=1000,
                event_size=2,
                elev=0,
                azim=45,
                imgs=[],
                img_ts=[],
                show_events=True,
                show_frames=True,
                show_plot=False,
                crop=None,
                compress_front=False,
                marker='.',
                stride=1,
                invert=False,
                img_size=None,
                show_axes=False,
                ts_scale=100000):
    """
    Given events, plot these in a spatiotemporal volume.
    :param: xs x coords of events
    :param: ys y coords of events
    :param: ts t coords of events
    :param: ps p coords of events
    :param: save_path if set, will save plot to here
    :param: num_compress will take this number of events from the end
        and create an event image from these. This event image will
        be displayed at the end of the spatiotemporal volume
    :param: num_show sets the number of events to plot. If set to -1
        will plot all of the events (can be potentially expensive)
    :param: event_size sets the size of the plotted events
    :param: elev sets the elevation of the plot
    :param: azim sets the azimuth of the plot
    :param: imgs a list of images to draw into the spatiotemporal volume
    :param: img_ts a list of the position on the temporal axis where each
        image from 'imgs' is to be placed (the timestamp of the images, usually)
    :param: show_events if False, will not plot the events (only images)
    :param: crop a list of length 4 that sets the crop of the plot (must
        be in the format [top_left_y, top_left_x, height, width]
    """
    print("plot all")
    #Crop events
    if img_size is None:
        img_size = [max(ys), max(ps)] if len(imgs) == 0 else imgs[0].shape[0:2]
    crop = [0, img_size[0], 0, img_size[1]] if crop is None else crop
    xs, ys, ts, ps = clip_events_to_bounds(xs,
                                           ys,
                                           ts,
                                           ps,
                                           crop,
                                           set_zero=False)
    xs, ys = xs - crop[2], ys - crop[0]

    #Defaults and range checks
    num_show = len(xs) if num_show == -1 else num_show
    skip = max(len(xs) // num_show, 1)
    print("Has {} events, show only {}, skip = {}".format(
        len(xs), num_show, skip))
    num_compress = len(xs) if num_compress == -1 else num_compress
    num_compress = min(img_size[0] * img_size[1] * 0.5,
                       len(xs)) if num_compress == 'auto' else num_compress
    xs, ys, ts, ps = xs[::skip], ys[::skip], ts[::skip], ps[::skip]

    t0 = ts[0]
    ts = ts - t0

    #mlab.options.offscreen = True

    #Plot images
    if len(imgs) > 0 and show_frames:
        for imgidx, (img, img_t) in enumerate(zip(imgs, img_ts)):
            img = img[crop[0]:crop[1], crop[2]:crop[3]]

            mlab.imshow(img,
                        colormap='gray',
                        extent=[
                            0, img.shape[0],
                            0, img.shape[1], (img_t - t0) * ts_scale,
                            (img_t - t0) * ts_scale + 0.01
                        ],
                        opacity=1.0,
                        transparent=False)

    colors = [0 if p > 0 else 240 for p in ps]
    ones = np.array([0 if p == 0 else 1 for p in ps])
    p3d = mlab.quiver3d(ys,
                        xs,
                        ts * ts_scale,
                        ones,
                        ones,
                        ones,
                        scalars=colors,
                        mode='sphere',
                        scale_factor=event_size)
    p3d.glyph.color_mode = 'color_by_scalar'
    p3d.module_manager.scalar_lut_manager.lut.table = colors
    #mlab.draw()

    #mlab.view(84.5, 54, 5400, np.array([ 187,  175, 2276]), roll=95)

    if show_plot:
        mlab.show()
Example #42
0
    tries = 0
    # ]:
    for outOrder in outorders[2:3]:
        for R in RList:
            print 'R', R
            for vector, color in zip([[100, 0, 0], [0, 100, 0], [0, 0, 100]],
                                     [(1., 0., 0.), (0., 1., 0.), (0., 0., 1.)]):
                c = pl.c_[[0, tries * 1000, ii * 1000]]
                if ii == 0 and tries == 0:
                    vector = pl.r_[vector] * 5  # point out the first vector
                lin = R_orig.dot(pl.c_[[0, 0, 0], vector]) + c
                mlab.plot3d(*lin,
                            color=color,
                            tube_radius=5)

            lin3D = mlab.imshow(im, colormap="gray")
            print 'inOrder', inOrder
            rxyz = pl.array(
                euler_from_matrix(R, inOrder)) * 180 / pl.pi
            print 'outOrder', outOrder
            i, j, k = outOrder
            print 'o', [rxyz[i], rxyz[j], rxyz[k]]

            lin3D.actor.orientation = [rxyz[i], rxyz[j], rxyz[k]]
            lin3D.actor.position = c.flatten()
            lin3D.actor.scale = (6, 6, 1)
            tries += 1


mlab.draw()
mlab.show()
Example #43
0
 def test_imshow_extent(self):
     mlab.imshow(np.random.rand(10, 20), extent=[-1, 11, -1, 21, 0, 0])
 def plot_colorbar(min_q, max_q, max_val=0.35, num_interp=100, width=25):
     """ Plot a colorbar """
     vals = np.linspace(0, max_val, num=num_interp)
     vals = vals[:,np.newaxis]
     image = np.tile(vals, [1, width])
     mv.imshow(image, colormap='hsv')
Example #45
0
def draw_poses(title,
               parents,
               pose_sequence,
               frame_paths=None,
               fps=50 / 3.0,
               crossover=None):
    T, _, J = pose_sequence.shape
    fig = mlab.figure()

    xmin, ymin = pose_sequence.min(axis=0).min(axis=1)
    xmax, ymax = pose_sequence.max(axis=0).max(axis=1)
    # ax.set_xlim(xmin, xmax)
    # ax.set_zlim(ymin, ymax)
    # ax.set_ylim(0, T/fps)
    # # ax.set_aspect('equal')
    # ax.invert_zaxis()

    if frame_paths:
        # Decide on plot indices ahead of time. Main constraints are:
        # - I don't want more than five frames in a 1s time period.
        # - I'd like to display the first and last frames
        inner_seconds = int(np.floor((T - 2) / fps))
        num_keyframes = min(T - 2, inner_seconds * 5) + 2
        skip = int(np.round(float(T) / num_keyframes))
        keyframe_inds = np.arange(0, T, skip)
        if keyframe_inds[-1] != T - 1:
            keyframe_inds = np.concatenate([keyframe_inds, [T - 1]])
        keyframe_inds = set(keyframe_inds)

    print('Keyframe inds: ', keyframe_inds)

    for t in range(T):
        # plot joints
        pose_xy_j = pose_sequence[t]
        depth = 10 * float(t) / fps
        for joint in range(1, len(parents)):
            joint_coord = pose_xy_j[:, joint]
            parent = parents[joint]
            parent_coord = pose_xy_j[:, parent]
            if (parent_coord == joint_coord).all():
                # mayavi will complain if we plot this zero-length line
                continue
            x_data = np.array((parent_coord[0], joint_coord[0]), dtype='int16')
            z_data = np.array((parent_coord[1], joint_coord[1]), dtype='int16')
            depth_data = np.full_like(x_data, depth, dtype='int16')
            x_data = np.array((parent_coord[0], joint_coord[0]))
            z_data = np.array((parent_coord[1], joint_coord[1]))
            depth_data = np.full_like(x_data, depth)
            mlab.plot3d(x_data, depth_data, z_data)

        # plot frame (TODO: only plot frames occasionally; don't want to overdo
        # it and make the plot unreadable)
        if frame_paths and t in keyframe_inds:
            im = imread(frame_paths[t])
            # mayavi wants a 2D array of integers instead of a real image; it
            # looks up colours in a colourmap
            im2d = np.arange(np.prod(im.shape[:2])).reshape(im.shape[:2])
            cmap = im.reshape((im.shape[0] * im.shape[1], im.shape[2]))
            # add alpha channel
            cmap = np.concatenate(
                [cmap, np.full((cmap.shape[0], 1), 255, dtype='uint8')],
                axis=1)
            assert cmap.dtype == np.uint8
            # extent = [xmin, xmax, ymin, ymax, zmin, zmaax]
            extent = np.array([0, im.shape[1], depth, depth, 0, im.shape[0]])
            ims = mlab.imshow(im2d,
                              colormap='binary',
                              extent=extent,
                              opacity=0.5)
            # Documentation? What's that?
            # http://stackoverflow.com/a/24471211
            ims.module_manager.scalar_lut_manager.lut.table = cmap
            mlab.draw()

        # TODO:
        # - Back-connection to previous frames
        # - Thicken original pose tubes relative to back-connections
        # - Add crossover colour for predictions
        # - Make surex/y/z are going in the right direction, and that camera is
        #   in the right place
        # - Maybe plot action labels

    return fig
Example #46
0
 def draw(self):
     sz = self.size
     anc = self.anchor
     mlab.imshow(self.cur,
                 extent=[anc[0], sz[0], anc[1], sz[1], anc[2], sz[2]],
                 colormap='gist_earth')
byold=numpy.zeros((N,N), dtype=float)


# Initial conditions
for i in range(len(x)):
    for j in range(len(y)):
        u[i][j]=numpy.sin(2*math.pi*x[i])*numpy.cos(2*math.pi*y[j])
        v[i][j]=-numpy.cos(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j])
        u_y[i][j]=-2*math.pi*numpy.sin(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j])
        v_x[i][j]=2*math.pi*numpy.sin(2*math.pi*x[i])*numpy.sin(2*math.pi*y[j])
        omega[i][j]=v_x[i][j]-u_y[i][j]
	theta[i][j]=numpy.exp(-2.0*((4*math.pi*(x[i]-0.3))**2+(4*math.pi*(y[j]-0.3))**2))
	alpha[i][j]=numpy.sin(4*math.pi*x[i])*numpy.cos(6*math.pi*y[j])


src = mlab.imshow(xx,yy,theta,colormap='jet')
mlab.scalarbar(object=src)
mlab.xlabel('x',object=src)
mlab.ylabel('y',object=src)


# Wavenumber
k_x = 2*math.pi*numpy.array([complex(0,1)*n for n in range(0,N/2) \
+ [0] + range(-N/2+1,0)])
k_y=k_x

kx=numpy.zeros((N,N), dtype=complex)
ky=numpy.zeros((N,N), dtype=complex)
kxx=numpy.zeros((N,N), dtype=complex)
kyy=numpy.zeros((N,N), dtype=complex)
Example #48
0
def plot3d(data,
           xvar,
           yvar,
           zvar,
           fvar,
           ival='Dive',
           day=None,
           filament=None,
           cmap='RdYlBu',
           rev_cmap=True,
           alpha=1,
           cmin=None,
           cmax=None,
           title='',
           temp=None,
           chl=None,
           intdat=None):
    """
    Create 3D curtain plot

    Parameters
    ----------
    data : dataframe
        Pandas dataframe containing the needed data.
    xvar : character
        Name of the x axis variable, in the data dataframe (normally lon - or however longitude is name in the dataframe) .
    yvar : character
        Name of the y axis variable, in the data dataframe  (normally lat - or however latitude is name in the dataframe) .
    zvar : character
        Name of the z axis variable, in the data dataframe (normally a rounded Depth or Pressure value).
    fvar : character
        Name of the variable used for the filling (for example temperature, salinity, Sv1000 or whtaever you want it to be).
    ival : character, optional
        This is a grouping value, if not using 'Dive', make sure to define it. The default is 'Dive'.
    day : dataframe, optional
        Reference to a dataframe containing day/night information, if defined, this will put a bar on top of the plot. The default is None.
    filament : dataframe, optional
        This will put a bar below the plot, for example to delimit certain regions. The default is None.
    cmap : colormap, optional
        Character describing a valid colormap. The default is 'RdYlBu'.
    rev_cmap : boolean, optional
        Define if the colormap should be reversed. The default is True.
    alpha : float, optional
        Sets the transparenct. The default is 1.
    cmin : float, optional
        Define the color scale minimum. The default is None.
    cmax : float, optional
        Define the color scale maximum. The default is None.
    title : character, optional
        Add a title to the plot. The default is ''.
    temp : TYPE, optional
        Add temperature background map. The default is None.
    chl : TYPE, optional
        Add chlorophyll background map. The default is None.
    intdat : TYPE, optional
        DESCRIPTION. The default is None.

    Returns
    -------
    None.

    """
    ne = 0
    #bring x,y,z data into shape, create 3 pivot tables
    x = pd.pivot(data=data.reset_index(),
                 index=ival,
                 columns=zvar,
                 values=xvar)
    y = pd.pivot(data=data.reset_index(),
                 index=ival,
                 columns=zvar,
                 values=yvar)
    z = -pd.pivot(
        data=data.reset_index(), index=ival, columns=zvar, values=zvar)

    #create pivot table with fill value, where ival become the index
    fill = pd.pivot(data=data.reset_index(),
                    index=ival,
                    columns=zvar,
                    values=fvar)

    #define cmax and cmin if they are not given
    if cmax is None:
        cmax = np.ceil(np.nanmax(fill))
    if cmin is None:
        cmin = np.floor(np.nanmin(fill))

    #create a mayavi figure
    fig = mlab.figure(size = (2048,1526),\
                bgcolor = (1,1,1), fgcolor = (0.5, 0.5, 0.5), figure=title)

    #create a mesh from the x,y,z and fill info
    svp = mlab.mesh(x,
                    y,
                    z,
                    scalars=fill,
                    colormap=cmap,
                    opacity=alpha,
                    extent=[0.2, 1, 0.1, 1, 0.22, .69],
                    figure=fig,
                    representation='surface')

    #reverse color map if needed
    if rev_cmap == True:
        svp.module_manager.scalar_lut_manager.reverse_lut = True
    #set color range
    svp.module_manager.scalar_lut_manager.data_range = (cmin, cmax)
    #svp.module_manager.scalar_lut_manager.use_below_range_color = True
    #svp.module_manager.scalar_lut_manager.below_range_color = (0,0,0,0)
    #svp.module_manager.scalar_lut_manager.lut.number_of_colors = 64

    #add colorbar
    cb = mlab.colorbar(object=svp, title=title, orientation='vertical')
    cb.scalar_bar.unconstrained_font_size = True
    cb.label_text_property.font_size = 20
    cb.title_text_property.font_size = 46

    #make plot window
    mlab.gcf()

    #set plot limits
    xmin = x.values[np.isfinite(x.values)].min()
    xmax = x.values[np.isfinite(x.values)].max()
    ymin = y.values[np.isfinite(y.values)].min()
    ymax = y.values[np.isfinite(y.values)].max()
    zmin = z.values[np.isfinite(z.values)].min()
    zmax = z.values[np.isfinite(z.values)].max()

    #change the aesthetics
    ax = mlab.axes(nb_labels=5,
                   xlabel='Longitude',
                   ylabel='Latitude',
                   zlabel='Depth [m]',
                   ranges=[xmin, xmax, ymin, ymax, zmin, zmax])
    ax.axes.font_factor = 0.5
    ax.axes.label_format = '    %6.2f'

    #add day night at top
    if day is not None:
        lut = np.zeros((2, 4))
        lut[1, :] = [0, 0, 0, 100]
        lut[0, :] = [100, 100, 0, 100]
        p3d = mlab.plot3d(day.lon.values,
                          day.lat.values,
                          day['depth'].values,
                          day['numSun'].values,
                          tube_radius=0.001,
                          figure=fig,
                          opacity=1,
                          extent=[0.2, 1, 0.1, 1, 0.695, 0.71])
        p3d.module_manager.scalar_lut_manager.lut.number_of_colors = 2
        p3d.module_manager.scalar_lut_manager.lut.table = lut

    #add line at bottom of plot
    if filament is not None:
        mlab.plot3d(filament.lon.values,
                    filament.lat.values,
                    filament['fildep'].values,
                    filament['numfil'].values,
                    tube_radius=0.01,
                    figure=fig,
                    opacity=1,
                    extent=[0.2, 1, 0.1, 1, 0.19, 0.21],
                    colormap='Set1')

    #add chl background map
    if chl is not None:
        if ne == 0:
            zl = 0.2
        else:
            zl = 0.72
        ne += 1
        x1 = chl.longitude.values.min()
        x2 = chl.longitude.values.max()
        y1 = chl.latitude.values.min()
        y2 = chl.latitude.values.max()
        dx = xmax - xmin
        dy = ymax - ymin
        xl1 = -(xmin - x1) / dx
        xl2 = -(xmax - x2) / dx
        yl1 = -(ymin - y1) / dy
        yl2 = -(ymax - y2) / dy

        zs = pd.pivot_table(data=chl,
                            index='latitude',
                            columns='longitude',
                            values='chlorophyll').transpose()
        #cmap2 =  matplotlib.cm.get_cmap()
        #cmap2.set_bad('white',1.)
        sat1 = mlab.imshow(
            zs,
            figure=fig,
            extent=[0.2 + xl1, 1 + xl2, 0.1 + yl1, 1 + yl2, zl, zl],
            opacity=0.8,
            colormap=cmap,
            interpolate=False)
        sat1.module_manager.scalar_lut_manager.reverse_lut = True
        sat1.module_manager.scalar_lut_manager.data_range = (0, 10)
        sat1.module_manager.scalar_lut_manager.lut.nan_color = (0, 0, 0, 0)
        cb2 = mlab.colorbar(object=sat1,
                            title='CHla',
                            orientation='horizontal')
        cb2.scalar_bar.unconstrained_font_size = True
        cb2.label_text_property.font_size = 20
        cb2.title_text_property.font_size = 46

    #add temp backgorund map
    if temp is not None:
        if ne == 0:
            zl = 0.2
        else:
            zl = 0.72
        ne += 1

        x1 = temp.longitude.values.min()
        x2 = temp.longitude.values.max()
        y1 = temp.latitude.values.min()
        y2 = temp.latitude.values.max()
        dx = xmax - xmin
        dy = ymax - ymin
        xl1 = -(xmin - x1) / dx
        xl2 = -(xmax - x2) / dx
        yl1 = -(ymin - y1) / dy
        yl2 = -(ymax - y2) / dy

        zs2 = pd.pivot_table(data=temp,
                             index='latitude',
                             columns='longitude',
                             values='sst').transpose()
        sat2 = mlab.imshow(
            zs2,
            figure=fig,
            extent=[0.2 + xl1, 1 + xl2, 0.1 + yl1, 1 + yl2, zl, zl],
            colormap=cmap,
            opacity=0.8,
            interpolate=False)
        sat2.module_manager.scalar_lut_manager.reverse_lut = True
        sat2.module_manager.scalar_lut_manager.lut.nan_color = (0, 0, 0, 0)
        #sat2.module_manager.scalar_lut_manager.data_range = (10, 25)

    #ignore this, as this was specific for the 38 kHz map for calibration
    if intdat is not None:
        x1 = intdat.Lon_S.values.min()
        x2 = intdat.Lon_S.values.max()
        y1 = intdat.Lat_S.values.min()
        y2 = intdat.Lat_S.values.max()
        dx = xmax - xmin
        dy = ymax - ymin
        xi1 = -(xmin - x1) / dx
        xi2 = -(xmin - x2) / dx
        yi1 = -(ymin - y1) / dy
        yi2 = -(ymin - y2) / dy

        xi = pd.pivot(data=intdat,
                      index='Ping_S',
                      columns='Depth_mean',
                      values='Lon_S')
        yi = pd.pivot(data=intdat,
                      index='Ping_S',
                      columns='Depth_mean',
                      values='Lat_S')
        zi = pd.pivot(data=intdat,
                      index='Ping_S',
                      columns='Depth_mean',
                      values='Depth_mean')

        filli = pd.pivot(data=intdat,
                         index='Ping_S',
                         columns='Depth_mean',
                         values='Sv38')

        ivp = mlab.mesh(xi,
                        yi,
                        zi,
                        scalars=filli,
                        colormap=cmap,
                        opacity=alpha,
                        extent=[xi1, xi2, yi1, yi2, 0.2, .7],
                        figure=fig,
                        representation='surface')
        if rev_cmap == True:
            ivp.module_manager.scalar_lut_manager.reverse_lut = True
        ivp.module_manager.scalar_lut_manager.data_range = (cmin, cmax)

    #set initial view
    mlab.view(90, 110, -2)