예제 #1
0
def inertial_asteroid_landing_cpp_save(time,
                                       state,
                                       filename,
                                       mayavi_objects,
                                       output_path,
                                       move_cam=False,
                                       mesh_weight=False,
                                       magnification=1):
    """Animation for the landing portion 
    """
    mesh, com, time_text, weight_text = mayavi_objects

    fig = mlab.gcf()
    camera = fig.scene.camera

    ms = mesh.mlab_source
    ts = com.mlab_source

    with h5py.File(filename, 'r') as hf:
        v = hf['landing/vertices'][()]
        f = hf['landing/faces'][()]

        Ra_group = hf['landing/Ra']
        keys = np.array(utilities.sorted_nicely(list(Ra_group.keys())))

        ii = 0
        for (t, pos, Rb2i, key) in zip(time, state[:, 0:3], state[:, 6:15],
                                       keys):
            mesh.scene.disable_render = True
            Ra = Ra_group[key][()]
            Rb2i = Rb2i.reshape((3, 3))
            new_vertices = Ra.dot(v.T).T
            new_faces = f

            time_text.trait_set(text="t: {:8.1f}".format(t))

            # option to change color of mesh_weight
            ms.set(x=new_vertices[:, 0],
                   y=new_vertices[:, 1],
                   z=new_vertices[:, 2],
                   triangles=new_faces)

            ts.set(x=pos[0], y=pos[1], z=pos[2])

            if move_cam:
                pos_sph = wavefront.cartesian2spherical(pos)
                graphics.mayavi_view(fig,
                                     azimuth=np.rad2deg(pos_sph[2]),
                                     elevation=90 - np.rad2deg(pos_sph[1]),
                                     distance=pos_sph[0] + 0.5,
                                     focalpoint=[0, 0, 0])
            filename = os.path.join(output_path, str(ii).zfill(7) + '.jpg')
            mesh.scene.disable_render = False
            graphics.mlab.savefig(filename, magnification=magnification)
            ii += 1
예제 #2
0
def exploration_generate_plots(data_path, img_path='/tmp/diss_explore', 
                               magnification=4, step=1, show=True):
    """Given a HDF5 file generated by explore (C++) this will generate some plots
    """

    if not os.path.exists(img_path):
        os.makedirs(img_path)

    with h5py.File(data_path, 'r') as hf:
        rv = hf['reconstructed_vertex']
        rw = hf['reconstructed_weight']
        
        # get all the keys
        v_keys = np.array(utilities.sorted_nicely(list(rv.keys())))
        w_keys = np.array(utilities.sorted_nicely(list(rw.keys())))

        v_initial = hf['initial_vertex'][()]
        f_initial = hf['initial_faces'][()]
        w_initial = np.squeeze(hf['initial_weight'][()])

        # determine the maximum extents of the mesh and add some margin
        scale = 1.25
        max_x = scale*np.max(v_initial[:, 0])
        min_x = scale*np.min(v_initial[:, 0])
        max_y = scale*np.max(v_initial[:, 1])
        min_y = scale*np.min(v_initial[:, 1])
        max_z = scale*np.max(v_initial[:, 2])
        min_z = scale*np.min(v_initial[:, 2])

        """Partial images during the reconstruction"""
        mfig = graphics.mayavi_figure(offscreen=(not show))
        mesh = graphics.mayavi_addMesh(mfig, v_initial, f_initial)
        ms = mesh.mlab_source
        graphics.mayavi_axes(mfig, [min_x, max_x, min_x, max_x, min_x, max_x], line_width=5, color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)
        partial_index = np.array([0, v_keys.shape[0]*1/4, v_keys.shape[0]*1/2,
                                  v_keys.shape[0]*3/4, v_keys.shape[0]*4/4-1],
                                 dtype=np.int)
        for img_index, vk in enumerate(partial_index):
            filename = os.path.join(img_path, 'partial_' + str(vk) + '.jpg')
            v = rv[str(vk)][()]
            # generate an image and save it 
            ms.reset(x=v[:, 0], y=v[:, 1], z=v[:,2], triangles=f_initial)
            graphics.mlab.savefig(filename, magnification=magnification)
        
        """Plot the truth asteroid"""
        v_true = hf['truth_vertex'][()]
        f_true = hf['truth_faces'][()]
        ms.reset(x=v_true[:, 0], y=v_true[:, 1], z=v_true[:,2], triangles=f_true)
        graphics.mayavi_axes(mfig, [min_x, max_x, min_x, max_x, min_x, max_x], line_width=5, color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)
        graphics.mlab.savefig(os.path.join(img_path, 'truth.jpg' ), magnification=magnification)
예제 #3
0
def castalia_raycasting_plot(img_path):
    """Generate an image of the raycaster in work
    """
    if not os.path.exists(img_path):
        os.makedirs(img_path)

    output_filename = os.path.join(img_path, 'castalia_raycasting_plot.jpg')

    input_filename = './data/shape_model/CASTALIA/castalia.obj'
    polydata = wavefront.read_obj_to_polydata(input_filename)

    # initialize the raycaster
    caster_obb = raycaster.RayCaster(polydata, flag='obb')
    caster_bsp = raycaster.RayCaster(polydata, flag='bsp')

    sensor = raycaster.Lidar(view_axis=np.array([1, 0, 0]), num_step=3)

    # need to translate the sensor and give it a pointing direction
    pos = np.array([2, 0, 0])
    dist = 2  # distance for each raycast
    R = attitude.rot3(np.pi)

    # find the inersections
    # targets = pos + sensor.rotate_fov(R) * dist
    targets = sensor.define_targets(pos, R, dist)
    intersections_obb = caster_obb.castarray(pos, targets)
    intersections_bsp = caster_bsp.castarray(pos, targets)

    # plot
    fig = graphics.mayavi_figure()

    graphics.mayavi_addPoly(fig, polydata)
    graphics.mayavi_addPoint(fig, pos, radius=0.05)

    # draw lines from pos to all targets
    for pt in targets:
        graphics.mayavi_addLine(fig, pos, pt, color=(1, 0, 0))

    for ints in intersections_bsp:
        graphics.mayavi_addPoint(fig, ints, radius=0.05, color=(1, 1, 0))

    graphics.mayavi_axes(fig=fig, extent=[-1, 1, -1, 1, -1, 1])
    graphics.mayavi_view(fig=fig)

    # savefig
    graphics.mayavi_savefig(fig=fig, filename=output_filename, magnification=4)
예제 #4
0
def asteroid_plots(asteroid_name, asteroid_path, output_directory):
    """This will generate 4 images for each asteroid.

    A view along each axis followed by a orthographic view
    """

    # load the asteroid
    v, f = wavefront.read_obj(asteroid_path)
    # create the image
    mfig = graphics.mayavi_figure(offscreen=True)
    graphics.mayavi_addMesh(mfig, v, f)
    filename = os.path.join(output_directory, asteroid_name + '_isometric.jpg')
    graphics.mayavi_savefig(mfig, filename, magnification=4)

    graphics.mayavi_view(mfig, azimuth=0, elevation=0)
    filename = os.path.join(output_directory, asteroid_name + '_x.jpg')
    graphics.mayavi_savefig(mfig, filename, magnification=4)

    graphics.mayavi_view(mfig, azimuth=90, elevation=0)
    filename = os.path.join(output_directory, asteroid_name + '_y.jpg')
    graphics.mayavi_savefig(mfig, filename, magnification=4)

    graphics.mayavi_view(mfig, azimuth=0, elevation=90)
    filename = os.path.join(output_directory, asteroid_name + '_z.jpg')
    graphics.mayavi_savefig(mfig, filename, magnification=4)
예제 #5
0
def asteroid_generate_plots(data_path,
                            img_path='/tmp/diss_reconstruct',
                            magnification=1,
                            step=10):
    """Given a HDF5 file this will read the data and create a bunch of plots/images
    """
    # check and create output directory if not existed
    if not os.path.exists(img_path):
        os.makedirs(img_path)

    with h5py.File(data_path, 'r') as hf:
        rv = hf['reconstructed_vertex']
        rw = hf['reconstructed_weight']

        # get all the keys for the groups
        v_keys = np.array(utilities.sorted_nicely(list(rv.keys())))
        w_keys = np.array(utilities.sorted_nicely(list(rw.keys())))

        v_initial = hf['initial_vertex'][()]
        f_initial = hf['initial_faces'][()]
        w_initial = hf['initial_weight'][()]
        """Partial images during the reconstruction"""
        mfig = graphics.mayavi_figure(offscreen=True)
        mesh = graphics.mayavi_addMesh(mfig, v_initial, f_initial)
        ms = mesh.mlab_source
        graphics.mayavi_axes(mfig, [-1, 1, -1, 1, -1, 1],
                             line_width=5,
                             color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)

        partial_index = np.array([
            0, v_keys.shape[0] * 1 / 4, v_keys.shape[0] * 1 / 2,
            v_keys.shape[0] * 3 / 4, v_keys.shape[0] * 4 / 4 - 1
        ],
                                 dtype=np.int)
        for img_index, vk in enumerate(partial_index):
            filename = os.path.join(img_path, 'partial_' + str(vk) + '.jpg')
            v = rv[str(vk)][()]
            # generate an image and save it
            ms.reset(x=v[:, 0], y=v[:, 1], z=v[:, 2], triangles=f_initial)
            graphics.mlab.savefig(filename, magnification=4)
        """Partial images using a colormap for the data"""
        mfig = graphics.mayavi_figure(offscreen=True)
        mesh = graphics.mayavi_addMesh(mfig,
                                       v_initial,
                                       f_initial,
                                       color=None,
                                       colormap='viridis',
                                       scalars=w_initial)
        ms = mesh.mlab_source
        graphics.mayavi_axes(mfig, [-1, 1, -1, 1, -1, 1],
                             line_width=5,
                             color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)

        partial_index = np.array([
            0, v_keys.shape[0] * 1 / 4, v_keys.shape[0] * 1 / 2,
            v_keys.shape[0] * 3 / 4, v_keys.shape[0] * 4 / 4 - 1
        ],
                                 dtype=np.int)
        for img_index, vk in enumerate(partial_index):
            filename = os.path.join(img_path,
                                    'partial_weights_' + str(vk) + '.jpg')
            v = rv[str(vk)][()]
            w = rw[str(vk)][()]
            # generate an image and save it
            ms.reset(x=v[:, 0],
                     y=v[:, 1],
                     z=v[:, 2],
                     triangles=f_initial,
                     scalars=w)
            graphics.mlab.savefig(filename, magnification=4)
        """Generate the completed shape at a variety of different angles"""
        # change the mesh to the finished mesh
        ms.reset(x=rv[v_keys[-1]][()][:, 0],
                 y=rv[v_keys[-1]][()][:, 1],
                 z=rv[v_keys[-1]][()][:, 2],
                 triangles=f_initial)
        elevation = np.array([30, -30])
        azimuth = np.array([0, 45, 135, 215, 315])

        for az, el in itertools.product(azimuth, elevation):
            filename = os.path.join(
                img_path, 'final_az=' + str(az) + '_el=' + str(el) + '.jpg')
            graphics.mayavi_view(fig=mfig, azimuth=az, elevation=el)
            graphics.mlab.savefig(filename, magnification=4)
        """Create a bunch of images for animation"""
        animation_path = os.path.join(img_path, 'animation')
        if not os.path.exists(animation_path):
            os.makedirs(animation_path)

        ms.reset(x=v_initial[:, 0],
                 y=v_initial[:, 1],
                 z=v_initial[:, 2],
                 triangles=f_initial,
                 scalars=w_initial)
        graphics.mayavi_view(mfig)
        for ii, vk in enumerate(v_keys[::step]):
            filename = os.path.join(animation_path, str(ii).zfill(7) + '.jpg')
            v = rv[vk][()]
            w = rw[str(vk)][()]
            ms.reset(x=v[:, 0],
                     y=v[:, 1],
                     z=v[:, 2],
                     triangles=f_initial,
                     scalars=w)
            graphics.mayavi_savefig(mfig,
                                    filename,
                                    magnification=magnification)

    return 0
예제 #6
0
def inertial_asteroid_refinement_cpp_save(time,
                                          state,
                                          inertial_intersections,
                                          hdf5_file,
                                          mayavi_objects,
                                          move_cam=False,
                                          mesh_weight=False,
                                          output_path="/tmp/refinement",
                                          magnification=1):
    """Save the refinment process to a bunch of images"""
    mesh, com, pc_points, time_text, weight_text = mayavi_objects

    f = mlab.gcf()
    camera = f.scene.camera
    # get all the keys for the reconstructed vertices and faces

    # animate the rotation fo the asteroid
    ms = mesh.mlab_source
    ts = com.mlab_source
    # ast_xs = ast_axes[0].mlab_source
    # ast_ys = ast_axes[1].mlab_source
    # ast_zs = ast_axes[2].mlab_source

    # dum_xs = dum_axes[0].mlab_source
    # dum_ys = dum_axes[1].mlab_source
    # dum_zs = dum_axes[2].mlab_source

    pc_sources = pc_points.mlab_source

    with h5py.File(hdf5_file, 'r') as hf:
        # oriignal vertices
        est_initial_vertices = hf[
            'simulation_parameters/estimate_asteroid/initial_vertices'][()]
        num_vert = est_initial_vertices.shape[0]

        rv_group = hf['refinement/reconstructed_vertex']
        rf_group = hf['refinement/reconstructed_face']
        rw_group = hf['refinement/reconstructed_weight']
        Ra_group = hf['refinement/Ra']

        rv_keys = np.array(utilities.sorted_nicely(list(rv_group.keys())))
        ii = 0
        for (t, pos, Rb2i, ints, key) in zip(time, state[:, 0:3], state[:,
                                                                        6:15],
                                             inertial_intersections, rv_keys):
            # rotate teh asteroid
            # Ra = ast.rot_ast2int(t)
            mesh.scene.disable_render = True
            Ra = Ra_group[key][()]
            Rb2i = Rb2i.reshape((3, 3))
            # parse out the vertices x, y, z
            # rotate the asteroid
            new_vertices = Ra.dot(rv_group[key][()].T).T
            new_faces = rf_group[key][()]
            new_weight = np.squeeze(rw_group[key][()])

            # store value for number of vertices
            # add current time
            time_text.trait_set(text="t: {:8.1f}".format(t))
            weight_text.trait_set(text="w: {:8.1f}".format(np.sum(new_weight)))

            # update asteroid
            if mesh_weight:
                # check if size is different than the last mesh
                if num_vert != new_vertices.shape[0]:
                    ms.reset(x=new_vertices[:, 0],
                             y=new_vertices[:, 1],
                             z=new_vertices[:, 2],
                             triangles=new_faces,
                             scalars=new_weight)
                    num_vert = new_vertices.shape[0]
                else:
                    ms.set(x=new_vertices[:, 0],
                           y=new_vertices[:, 1],
                           z=new_vertices[:, 2],
                           triangles=new_faces,
                           scalars=new_weight)
            else:
                if num_vert != new_vertices.shape[0]:
                    ms.reset(x=new_vertices[:, 0],
                             y=new_vertices[:, 1],
                             z=new_vertices[:, 2],
                             triangles=new_faces)
                else:
                    ms.set(x=new_vertices[:, 0],
                           y=new_vertices[:, 1],
                           z=new_vertices[:, 2],
                           triangles=new_faces)

            # update the satellite
            ts.set(x=pos[0], y=pos[1], z=pos[2])

            # update the camera view to be right behind the satellite
            if move_cam:
                pos_sph = wavefront.cartesian2spherical(pos)
                graphics.mayavi_view(f,
                                     azimuth=np.rad2deg(pos_sph[2]),
                                     elevation=90 - np.rad2deg(pos_sph[1]),
                                     distance=pos_sph[0] + 0.5,
                                     focalpoint=[0, 0, 0])

            pc_sources.set(x=ints[:, 0], y=ints[:, 1], z=ints[:, 2])

            mesh.scene.disable_render = False
            filename = os.path.join(output_path, str(ii).zfill(7) + '.jpg')
            graphics.mlab.savefig(filename, magnification=magnification)
            ii += 1
예제 #7
0
def inertial_asteroid_trajectory_cpp(time,
                                     state,
                                     inertial_intersections,
                                     hdf5_file,
                                     mayavi_objects,
                                     move_cam=False,
                                     mesh_weight=False):
    """Animate the rotation of an asteroid and the motion of SC

    This assumes an asteroid object from C++ and using the exploration sim
    """
    # pdb.set_trace()
    # mesh, ast_axes, com, dum_axes, pc_lines = mayavi_objects
    mesh, com, pc_points, time_text, weight_text = mayavi_objects

    f = mlab.gcf()
    camera = f.scene.camera
    # get all the keys for the reconstructed vertices and faces

    # animate the rotation fo the asteroid
    ms = mesh.mlab_source
    ts = com.mlab_source
    # ast_xs = ast_axes[0].mlab_source
    # ast_ys = ast_axes[1].mlab_source
    # ast_zs = ast_axes[2].mlab_source

    # dum_xs = dum_axes[0].mlab_source
    # dum_ys = dum_axes[1].mlab_source
    # dum_zs = dum_axes[2].mlab_source

    pc_sources = pc_points.mlab_source

    with h5py.File(hdf5_file, 'r') as hf:
        # oriignal vertices
        est_initial_vertices = hf[
            'simulation_parameters/estimate_asteroid/initial_vertices'][()]
        num_vert = est_initial_vertices.shape[0]

        rv_group = hf['reconstructed_vertex']
        rf_group = hf['reconstructed_face']
        rw_group = hf['reconstructed_weight']
        Ra_group = hf['Ra']

        rv_keys = np.array(utilities.sorted_nicely(list(rv_group.keys())))

        for (t, pos, Rb2i, ints, key) in zip(time, state[:, 0:3], state[:,
                                                                        6:15],
                                             inertial_intersections, rv_keys):
            # rotate teh asteroid
            # Ra = ast.rot_ast2int(t)
            mesh.scene.disable_render = True
            Ra = Ra_group[key][()]
            Rb2i = Rb2i.reshape((3, 3))
            # parse out the vertices x, y, z
            # rotate the asteroid
            new_vertices = Ra.dot(rv_group[key][()].T).T
            new_faces = rf_group[key][()]
            new_weight = np.squeeze(rw_group[key][()])

            # store value for number of vertices
            # add current time
            time_text.trait_set(text="t: {:8.1f}".format(t))
            weight_text.trait_set(text="w: {:8.1f}".format(np.sum(new_weight)))

            # update asteroid
            if mesh_weight:
                # check if size is different than the last mesh
                if num_vert != new_vertices.shape[0]:
                    ms.reset(x=new_vertices[:, 0],
                             y=new_vertices[:, 1],
                             z=new_vertices[:, 2],
                             triangles=new_faces,
                             scalars=new_weight)
                    num_vert = new_vertices.shape[0]
                else:
                    ms.set(x=new_vertices[:, 0],
                           y=new_vertices[:, 1],
                           z=new_vertices[:, 2],
                           triangles=new_faces,
                           scalars=new_weight)
            else:
                if num_vert != new_vertices.shape[0]:
                    ms.reset(x=new_vertices[:, 0],
                             y=new_vertices[:, 1],
                             z=new_vertices[:, 2],
                             triangles=new_faces)
                else:
                    ms.set(x=new_vertices[:, 0],
                           y=new_vertices[:, 1],
                           z=new_vertices[:, 2],
                           triangles=new_faces)

            # update the satellite
            ts.set(x=pos[0], y=pos[1], z=pos[2])

            # update the camera view to be right behind the satellite
            if move_cam:
                pos_sph = wavefront.cartesian2spherical(pos)
                graphics.mayavi_view(f,
                                     azimuth=np.rad2deg(pos_sph[2]),
                                     elevation=90 - np.rad2deg(pos_sph[1]),
                                     distance=pos_sph[0] + 0.5,
                                     focalpoint=[0, 0, 0])
            # update the asteroid axes
            # ast_xs.set(x=[0, Ra[0,0]], y=[0, Ra[1,0]], z=[0, Ra[2,0]])
            # ast_ys.set(x=[0, Ra[0,1]], y=[0, Ra[1,1]], z=[0, Ra[2,1]])
            # ast_zs.set(x=[0, Ra[0,2]], y=[0, Ra[1,2]], z=[0, Ra[2,2]])

            # dum_xs.set(x=[pos[0], pos[0]+Rb2i[0,0]], y=[pos[1], pos[1]+Rb2i[1,0]],
            #              z=[pos[2], pos[2]+Rb2i[2,0]])
            # dum_ys.set(x=[pos[0], pos[0]+Rb2i[0,1]], y=[pos[1], pos[1]+Rb2i[1,1]],
            #              z=[pos[2], pos[2]+Rb2i[2,1]])
            # dum_zs.set(x=[pos[0], pos[0]+Rb2i[0,2]], y=[pos[1], pos[1]+Rb2i[1,2]],
            #              z=[pos[2], pos[2]+Rb2i[2,2]])

            pc_sources.set(x=ints[:, 0], y=ints[:, 1], z=ints[:, 2])
            # for pcs, inter in zip(pc_sources, ints):
            # check if intersection is empty
            # if inter.size > 2:
            #     pcs.set(x=inter[0], y=inter[1], z=inter[2])
            # else:
            #     pcs.set(x=0, y=0, z=0)
            # pcs.set(x=1, y=1, z=1)

            mesh.scene.disable_render = False
            yield
예제 #8
0
def read_mesh_reconstruct(filename, output_path='/tmp/reconstruct_images'):
    """Use H5PY to read the data back and plot
    """
    logger = logging.getLogger(__name__)
    logger.info('Starting the image generation')

    # check if location exists
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    logger.info('Opening {}'.format(filename))
    with h5py.File(filename, 'r') as hf:
        rv = hf['reconstructed_vertex']
        rf = hf['reconstructed_face']
        rw = hf['reconstructed_weight']

        # get all the keys for the groups
        v_keys = np.array(utilities.sorted_nicely(list(rv.keys())))
        f_keys = np.array(utilities.sorted_nicely(list(rf.keys())))
        w_keys = np.array(utilities.sorted_nicely(list(rw.keys())))

        v_initial = hf['initial_vertex'][()]
        f_initial = hf['initial_faces'][()]
        w_initial = hf['initial_weight'][()]
        """Partial images during the reconstruction"""
        logger.info('Starting on partial reconstruction images')

        mfig = graphics.mayavi_figure(offscreen=True)
        mesh = graphics.mayavi_addMesh(mfig, v_initial, f_initial)
        ms = mesh.mlab_source
        graphics.mayavi_axes(mfig, [-1, 1, -1, 1, -1, 1],
                             line_width=5,
                             color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)

        partial_index = np.array([
            0, v_keys.shape[0] * 1 / 4, v_keys.shape[0] * 1 / 2,
            v_keys.shape[0] * 3 / 4, v_keys.shape[0] * 4 / 4 - 1
        ],
                                 dtype=np.int)
        for img_index, vk in enumerate(partial_index):
            filename = os.path.join(output_path, 'partial_' + str(vk) + '.jpg')
            v = rv[str(vk)][()]
            # generate an image and save it
            ms.reset(x=v[:, 0], y=v[:, 1], z=v[:, 2], triangles=f_initial)
            graphics.mlab.savefig(filename, magnification=4)
        """Partial images using a colormap for the data"""
        logger.info('Now using a colormap for the uncertainty')
        mfig = graphics.mayavi_figure(offscreen=True)
        mesh = graphics.mayavi_addMesh(mfig,
                                       v_initial,
                                       f_initial,
                                       color=None,
                                       colormap='viridis',
                                       scalars=w_initial)
        ms = mesh.mlab_source
        graphics.mayavi_axes(mfig, [-1, 1, -1, 1, -1, 1],
                             line_width=5,
                             color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)

        partial_index = np.array([
            0, v_keys.shape[0] * 1 / 4, v_keys.shape[0] * 1 / 2,
            v_keys.shape[0] * 3 / 4, v_keys.shape[0] * 4 / 4 - 1
        ],
                                 dtype=np.int)
        for img_index, vk in enumerate(partial_index):
            filename = os.path.join(output_path,
                                    'partial_weights_' + str(vk) + '.jpg')
            v = rv[str(vk)][()]
            w = rw[str(vk)][()]
            # generate an image and save it
            ms.reset(x=v[:, 0],
                     y=v[:, 1],
                     z=v[:, 2],
                     triangles=f_initial,
                     scalars=w)
            graphics.mlab.savefig(filename, magnification=4)
        """Generate the completed shape at a variety of different angles"""
        logger.info('Now generating some views of the final shape')
        # change the mesh to the finished mesh
        ms.reset(x=rv[v_keys[-1]][()][:, 0],
                 y=rv[v_keys[-1]][()][:, 1],
                 z=rv[v_keys[-1]][()][:, 2],
                 triangles=f_initial)
        elevation = np.array([30, -30])
        azimuth = np.array([0, 45, 135, 215, 315])

        for az, el in itertools.product(azimuth, elevation):
            filename = os.path.join(
                output_path, 'final_az=' + str(az) + '_el=' + str(el) + '.jpg')
            graphics.mayavi_view(fig=mfig, azimuth=az, elevation=el)
            graphics.mlab.savefig(filename, magnification=4)
        """Create a bunch of images for animation"""
        logger.info('Now making images for a movie')
        animation_path = os.path.join(output_path, 'animation')
        if not os.path.exists(animation_path):
            os.makedirs(animation_path)

        ms.reset(x=v_initial[:, 0],
                 y=v_initial[:, 1],
                 z=v_initial[:, 2],
                 triangles=f_initial)

        for ii, vk in enumerate(v_keys):
            filename = os.path.join(animation_path, str(ii).zfill(7) + '.jpg')
            v = rv[vk][()]
            ms.reset(x=v[:, 0], y=v[:, 1], z=v[:, 2], triangles=f_initial)
            graphics.mayavi_savefig(mfig, filename, magnification=4)

    logger.info('Finished')

    return mfig
예제 #9
0
def save_animation(filename, output_path, mesh_weight=False, magnification=4):
    
    output_path = os.path.join(output_path, 'animation')
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    with h5py.File(filename, 'r') as hf:
        rv = hf['reconstructed_vertex']
        rw = hf['reconstructed_weight']
        
        # get all the keys
        v_keys = np.array(utilities.sorted_nicely(list(rv.keys())))
        w_keys = np.array(utilities.sorted_nicely(list(rw.keys())))

        v_initial = hf['initial_vertex'][()]
        f_initial = hf['initial_faces'][()]
        w_initial = np.squeeze(hf['initial_weight'][()])
            
        # think about a black background as well
        mfig = graphics.mayavi_figure(bg=(0, 0, 0), size=(800,600), offscreen=True)
        
        if mesh_weight:
            mesh = graphics.mayavi_addMesh(mfig, v_initial, f_initial,
                                           scalars=w_initial,
                                           color=None, colormap='viridis')
        else:
            mesh = graphics.mayavi_addMesh(mfig, v_initial, f_initial)

        # xaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([2, 0, 0]), color=(1, 0, 0)) 
        # yaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 2, 0]), color=(0, 1, 0)) 
        # zaxis = graphics.mayavi_addLine(mfig, np.array([0, 0, 0]), np.array([0, 0, 2]), color=(0, 0, 1)) 
        # ast_axes = (xaxis, yaxis, zaxis)
        
        print("Images will be saved to {}".format(output_path))
        ms = mesh.mlab_source
        # determine the maximum extents of the mesh and add some margin
        scale = 1.25
        max_x = scale*np.max(v_initial[:, 0])
        min_x = scale*np.min(v_initial[:, 0])
        max_y = scale*np.max(v_initial[:, 1])
        min_y = scale*np.min(v_initial[:, 1])
        max_z = scale*np.max(v_initial[:, 2])
        min_z = scale*np.min(v_initial[:, 2])

        graphics.mayavi_axes(mfig, [min_x, max_x, min_x, max_x, min_x, max_x], line_width=5, color=(1, 0, 0))
        graphics.mayavi_view(fig=mfig)

        # loop over keys and save images
        for img_index, vk in enumerate(v_keys):
            filename = os.path.join(output_path, str(vk).zfill(7) + '.jpg')
            new_vertices = rv[str(vk)][()]
            new_faces = f_initial
            new_weight = rw[str(vk)][()]

            # generate an image and save it 
            if mesh_weight:
                ms.set(x=new_vertices[:, 0],y=new_vertices[:, 1],
                       z=new_vertices[:,2], triangles=new_faces,
                       scalars=new_weight)
            else:
                ms.set(x=new_vertices[:, 0],y=new_vertices[:, 1],
                       z=new_vertices[:,2], triangles=new_faces)

            graphics.mlab.savefig(filename, magnification=magnification)

    # now call ffmpeg
    fps = 60
    name_str = "reconstruction_" + datetime.datetime.now().strftime("%Y%m%dT%H%M%S") + ".mp4"

    name = os.path.join(output_path, name_str)
    ffmpeg_fname = os.path.join(output_path, '%07d.jpg')
    cmd = "ffmpeg -framerate {} -i {} -c:v libx264 -profile:v high -crf 20 -pix_fmt yuv420p -vf 'scale=trunc(iw/2)*2:trunc(ih/2)*2' {}".format(fps, ffmpeg_fname, name)
    print(cmd)
    subprocess.check_output(['bash', '-c', cmd])

    # remove folder now
    for file in os.listdir(output_path): 
        file_path = os.path.join(output_path, file)
        if file_path.endswith('.jpg'):
            os.remove(file_path)
import numpy as np
import os
import h5py
import argparse

from point_cloud import wavefront
from visualization import graphics
import utilities

view = (0, 25, 3.32, np.array([-0.04, -0.015, -0.029]))
# load the bumpy castalia
vb_true, fb_true = wavefront.read_obj(
    './data/shape_model/CASTALIA/castalia_bump_2.obj')
mfig = graphics.mayavi_figure(offscreen=False)
mesh = graphics.mayavi_addMesh(mfig, vb_true, fb_true)
graphics.mayavi_view(mfig, *view)
graphics.mayavi_savefig(mfig, '/tmp/castalia_bump_true.jpg', magnification=4)

# load the refinement final version
with h5py.File('./data/exploration/refine/20180619_castalia_refinement.hdf5',
               'r') as hf:
    # oriignal vertices
    est_initial_vertices = hf[
        'simulation_parameters/estimate_asteroid/initial_vertices'][()]
    num_vert = est_initial_vertices.shape[0]

    rv_group = hf['refinement/reconstructed_vertex']
    rf_group = hf['refinement/reconstructed_face']
    rw_group = hf['refinement/reconstructed_weight']
    Ra_group = hf['refinement/Ra']