示例#1
0
def anim():
    fig = mlab.gcf()
    fig.scene.movie_maker.record = True
    mlab.figure(figure=fig, bgcolor=(0.005, 0.005, 0.005))
    i = 0
    while i < 60:
        mlab.move(forward=-2)
        fig.scene.render()
        i = i + 1
        yield
    i = 0
    while i < 5:
        i = i + 1
        yield
    i = 0
    while i < 45:
        mlab.view(azimuth=180 + i * 2, elevation=130 - i)
        fig.scene.render()
        i = i + 1
        yield
    i = 0
    while i < 5:
        i = i + 1
        yield
    i = 0
    while i < 45:
        mlab.view(azimuth=270 + i * 2, elevation=85 - 2 * i)
        mlab.move(forward=-0.1)
        fig.scene.render()
        i = i + 1
        yield
    i = 0
    while i < 15:
        i = i + 1
        yield
示例#2
0
 def set_figure(self, fig, fname=None):
     #ax.set_aspect('equal')
     #set_axes_equal(ax)
     #ax.autoscale_view(tight=True)
     #ax.set_xlim([-125, 125])
     #ax.set_ylim([-125, 125])
     #ax.set_zlim([-220, 30])
     #plt.axis('off')
     #plt.show()
     mlab.move([-517.16728532, -87.0711504, 5.60826224],
               [1.35691603e+01, -2.84217094e-14, -1.06547500e+02])
     mlab.view(-170.68320804213343, 78.220729198686854, 549.40101471336777,
               [1.35691603e+01, 0.0, -1.06547500e+02])
     if not fname is None: mlab.savefig(fname, figure=fig)
     mlab.show(stop=True)
 def legal_actions(self):
     actions = [0] * self.action_space()
     #abbreviate actions_index_dict to d
     d = self.actions_index_dict
     
     #Set turning to be legal if they are availabe actions
     if d[Action.CW] != None:
         actions[d[Action.CW]] = 1
     if d[Action.CCW] != None:
         actions[d[Action.CCW]] = 1
     if d[Action.STAY] != None:
         actions[d[Action.STAY]] = 1
         
     pos,focal = mlab.move()
     v = focal - pos
     v = np.asarray((v[0],v[1]))
     v /= np.linalg.norm(v)
     w = np.asarray((-v[1],v[0]))
     pos = np.asarray((pos[0],pos[1]))
     
     #left
     if self.state(*(self.move_distance * w + pos)) != State.ILLEGAL and d[Action.LEFT] != None:
         actions[d[Action.LEFT]] = 1
     #right
     if self.state(*(self.move_distance * -w + pos)) != State.ILLEGAL and d[Action.RIGHT] != None:
         actions[d[Action.RIGHT]] = 1
     #forwards
     if self.state(*(self.move_distance * v + pos)) != State.ILLEGAL and d[Action.FORWARDS] != None:
         actions[d[Action.FORWARDS]] = 1
     #backwards
     if self.state(*(self.move_distance * -v + pos)) != State.ILLEGAL and d[Action.BACKWARDS] != None:
         actions[d[Action.BACKWARDS]] = 1
     return actions
示例#4
0
    def init_camera(self):
        all_activated = self.prediction.scene.interactor is not None and \
            self.mse.scene.interactor is not None and \
            self.truth.scene.interactor is not None
        if not all_activated:
            return

        self.prediction.scene.interactor.interactor_style = \
            RotateAroundZInteractor()
        self.mse.scene.interactor.interactor_style = RotateAroundZInteractor()
        self.truth.scene.interactor.interactor_style = \
            RotateAroundZInteractor()

        self.truth.scene.anti_aliasing_frames = 2

        try:
            self._plot_fit()
        except:
            traceback.print_exc()
        self._plot_plume()
        extent = [-150, 140, -140, 150, -85, 0]
        #ax = mlab.axes(extent=extent, xlabel='', ylabel='', zlabel='')
        #ax.axes.number_of_labels = 3
        #ax.axes.corner_offset = 0.05
        #ax.axes.label_format = '%2.0f'
        #ax.label_text_property.italic = False
        #ax.label_text_property.bold = False
        #ax.axes.font_factor = 2
        #ax.axes.ranges = [-140, 140, -140, 140, -80, 0]
        #ax.axes.use_ranges = True

        x, y = np.meshgrid([-140, 140], [-140, 140], indexing='ij')
        mlab.surf(x, y, np.zeros_like(x, 'd'), color=(1.0, 1.0, 1.0))

        mlab.sync_camera(self.prediction.mayavi_scene, self.mse.mayavi_scene)
        mlab.sync_camera(self.mse.mayavi_scene, self.prediction.mayavi_scene)
        mlab.sync_camera(self.mse.mayavi_scene, self.truth.mayavi_scene)
        mlab.sync_camera(self.truth.mayavi_scene, self.mse.mayavi_scene)
        mlab.view(
            azimuth=135, elevation=135, distance=1200, roll=-120,
            figure=self.prediction.mayavi_scene)
        self.truth.scene.interactor.interactor_style.move(
            self.truth.camera, [0, -20])
        mlab.move(up=-30)
示例#5
0
def mayavi_demo2():
  
    """
    This function is a practice for the mayavi package in python
    """
    # function
    x = np.linspace(-10,10,100)
    y = np.linspace(-10,10,100)
    z = x*np.sin(x)*np.sin(y)
    
    # mayavi plot
    mlab.figure(1,bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    mlab.contour3d(x,y,z)
    mlab.axes(extent=[-10,10,-10,10,-10,10], \
                  x_axis_visibility=False, \
                  y_axis_visibility=False, \
                  z_axis_visibility=False)
    mlab.move(1,0,0)  
    mlab.show()
示例#6
0
def mayavi_demo():
  
    """
    This function is a practice for the mayavi package in python
    """
    # function
    x = np.linspace(-10,10,100)
    y = np.sin(x)
    z = np.zeros(100)
    
    # mayavi plot
    mlab.figure(1,bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    mlab.plot3d(x,y,z)
    mlab.axes(extent=[-10,10,-10,10,-10,10], \
                  x_axis_visibility=False, \
                  y_axis_visibility=False, \
                  z_axis_visibility=False)
    mlab.move(1,0,0)
    mlab.screenshot()
    #plt.show(img)    
    mlab.show()
示例#7
0
def show_3d_point(points):
    """
    show a (n, 3) array of point cloud
    :param points:
    :return:
    """
    if points.shape[1] != 3:
        points = np.asarray(points).T
    print('show shape: ', points.shape)
    fig = figure(bgcolor=(0, 0, 0), fgcolor=(1, 1, 1), size=(1400, 800))
    points3d(points[:, 0],
             points[:, 1],
             points[:, 2],
             mode='sphere',
             colormap='gnuplot',
             scale_factor=0.05,
             figure=fig)

    # mlab.view(75.0, 140.0, [30., 30., 30.])
    mlab.roll(360)
    mlab.move(3, -1, 3.2)
    print(mlab.view())
    mlab.show()
 def state(self,x = None,y = None):
     pos = mlab.move()[0]
     if x is None:
         x = pos[0]
     if y is None:
         y = pos[1]
     apothem = self.square_width * 3 / 2
     if x > apothem or x < -apothem or y > apothem or y < -apothem:
         return State.ILLEGAL
     if self.check_collision(self.silver_mineral_1) or self.check_collision(self.silver_mineral_2):
         return State.LOSS
     if self.check_collision(self.gold_mineral):
         return State.WIN
     return State.STANDARD 
 def check_collision(self, mineral, x = None, y = None):
     pos = mlab.move()[0]
     if x is None:
         x = pos[0]
     if y is None:
         y = pos[1]
     if hasattr(mineral,'length'):
         rad = mineral.length / 2
     else:
         rad = mineral.radius
     rad *= 1.2
     if x <= mineral.x + rad * self.x_collision_scale and x >= mineral.x - rad * self.x_collision_scale  and y <= mineral.y + rad *self.y_collision_scale and y >= mineral.y - rad * self.y_collision_scale:
         return True
     return False
示例#10
0
			sign = "abs"
		elif dataMin < 0 and dataMax == 0:
			sign = "neg"
		else:
			sign = "pos"
	
		#Add overlay
		brain.add_overlay(data,min=args.minmax[0],max=args.minmax[1],sign=sign,name='multi')
		setOverlay(brain.overlays['multi'])

	#Take a screenshots for each view
	for view in ['m','l']:
		#Show appropriate view and adjust placement
		brain.show_view(view)
		brain.show_view({'distance': 475})
		mlab.move(0,25,0)
	
		#Take screeshot
		pic = os.path.join(outDir,'temp_%s_%s.jpg'%(hemi,view))
		brain.save_image(pic)
		pics.append(pic)

#Reorder lists
pics = [pics[0],pics[2],pics[1],pics[3]]

#Read in each image
images = map(Image.open, pics)

#Crop each image
cropped = []
for img in range(len(images)):
示例#11
0
文件: pitchplot.py 项目: zirmite/flb
def pitchPlot(pitches=None, pname=None, bname=None, game=None, ptype=None, pmeth='lslsls'):
    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    
    session = Session()
    q1 = session.query(Pitch)

    if pitches is None:
        if pname is not None:
            p1 = session.query(Pitcher).filter(Pitcher.name.like('%'+pname+'%')).first()
            q1 = q1.filter(Pitch.pitcher==p1)
        if bname is not None:
            b1 = session.query(Batter).filter(Batter.name.like('%'+bname+'%')).first()
            q1 = q1.filter(Pitch.batter==b1)
        if game is not None:
            g1 = session.query(Game).filter(Game.id==game).first()
            q1 = q1.filter(Pitch.game==g1)
        if ptype is not None:
            q1 = q1.filter(Pitch.p_type==ptype)
        pitches = q1.all()

    avgsz = avgsz1(pitches)
    
    plate = (8.5/12.0) + (1.5/12.0)

    import sys
    sys.path.append('/Library/Frameworks/Python.framework/Versions/Current/lib/python2.7/site-packages')

    if pmeth=='mpl':
        ax1.plot3D([-plate,plate,plate,-plate, -plate], [0.0, 0.0, 0.0, 0.0, 0.0], [avgsz[1], avgsz[1], avgsz[0], avgsz[0], avgsz[1]], 'k-', lw=5.0, alpha=0.75)
        [ax1.plot3D(x, y, z) for x, y, z in [p.traj() for p in pitches]]
        [ax1.scatter3D(xs=[float(p.attributes['px'].value)], ys=[1.417], zs=[float(p.attributes['pz'].value)], zdir='y', s=50, c='b') for p in pitches if p.attributes['type'].value in ('S','X')]
        [ax1.scatter3D(xs=[float(p.attributes['px'].value)], ys=[1.417], zs=[float(p.attributes['pz'].value)], zdir='y', s=50, c='r') for p in pitches if p.attributes['type'].value == 'B']
    
        ax1.set_xlim3d(-3.5,3.5)
        ax1.set_ylim3d(0.0, 50.0)
        ax1.set_zlim3d(0.0,7.0)
    
        ax1.azim = -140.0
        ax1.elev = 4.0
    
        fig.show()
    else:
        from mayavi import mlab
        import numpy as np
        fig = mlab.figure(1)
        objs = [mlab.plot3d(x,y,z,s*np.ones_like(z), tube_radius=0.15, tube_sides=15, figure=fig, vmin=70.0, vmax=100.0, colormap='jet') for (x,y,z),s in [(p.traj(), p.speed) for p in pitches]]
        mlab.colorbar(objs[0])
        
        ## label with number and color code call
        [mlab.text3d(float(p.attributes['px'].value), 1.417, float(p.attributes['pz'].value), str(p.pi + 1), color=(100/256.0, 111/256.0, 255/256.0), scale=3.5/12.0) for p in pitches if p.attributes['type'].value in ('S','X')]
        [mlab.text3d(float(p.attributes['px'].value), 1.417, float(p.attributes['pz'].value), str(p.pi + 1), color=(220/256.0, 20/256.0, 60/256.0), scale=3.5/12.0) for p in pitches if p.attributes['type'].value in ('B')]
        ## plot the mound
        mlab.points3d([0.0],[62.5],[-9.0+(10.5/12.0)], scale_factor=18.0, figure=fig)
        ## plot the plate
        xp = np.array([0.0, -8.5, -8.5, 8.5, 8.5, 0.0]) / 12.0
        yp = np.array([0.0, 8.5, 17.0, 17.0, 8.5, 0.0]) / 12.0
        zp = np.zeros_like(yp)
        mlab.plot3d(xp, yp, zp, figure=fig)
        ## plot strike zone
        mlab.plot3d([-plate,plate,plate,-plate, -plate], [0.0, 0.0, 0.0, 0.0, 0.0], [avgsz[1], avgsz[1], avgsz[0], avgsz[0], avgsz[1]], figure=fig)        
        mlab.plot3d([-plate,plate,plate,-plate, -plate], [1.5, 1.5, 1.5, 1.5, 1.5], [avgsz[1], avgsz[1], avgsz[0], avgsz[0], avgsz[1]], figure=fig)        
        x, y = np.ogrid[-100:100.0:100j, -100.0:100.0:100j]
        mlab.surf(x, y, np.zeros((100,100)), color=(76/256.0, 153/256.0, 0), figure=fig)
        mlab.view(-109.5, 79.0, 40.0)
        mlab.move(0.0, -0.0, 6.0)
    #fig.savefig('pitches.vrml')#, dpi=400)
    return pitches, fig, objs
surf.actor.tcoord_generator_mode = 'plane'
surf.actor.actor.texture = textur

#adjust the light source
surf.scene.light_manager.light_mode = "vtk"
surf.scene.light_manager.number_of_lights = 3
camera_lights = surf.scene.light_manager.lights
camera_lights[1].activate = False
camera_lights[2].activate = False

# SAVE images and camera poses
#calculate the intrinsic matrix
poses = []
focs = []
extrinsic_matrices = []
cam,foc=mlab.move()
poses.append(cam)
focs.append(foc)
focal_length=distance.euclidean(cam,foc)
intrinsic_matrix=[[focal_length,0,surf.scene.get_size()[1]/2],[0,focal_length,surf.scene.get_size()[0]/2],[0,0,1]]

#move camera and save images(unfinished)
'''
for i in range(50):
    #move camera by (10,0,0)
    mlab.move(10,0,0)

    #get new camera position and focal point
    cam,foc=mlab.move()
    poses.append(cam)
    focs.append(foc)
    def step(self,action):
        
        #action is in the action space
        assert (action >= 0 and action <= self.action_space() - 1), "action not in action space"
        #verify action is legal
        assert (self.legal_actions()[action] == 1), "action not legal"

        #left = 0,right = 0,forwards = 0,backwards = 0, pos_angle = 0, neg_angle = 0
  
        #get the action which coressponds to the action integer
        action_name = None
        for act, index in self.actions_index_dict.items():
            if index == action:
                action_name = act
        #make sure that the action is found
        assert (action_name != None), "action not found"
        
        #create moves list to pass to the move_position function
        moves = [0] * 6
        #assign move or turn angle, use the enum value -1 because each enum value is ones based
        if action_name == Action.CW or action_name == Action.CCW:
            moves[action_name.value - 1] = self.turn_angle
        elif action_name != Action.STAY:
            moves[action_name.value - 1] = self.move_distance
        #store previous position
        previous_pos = mlab.move()[0]
        #transition to new state
        self.move_position(*moves)
        new_pos = mlab.move()[0]
        
        #get the reward
        game_state = self.state()
        assert (game_state != State.ILLEGAL), "transitioned to an illegal state with action {} and distance".format(action,self.move_distance)
        
           
        if game_state == State.WIN:
            reward = self.win_reward
            done = True
        elif game_state == State.LOSS:
            reward = self.loss_reward
            done = True
        else:
            done = False
            #calculate previous and current distances
            def distance(x1,y1,x2,y2):
                return np.sqrt((x2-x1)**2 + (y2-y1)**2)
            previous_distance = distance(previous_pos[0],previous_pos[1],self.gold_mineral.x,self.gold_mineral.y)
            current_distance = distance(new_pos[0],new_pos[1],self.gold_mineral.x,self.gold_mineral.y)
            
            #use one of the reward structures
            if self.reward == Reward.RELATIVE:
                if previous_distance > current_distance:
                    reward = self.move_reward
                else:
                    reward = self.move_reward * 2
            elif self.reward == Reward.PROPORTIONAL:
                reward = current_distance**2 / -100
            elif self.reward == Reward.RELATIVE_PROPORTIONAL:
                reward = previous_distance - current_distance
                #if reward == 0:
                    #reward = -.5
            else:
                reward = self.move_reward
            #also end the game if there are no more legal actions in the new state 
            if max(self.legal_actions()) == 0:
               done = True
            
        next_state = self.screenshot()
        
        return next_state, reward, done, game_state
        t_azimuth = arg_azimuth
    else:
        t_azimuth = AZIMUTH[hemi]

    if arg_elevation != DEFAULT_ANGLE:
        t_elevation = arg_elevation
    else:
        t_elevation = ELEVATION[hemi]

    print("azimuth = %f; elevation = %f" % (t_azimuth, t_elevation))
    
    mlab.view(azimuth=t_azimuth, elevation=t_elevation, roll=180, \
              focalpoint=[0, 0, 0], distance=240)


    cam,foc = mlab.move()
    print(cam)
    print(foc)
    
    view=mlab.view()
    print(view)

    # === Save to output image === #
    if len(outputImgFN) > 0:
        os.system("rm -f %s" % outputImgFN)
        print("Saving image file ...")
        mlab.savefig(outputImgFN)
        check_file(outputImgFN)
        print("Image file saved at: %s" % outputImgFN)
    
    mlab.show()
 def move_position(self,left = 0,right = 0,forwards = 0,backwards = 0, pos_angle = 0, neg_angle = 0, set_value = True):
     mlab.move(forwards - backwards, right - left,0)
     mlab.yaw(pos_angle - neg_angle)
    # Axis texts scales to fit in the viewport?
    axes.axes.scaling = False
    # Text color
    axes.title_text_property.color, axes.label_text_property.color = (
        0, 0, 0), (89 / 255., 89 / 255., 89 / 255.)
    # Text size
    axes.title_text_property.font_size, axes.label_text_property.font_size = 14, 12
    axes.axes.font_factor = 1.0
    # Prevent corner axis label clash
    axes.axes.corner_offset = 0.05
    figW = 3.39
    figH = figW * (np.sqrt(5) - 1.0) / 2.0
    if figView is 'iso':
        mlab.view(azimuth=260, elevation=60)
        # Move the figure left 20 pixels?
        mlab.move(right=-20)
    elif figView is 'front':
        mlab.view(azimuth=210, elevation=90)
        mlab.move(forward=500)
    elif figView is 'left':
        mlab.view(azimuth=120, elevation=90)
        mlab.move(up=0, right=-40)
    elif figView is 'top':
        mlab.view(azimuth=0, elevation=0)
        mlab.move(right=-20)

    # [BUG] Magnification doesn't work on axis
    mlab.savefig(case.resultPath[time] + pickleName + '_quiver_' + figView +
                 '.png',
                 size=(figW, figH))
    # mlab.show()
示例#17
0
def plotIsosurfaces3D(x3D,
                      y3D,
                      z3D,
                      surface3Dlist,
                      contourList,
                      slice3Dlist=(None, ),
                      boundSurface=(None, ),
                      customColors=(None, ),
                      figDir='./',
                      name='UntitledIsosurface',
                      sliceOriantations=(None, ),
                      sliceOffsets=(None, ),
                      boundSlice=(None, ),
                      sliceValRange=(None, )):
    from mayavi import mlab
    from mayavi.modules.contour_grid_plane import ContourGridPlane
    from mayavi.modules.outline import Outline
    from mayavi.api import Engine
    import numpy as np
    from warnings import warn

    x3D, y3D, z3D = np.array(x3D), np.array(y3D), np.array(z3D)

    engine = Engine()
    engine.start()
    # if len(engine.scenes) == 0:
    #     engine.new_scene()

    if customColors[0] is not None:
        customColors = iter(customColors)
    else:
        customColors = iter(
            ('inferno', 'viridis', 'coolwarm', 'Reds', 'Blues') * 2)

    contourList = iter(contourList)
    if sliceOriantations[0] is not None:
        sliceOriantations = iter(sliceOriantations)
    else:
        sliceOriantations = iter(('z_axes', ) * len(slice3Dlist))

    if boundSurface[0] is None:
        boundSurface = (x3D.min(), x3D.max(), y3D.min(), y3D.max(), z3D.min(),
                        z3D.max())

    if boundSlice[0] is None:
        boundSlice = (x3D.min(), x3D.max(), y3D.min(), y3D.max(), z3D.min(),
                      z3D.max())

    if sliceOffsets[0] is None:
        sliceOffsets = iter((0, ) * len(slice3Dlist))
    else:
        sliceOffsets = iter(sliceOffsets)

    if sliceValRange[0] is None:
        sliceValRange = iter((None, None) * len(slice3Dlist))
    else:
        sliceValRange = iter(sliceValRange)

    mlab.figure(name,
                engine=engine,
                size=(1200, 900),
                bgcolor=(1, 1, 1),
                fgcolor=(0.5, 0.5, 0.5))

    for surface3D in surface3Dlist:
        color = next(customColors)
        # If a colormap given
        if isinstance(color, str):
            mlab.contour3d(x3D,
                           y3D,
                           z3D,
                           surface3D,
                           contours=next(contourList),
                           colormap=color,
                           extent=boundSurface)
        # If only one color of (0-1, 0-1, 0-1) given
        else:
            mlab.contour3d(x3D,
                           y3D,
                           z3D,
                           surface3D,
                           contours=next(contourList),
                           color=color,
                           extent=boundSurface)

        # cgp = ContourGridPlane()
        # engine.add_module(cgp)
        # cgp.grid_plane.axis = 'y'
        # cgp.grid_plane.position = x3D.shape[1] - 1
        # cgp.contour.number_of_contours = 20
        # # contour_grid_plane2.actor.mapper.scalar_range = array([298., 302.])
        # # contour_grid_plane2.actor.mapper.progress = 1.0
        # # contour_grid_plane2.actor.mapper.scalar_mode = 'use_cell_data'
        # cgp.contour.filled_contours = True
        # cgp.actor.property.lighting = False

    for slice3D in slice3Dlist:
        sliceOriantation = next(sliceOriantations)
        sliceOffset = next(sliceOffsets)
        if sliceOriantation == 'z_axes':
            origin = np.array([boundSlice[0], boundSlice[2], sliceOffset])
            point1 = np.array([boundSlice[1], boundSlice[2], sliceOffset])
            point2 = np.array([boundSlice[0], boundSlice[3], sliceOffset])
        elif sliceOriantation == 'x_axes':
            origin = np.array([sliceOffset, boundSlice[2], boundSlice[4]])
            point1 = np.array([sliceOffset, boundSlice[3], boundSlice[4]])
            point2 = np.array([sliceOffset, boundSlice[2], boundSlice[5]])
        else:
            origin = np.array([boundSlice[0], sliceOffset, boundSlice[4]])
            point1 = np.array([boundSlice[1], sliceOffset, boundSlice[4]])
            point2 = np.array([boundSlice[0], sliceOffset, boundSlice[5]])

        image_plane_widget = mlab.volume_slice(
            x3D,
            y3D,
            z3D,
            slice3D,
            plane_orientation=sliceOriantation,
            colormap=next(customColors),
            vmin=next(sliceValRange),
            vmax=next(sliceValRange))
        image_plane_widget.ipw.reslice_interpolate = 'cubic'
        image_plane_widget.ipw.origin = origin
        image_plane_widget.ipw.point1 = point1
        image_plane_widget.ipw.point2 = point2
        # image_plane_widget.ipw.slice_index = 2
        image_plane_widget.ipw.slice_position = sliceOffset

    # Contour grid plane at last y if the last slice is in xy plane
    if sliceOriantation == 'z_axes':
        cgp2 = ContourGridPlane()
        engine.add_module(cgp2)
        cgp2.grid_plane.axis = 'y'
        cgp2.grid_plane.position = x3D.shape[1] - 1
        cgp2.contour.number_of_contours = 20
        cgp2.contour.filled_contours = True
        cgp2.actor.property.lighting = False

    outline = Outline()
    engine.add_module(outline)
    outline.actor.property.color = (0.2, 0.2, 0.2)
    outline.bounds = np.array(boundSurface)
    outline.manual_bounds = True

    mlab.view(azimuth=270, elevation=45)
    mlab.move(-500, 0, 0)
    mlab.savefig(figDir + '/' + name + '.png', magnification=3)
    print('\nFigure ' + name + ' saved at ' + figDir)
    mlab.show()
示例#18
0
 def move(self, forward=None, right=None, up=None):
     return mlab.move(forward=forward, right=right, up=up)
示例#19
0
def make_frame(t):
    # x = volumes_data[:, :, :, int(t * 100/5/2)]
    # vol.mlab_source.set(scalars=x)
    mlab.clf(figure=None)
    print(int(t * 100 / 5 / 2))
    mlab.barchart(A1)
    mlab.barchart(A2)
    mlab.barchart(A3)
    mlab.barchart(A4)

    mlab.points3d(0,
                  0,
                  0,
                  mode='cube',
                  color=(1, 1, 0),
                  scale_mode='none',
                  scale_factor='0.5')
    mlab.points3d(A.shape[0] - 1,
                  A.shape[1] - 1,
                  0,
                  mode='cube',
                  color=(1, 1, 0),
                  scale_mode='none',
                  scale_factor='0.5')
    num = int(t)
    # plan_path_Hybrid1 = "plan_path_Hybrid_temp" + str(num) + ".npy"
    plan_path_Hybrid1 = "plan_path_PP_temp" + str(num) + ".npy"
    plan_path_Hybrid = np.load(file=plan_path_Hybrid1)
    # print("综合规划路径数组类型输出:",plan_path_Hybrid.shape)
    # print("输出Hybird路径:\n")
    # print(plan_path_Hybrid)
    # print("x=0时:")
    # print(plan_path_Hybrid[0])
    # print("测试...取第一维高度:")
    # print(plan_path_Hybrid[:,0])
    x1 = plan_path_Hybrid[:, 1]
    x1 = np.insert(x1, 0, 0)
    x1 = np.append(x1, A.shape[0] - 1)
    y1 = plan_path_Hybrid[:, 2]
    y1 = np.insert(y1, 0, 0)
    y1 = np.append(y1, A.shape[1] - 1)
    z1 = plan_path_Hybrid[:, 0] + 0.5
    z1 = np.insert(z1, 0, 0)
    z1 = np.append(z1, 0)

    # camera状态改变可视化过程
    # camera_path = "plan_path_Hybrid_temp" + str(num) + ".npy"
    camera_path = "plan_path_PP_temp" + str(num) + ".npy"
    camera_path = np.load(file=camera_path)

    # print("测试...取摄像机开关状态:")
    c = plan_path_Hybrid[:, 3]
    # print(c)
    # print(len(c))
    # print(c[0])
    cc = []  # cc表示改变摄像机状态的点的位置集合
    for i in range(len(c)):
        if c[i] != c[i - 1]:
            # print(i-1,c[i-1])
            cc.append(i - 1)
    # print("改变摄像机状态的点的位置集合:",cc)
    ccc = []
    n = 2
    for i in range(0, len(cc), n):
        # print(cc[i:i + n])
        ccc.append(cc[i:i + n])
    # print("将状态的位置集合拆分成两两的线段:",ccc)
    # print("改变camera状态的线段的条数:",len(ccc))
    # print("####",np.shape(ccc)[0])

    # mlab.plot3d(x, y, z, color=(0.23, 0.6, 1), colormap='Spectral')
    mlab.plot3d(x1,
                y1,
                z1,
                color=(0, 0, 1),
                opacity=1,
                tube_radius=None,
                colormap='Spectral')
    mlab.plot3d(x,
                y,
                z,
                color=(0, 0, 0),
                opacity=1,
                tube_radius=None,
                colormap='Spectral')

    for i in range(np.shape(ccc)[0]):
        c1 = plan_path_Hybrid[ccc[i][0]:(ccc[i][1] + 1), 0:3]
        # print("******",c1)
        np.savetxt("c" + str(i) + ".txt", c1, fmt='%d', delimiter=' ')
        camera_path_1 = np.loadtxt("c" + str(i) + ".txt",
                                   delimiter=' ',
                                   dtype=int)
        # print("@@@@@@@@@",camera_path_1)
        X = camera_path_1[:, 1]
        Y = camera_path_1[:, 2]
        Z = camera_path_1[:, 0] + 0.5
        for i in range(np.shape(ccc)[0]):
            mlab.plot3d(X,
                        Y,
                        Z,
                        color=(0, 1, 0),
                        opacity=1,
                        tube_radius=None,
                        colormap='Spectral')

    a = plan_path_Hybrid[num][0]
    b = plan_path_Hybrid[num][1]
    c = plan_path_Hybrid[num][2]
    # print(c, a, b)
    mlab.points3d(b,
                  c,
                  a + 0.5,
                  mode='cube',
                  color=(1, 1, 0),
                  scale_mode='none',
                  scale_factor='0.5')

    s = mlab.gcf()
    s.scene.background = (1, 1, 1)
    source = s.children[0]
    colors = source.children[0]
    # colors = manager.children[0]
    # print(colors)
    colors.scalar_lut_manager.lut_mode = "Blues"
    colors = s.children[1].children[0]
    colors.scalar_lut_manager.lut_mode = "Wistia"
    colors = s.children[2].children[0]
    colors.scalar_lut_manager.lut_mode = "RdYlBu"
    colors = s.children[3].children[0]
    colors.scalar_lut_manager.lut_mode = "OrRd"
    mlab.move(forward=-4, right=-4)

    mlab.savefig('abc.png', figure=mlab.gcf(), magnification=2)

    # mlab.show()

    # return mlab.screenshot(antialiased=True)
    print(mlab.screenshot(figure=None, mode='rgb', antialiased=False))
    return mlab.screenshot(figure=None, mode='rgb', antialiased=False)
示例#20
0
        i = i + 1
        yield
    i = 0
    while i < 45:
        mlab.view(azimuth=180 + i * 2, elevation=130 - i)
        fig.scene.render()
        i = i + 1
        yield
    i = 0
    while i < 5:
        i = i + 1
        yield
    i = 0
    while i < 45:
        mlab.view(azimuth=270 + i * 2, elevation=85 - 2 * i)
        mlab.move(forward=-0.1)
        fig.scene.render()
        i = i + 1
        yield
    i = 0
    while i < 15:
        i = i + 1
        yield


mlab.view(azimuth=180, elevation=130)
mlab.move(forward=120)
animate = anim()

mlab.show()