Exemplo n.º 1
0
    def SedimentColour(self, z):
        # The method changes the texture of the sediment surface. The texture is such that color of each element is
        # directly correlated to the sediment depth of the element.
        # ============== BUG ============== BUG ============== BUG ============== BUG ============== BUG ==============
        # There is a bug which occurs randomly, in those cases the texture is transposed. It is unclear what causes the
        # bug and what can be done to remove it.
        # ============== BUG ============== BUG ============== BUG ============== BUG ============== BUG ==============
        from PIL import Image
        b = np.zeros((512, 512, 3))
        b[:, :, 1] = 255 * z / np.max(z)
        img = Image.fromarray(b.astype('uint8'), 'RGB')
        #img.show()
        img = img.rotate(
            90
        )  # The rotation is necessary for the image to align with the surface properly.
        #img = img.transpose(Image.TRANSPOSE)  # The rotation is necessary for the image to align with the surface properly.
        img.save('my.png')

        bmp1 = tvtk.PNGReader()
        #bmp1 = tvtk.JPEGReader()
        bmp1.file_name = "my.png"
        my_texture = tvtk.Texture(input_connection=bmp1.output_port,
                                  interpolate=0)

        # If the scalar_visibility is not False the colour of the texture will depend on the height of the surface. When
        # they value is false the appearance of the texture do not depend on the height of the surface, THIS IS CRUCIAL.
        self.a.actor.mapper.scalar_visibility = False
        self.a.actor.enable_texture = True
        self.a.actor.tcoord_generator_mode = 'plane'
        self.a.actor.actor.texture = my_texture
Exemplo n.º 2
0
    def update_plot(self, terrain, track):
        # This function is called when the view is opened. We don't
        # populate the scene when the view is not yet open, as some
        # VTK features require a GLContext.

        # We can do normal mlab calls on the embedded scene.
        # self.scene.mlab.test_points3d()

        # Here's were I embedded my code
        self.scene.mlab.clf()

        # Plot the elevation mesh
        elevation_mesh = self.scene.mlab.mesh(terrain['x'], terrain['y'],
                                              terrain['z'])

        # Read and apply texture
        bmp = tvtk.PNGReader(file_name=bombo.TEXTURE_FILE)
        texture = tvtk.Texture(input_connection=bmp.output_port, interpolate=1)
        elevation_mesh.actor.actor.mapper.scalar_visibility = False
        elevation_mesh.actor.enable_texture = True
        elevation_mesh.actor.tcoord_generator_mode = 'plane'
        elevation_mesh.actor.actor.texture = texture

        # Display path nodes
        if len(track['x']) == 1:
            track_line = self.scene.mlab.points3d(
                track['x'],
                track['y'],
                track['z'],
                color=track['color'],
                mode='sphere',
                scale_factor=track['line_radius'] * 10)
        else:
            track_line = self.scene.mlab.plot3d(
                track['x'],
                track['y'],
                track['z'],
                color=track['color'],
                line_width=10.0,
                tube_radius=track['line_radius'])

        # Display north text
        north_label = self.scene.mlab.text3d(
            (terrain['x'][0][0] + terrain['x'][-1][0]) / 2,
            terrain['y'][0][0],
            np.max(terrain['z']),
            "NORTH",
            scale=(track['textsize'], track['textsize'], track['textsize']))

        # Displaying start test
        if len(track['x']) > 1:
            start_label = self.scene.mlab.text3d(track['x'][0],
                                                 track['y'][0],
                                                 track['z'][0] * 1.5,
                                                 "START",
                                                 scale=(track['textsize'],
                                                        track['textsize'],
                                                        track['textsize']))
Exemplo n.º 3
0
 def __init__(self, **traits):
     d = {'bmp':tvtk.BMPReader(),
          'jpg':tvtk.JPEGReader(),
          'png':tvtk.PNGReader(),
          'pnm':tvtk.PNMReader(),
          'dcm':tvtk.DICOMImageReader(),
          'tiff':tvtk.TIFFReader(),
          'ximg':tvtk.GESignaReader(),
          'dem':tvtk.DEMReader(),
          'mha':tvtk.MetaImageReader(),
          'mhd':tvtk.MetaImageReader(),
         }
     # Account for pre 5.2 VTk versions, without MINC reader
     if hasattr(tvtk, 'MINCImageReader'):
         d['mnc'] = tvtk.MINCImageReader()
     d['jpeg'] = d['jpg']
     self._image_reader_dict = d
     # Call parent class' init.
     super(ImageReader, self).__init__(**traits)
Exemplo n.º 4
0
def manual_sphere(image_file):
    # caveat 1: flip the input image along its first axis
    img = plt.imread(image_file)  # shape (N,M,3), flip along first dim
    #outfile = image_file.replace('.png', '_flipped.png')
    # flip output along first dim to get right chirality of the mapping
    #img = img[::-1,...]
    #plt.imsave(outfile, img)
    #image_file = outfile  # work with the flipped file from now on

    # parameters for the sphere
    R = 1  # radius of the sphere
    Nrad = 180  # points along theta and phi
    phi = np.linspace(0, 2 * np.pi, Nrad)  # shape (Nrad,)
    theta = np.linspace(0, np.pi, Nrad)  # shape (Nrad,)
    phigrid, thetagrid = np.meshgrid(phi, theta)  # shapes (Nrad, Nrad)

    # compute actual points on the sphere
    x = R * np.sin(thetagrid) * np.cos(phigrid)
    y = R * np.sin(thetagrid) * np.sin(phigrid)
    z = R * np.cos(thetagrid)

    # create figure
    mlab.figure(size=(600, 600))
    # create meshed sphere
    mesh = mlab.mesh(x, y, z)
    mesh.actor.actor.mapper.scalar_visibility = False
    mesh.actor.enable_texture = True  # probably redundant assigning the texture later

    # load the (flipped) image for texturing
    img = tvtk.PNGReader(file_name=image_file)
    texture = tvtk.Texture(input_connection=img.output_port,
                           interpolate=0,
                           repeat=0)
    mesh.actor.actor.texture = texture

    # tell mayavi that the mapping from points to pixels happens via a sphere
    mesh.actor.tcoord_generator_mode = 'sphere'  # map is already given for a spherical mapping
    cylinder_mapper = mesh.actor.tcoord_generator
    # caveat 2: if prevent_seam is 1 (default), half the image is used to map half the sphere
    cylinder_mapper.prevent_seam = 0  # use 360 degrees, might cause seam but no fake data
Exemplo n.º 5
0
def auto_sphere(image_file):
    # create a figure window (and scene)
    fig = mlab.figure(size=(600, 600))

    # load and map the texture
    img = tvtk.PNGReader()
    img.file_name = image_file
    texture = tvtk.Texture(input_connection=img.output_port, interpolate=1)
    # (interpolate for a less raster appearance when zoomed in)

    # use a TexturedSphereSource, a.k.a. getting our hands dirty
    R = 1
    Nrad = 180

    # create the sphere source with a given radius and angular resolution
    sphere = tvtk.TexturedSphereSource(radius=R,
                                       theta_resolution=Nrad,
                                       phi_resolution=Nrad)
    # assemble rest of the pipeline, assign texture
    sphere_mapper = tvtk.PolyDataMapper(input_connection=sphere.output_port)
    sphere_actor = tvtk.Actor(mapper=sphere_mapper, texture=texture)
    fig.scene.add_actor(sphere_actor)
Exemplo n.º 6
0
def draw_bilboard(fig, texture_name, pos=(0, 0, 0), scale=1.0):
    plane = tvtk.PlaneSource(center=pos)
    # pdb.set_trace()
    # plane = resize(plane, scale)

    reader = tvtk.PNGReader()
    reader.set_data_scalar_type_to_unsigned_char()
    reader.set(file_name=texture_name)

    plane_texture = tvtk.Texture()
    plane_texture.set_input(reader.get_output())
    plane_texture.set(interpolate=0)
    # pdb.set_trace()

    map = tvtk.TextureMapToPlane()
    map.set_input(plane.get_output())

    plane_mapper = tvtk.PolyDataMapper()
    plane_mapper.set(input=map.get_output())

    p = tvtk.Property(opacity=1.0, color=(1, 0, 0))
    plane_actor = tvtk.Actor(mapper=plane_mapper, texture=plane_texture)
    fig.scene.add_actor(plane_actor)
Exemplo n.º 7
0
def compare_image_with_saved_image(src_img,
                                   img_fname,
                                   threshold=10,
                                   allow_resize=True):
    """Compares a source image (src_img, which is a tvtk.ImageData)
    with the saved image file whose name is given in the second
    argument.  If the image file does not exist the image is generated
    and stored.  If not the source image is compared to that of the
    figure.  This function also handles multiple images and finds the
    best matching image.  If `allow_resize` is True then the images
    are rescaled if they are not of the same size.
    """
    f_base, f_ext = os.path.splitext(os.path.abspath(img_fname))

    if not os.path.isfile(img_fname):
        # generate the image
        pngw = tvtk.PNGWriter(file_name=img_fname, input=src_img)
        pngw.write()
        if VERBOSE:
            print "Creating baseline image '%s'." % img_fname
        return

    pngr = tvtk.PNGReader(file_name=img_fname)
    pngr.update()

    if allow_resize:
        src_resample = tvtk.ImageResample(input=src_img,
                                          interpolate=1,
                                          interpolation_mode='cubic')
        img_resample = tvtk.ImageResample(input=pngr.output,
                                          interpolate=1,
                                          interpolation_mode='cubic')
        _set_scale(src_resample, img_resample)
        idiff = tvtk.ImageDifference(input=src_resample.output,
                                     image=img_resample.output)
    else:
        idiff = tvtk.ImageDifference(input=src_img, image=pngr.output)
    idiff.update()

    min_err = idiff.thresholded_error
    img_err = min_err
    best_img = img_fname

    err_index = 0
    count = 0
    if min_err > threshold:
        count = 1
        test_failed = 1
        err_index = -1
        while 1:  # keep trying images till we get the best match.
            new_fname = f_base + "_%d.png" % count
            if not os.path.exists(new_fname):
                # no other image exists.
                break
            # since file exists check if it matches.
            pngr.file_name = new_fname
            pngr.update()
            if allow_resize:
                _set_scale(src_resample, img_resample)
            idiff.update()
            alt_err = idiff.thresholded_error
            if alt_err < threshold:
                # matched,
                err_index = count
                test_failed = 0
                min_err = alt_err
                img_err = alt_err
                best_img = new_fname
                break
            else:
                if alt_err < min_err:
                    # image is a better match.
                    err_index = count
                    min_err = alt_err
                    img_err = alt_err
                    best_img = new_fname

            count = count + 1
        # closes while loop.

        if test_failed:
            _handle_failed_image(idiff, src_img, pngr, best_img)
            _print_image_error(img_err, err_index, f_base)
            msg = "Failed image test: %f\n" % idiff.thresholded_error
            raise AssertionError, msg
    # output the image error even if a test passed
    _print_image_success(img_err, err_index)
Exemplo n.º 8
0
def mlabtex(
        x,
        y,
        z,
        text,
        color=(0, 0, 0),
        figure=None,
        name=None,
        opacity=1.0,
        orientation=(0.0, 0.0, 0.0),
        scale=1.0,
        dpi=1200,
):
    r"""
    Render for matplotlib like text in mayavi. Analogous to mlab.text3d.

    Parameters
    ----------
    x : float
        x position of the text.
    y : float
        y position of the text.
    z : float
        z position of the text.
    text : string
        The text is positionned in 3D, in figure coordinnates.
    color : tuple, optional
        color of the text given as rgb tuple. Default: ``(0, 0, 0)``
    figure : Scene, optional
        Must be a Scene or None.
    name : string, optional
        the name of the vtk object created.
    opacity : float, optional
        The overall opacity of the vtk object. Must be a float. Default: 1.0
    orientation : tuple, optional
        the angles giving the orientation of the text.
        If the text is oriented to the camera,
        these angles are referenced to the axis of the camera.
        If not, these angles are referenced to the z axis.
        Must be an array with shape (3,).
    scale : float, optional
        The scale of the text, in figure units. It is rescaled by the size of
        the letter "I".
    dpi : int, optional
        Used dpi. Default: 1200

    Returns
    -------
    surf : Surf
        Mayavi ``Surf`` class with the rendered text as texture.

    Notes
    -----
    If you get the following error:

        ``RuntimeError: libpng signaled error``

    Try to set the dpi higher. (1200 recomended)

    If big symbols like ``\int`` or ``\sum`` don't show up properly,
    try setting a

        ``\displaystyle``

    infront of them.
    """
    # create temporary file for the reference height of the letter "I"
    reffile = TmpFile(suffix=".png")
    render_latex(r"I", path=reffile.name, dpi=dpi)
    ref = tvtk.PNGReader()
    ref.file_name = reffile.name
    ref.update()
    # Reference heigth of the letter "I"
    ref_y = ref.data_extent[3]
    reffile.close()
    # create temporary file for the png
    pngfile = TmpFile(suffix=".png")
    # create png file containing text with matplotlib
    render_latex(text, path=pngfile.name, color=color, dpi=dpi)
    # loading image with tvtk
    surf = mlabimg(
        x,
        y,
        z,
        pngfile.name,
        figure,
        name,
        opacity,
        orientation,
        scale,
        typ="png",
        ref_y_extent=ref_y,
    )
    # close temp file
    pngfile.close()

    return surf