Esempio n. 1
0
File: convert.py Progetto: zoq/fury
def matplotlib_figure_to_numpy(fig, dpi=100, fname=None, flip_up_down=True,
                               transparent=False):
    """Convert a Matplotlib figure to a 3D numpy array with RGBA channels.

    Parameters
    ----------
    fig : obj
        A matplotlib figure object
    dpi : int, optional
        Dots per inch
    fname : str, optional
        If ``fname`` is given then the array will be saved as a png to this
        position.
    flip_up_down : bool, optional
        The origin is different from matlplotlib default and VTK's default
        behaviour (default True).
    transparent : bool, optional
        Make background transparent (default False).

    Returns
    -------
    arr : ndarray
        a numpy 3D array of RGBA values

    Notes
    -----
    The safest way to read the pixel values from the figure was to save them
    using savefig as a png and then read again the png. There is a cleaner
    way found here http://www.icare.univ-lille1.fr/drupal/node/1141 where
    you can actually use fig.canvas.tostring_argb() to get the values directly
    without saving to the disk. However, this was not stable across different
    machines and needed more investigation from what time permited.

    """
    if fname is None:
        with TemporaryDirectory() as tmpdir:
            fname = os.path.join(tmpdir, 'tmp.png')
            fig.savefig(fname, dpi=dpi, transparent=transparent,
                        bbox_inches='tight', pad_inches=0)
            arr = load_image(fname)
    else:
        fig.savefig(fname, dpi=dpi, transparent=transparent,
                    bbox_inches='tight', pad_inches=0)
        arr = load_image(fname)

    if flip_up_down:
        arr = np.flipud(arr)
    return arr
Esempio n. 2
0
def test_convert():
    names = ['group_a', 'group_b', 'group_c']
    values = [1, 10, 100]

    fig = plt.figure(figsize=(9, 3))
    plt.subplot(131)
    plt.bar(names, values)
    plt.subplot(132)
    plt.scatter(names, values)
    plt.subplot(133)
    plt.plot(names, values)
    plt.suptitle('Categorical Plotting')
    arr2 = matplotlib_figure_to_numpy(fig,
                                      transparent=False,
                                      flip_up_down=False)

    with TemporaryDirectory() as tmpdir:
        fname = os.path.join(tmpdir, 'tmp.png')
        dpi = 100
        fig.savefig(fname,
                    transparent=False,
                    bbox_inches='tight',
                    pad_inches=0)
        arr1 = load_image(fname)
        npt.assert_array_equal(arr1, arr2)
Esempio n. 3
0
 def test_content(filename='fury.png', colors_found=(True, True)):
     npt.assert_equal(os.path.isfile(filename), True)
     arr = io.load_image(filename)
     report = window.analyze_snapshot(arr,
                                      colors=[(0, 255, 0), (255, 0, 0)])
     npt.assert_equal(report.objects, 3)
     npt.assert_equal(report.colors_found, colors_found)
     return arr
Esempio n. 4
0
def test_pillow():

    with InTemporaryDirectory() as odir:
        data = (255 * np.random.rand(400, 255, 4)).astype(np.uint8)
        fname_path = pjoin(odir, "test.png")
        save_image(data, fname_path, use_pillow=True)
        data2 = load_image(fname_path, use_pillow=True)
        npt.assert_array_almost_equal(data, data2)
        npt.assert_equal(data.dtype, data2.dtype)
Esempio n. 5
0
def test_save_load_image():
    l_ext = ["png", "jpeg", "jpg", "bmp", "tiff"]
    fname = "temp-io"

    for ext in l_ext:
        with InTemporaryDirectory() as odir:
            data = np.random.randint(0, 255, size=(50, 3), dtype=np.uint8)
            fname_path = pjoin(odir, "{0}.{1}".format(fname, ext))

            save_image(data, fname_path, compression_quality=100)

            npt.assert_equal(os.path.isfile(fname_path), True)
            assert_greater(os.stat(fname_path).st_size, 0)

            out_image = load_image(fname_path)
            if ext not in ["jpeg", "jpg", "tiff"]:
                npt.assert_array_equal(data[..., 0], out_image[..., 0])
            else:

                npt.assert_array_almost_equal(data[..., 0],
                                              out_image[..., 0],
                                              decimal=0)

    npt.assert_raises(IOError, load_image, "test.vtk")
    npt.assert_raises(IOError, load_image, "test.vtk", use_pillow=False)
    npt.assert_raises(IOError, save_image,
                      np.random.randint(0, 255, size=(50, 3)), "test.vtk")
    npt.assert_raises(IOError,
                      save_image,
                      np.random.randint(0, 255, size=(50, 3)),
                      "test.vtk",
                      use_pillow=False)
    npt.assert_raises(IOError, save_image,
                      np.random.randint(0, 255, size=(50, 3, 1, 1)),
                      "test.png")

    compression_type = [None, "lzw"]

    for ct in compression_type:
        with InTemporaryDirectory() as odir:
            try:
                data = np.random.randint(0, 255, size=(50, 3), dtype=np.uint8)
                fname_path = pjoin(odir, "{0}.tif".format(fname))

                save_image(data,
                           fname_path,
                           compression_type=ct,
                           use_pillow=False)
                npt.assert_equal(os.path.isfile(fname_path), True)
                assert_greater(os.stat(fname_path).st_size, 0)
            except OSError:
                continue
Esempio n. 6
0
def test_save_screenshot():
    xyzr = np.array([[0, 0, 0, 10], [100, 0, 0, 25], [200, 0, 0, 50]])
    colors = np.array([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1., 1]])
    sphere_actor = actor.sphere(centers=xyzr[:, :3],
                                colors=colors[:],
                                radii=xyzr[:, 3],
                                phi=10,
                                theta=30)
    scene = window.Scene()
    scene.add(sphere_actor)

    window_sz = (400, 400)
    show_m = window.ShowManager(scene, size=window_sz)
    show_m.initialize()

    with InTemporaryDirectory():
        fname = 'test.png'
        # Basic test
        show_m.save_screenshot(fname)
        npt.assert_equal(os.path.exists(fname), True)
        data = io.load_image(fname)
        report = window.analyze_snapshot(data,
                                         colors=[(0, 255, 0), (255, 0, 0)])
        npt.assert_equal(report.objects, 3)
        npt.assert_equal(report.colors_found, (True, True))
        # Test size
        ss_sz = (200, 200)
        show_m.save_screenshot(fname, size=ss_sz)
        npt.assert_equal(os.path.isfile(fname), True)
        data = io.load_image(fname)
        npt.assert_equal(data.shape[:2], ss_sz)
        # Test magnification
        magnification = 2
        show_m.save_screenshot(fname, magnification=magnification)
        npt.assert_equal(os.path.isfile(fname), True)
        data = io.load_image(fname)
        desired_sz = tuple(np.array(window_sz) * magnification)
        npt.assert_equal(data.shape[:2], desired_sz)
Esempio n. 7
0
    def __init__(self, img_path, position=(0, 0), size=(100, 100)):
        """Init class instance.

        Parameters
        ----------
        img_path : string
            URL or local path of the image
        position : (float, float), optional
            Absolute coordinates (x, y) of the lower-left corner of the image.
        size : (int, int), optional
            Width and height in pixels of the image.
        """
        super(ImageContainer2D, self).__init__(position)
        self.img = load_image(img_path, as_vtktype=True)
        self.set_img(self.img)
        self.resize(size)
Esempio n. 8
0
def init_planet(filename):
    """Initialize a planet actor.

    Parameters
    ----------
    filename : str
        The filename for the corresponding planet texture.

    Returns
    -------
    planet_actor: actor
        The corresponding sphere actor with texture applied.
    """
    planet_file = read_viz_textures(filename)
    planet_image = io.load_image(planet_file)
    planet_actor = actor.texture_on_sphere(planet_image)
    scene.add(planet_actor)
    return planet_actor
Esempio n. 9
0
def test_roi_images():
    np.random.seed(42)
    img1 = np.random.rand(5, 5, 5)
    img2 = np.zeros((5, 5, 5))
    img2[1, 1, 1] = 1
    img3 = np.zeros((5, 5, 5))
    img3[3, 3, 3] = 1
    images = [(img1, np.eye(4)), (img2, np.eye(4)), (img3, np.eye(4))]
    with TemporaryDirectory() as out_dir:
        tmp_fname = os.path.join(out_dir, 'tmp_x.png')

        # If roi_images=False, only the first non-binary image is loaded
        horizon(images=images, interactive=False, out_png=tmp_fname)
        npt.assert_equal(os.path.exists(tmp_fname), True)

        # If roi_images=True, all th binary images are shown as contours
        horizon(images=images, roi_images=True, interactive=False,
                out_png=tmp_fname)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        npt.assert_equal(ss[150, 800, :], [147, 0, 0])
Esempio n. 10
0
def init_planet(planet_data):
    """Initialize a planet actor.

    Parameters
    ----------
    planet_data : dict
        The planet_data is a dictionary, and the keys are filename(texture),
        position and scale.

    Returns
    -------
    planet_actor: actor
        The corresponding sphere actor with texture applied.
    """
    planet_file = read_viz_textures(planet_data['filename'])
    planet_image = io.load_image(planet_file)
    planet_actor = actor.texture_on_sphere(planet_image)
    planet_actor.SetPosition(planet_data['position'], 0, 0)
    planet_actor.SetScale(planet_data['scale'])
    scene.add(planet_actor)
    return planet_actor
Esempio n. 11
0
    def _build_icons(self, icon_fnames):
        """Convert file names to ImageData.

        A pre-processing step to prevent re-read of file names during every
        state change.

        Parameters
        ----------
        icon_fnames : List(string, string)
            ((iconname, filename), (iconname, filename), ....)

        Returns
        -------
        icons : List
            A list of corresponding ImageData.

        """
        icons = []
        for icon_name, icon_fname in icon_fnames:
            icons.append((icon_name, load_image(icon_fname, as_vtktype=True)))

        return icons
Esempio n. 12
0
from fury.data import read_viz_textures, fetch_viz_textures

##############################################################################
# Create a scene to start.

scene = window.Scene()

##############################################################################
# Load an image (png, bmp, jpeg or jpg) using ``io.load_image``. In this
# example, we will use ``read_viz_textures`` to access an image of the
# Earth's surface from the fury Github after using ''fetch_viz_textures()''
# to download the available textures.

fetch_viz_textures()
filename = read_viz_textures("1_earth_8k.jpg")
image = io.load_image(filename)

##############################################################################
# Next, use ``actor.texture_on_sphere`` to add a sphere with the texture from
# your loaded image to the already existing scene.
# To add a texture to your scene as visualized on a plane, use
# ``actor.texture`` instead.

scene.add(actor.texture_on_sphere(image))

##############################################################################
# Lastly, record the scene, or set interactive to True if you would like to
# manipulate your new sphere.

interactive = False
if interactive:
Esempio n. 13
0
def analyze_snapshot(im, bg_color=colors.black, colors=None,
                     find_objects=True,
                     strel=None):
    """Analyze snapshot from memory or file.

    Parameters
    ----------
    im: str or array
        If string then the image is read from a file otherwise the image is
        read from a numpy array. The array is expected to be of shape (X, Y, 3)
        or (X, Y, 4) where the last dimensions are the RGB or RGBA values.
    colors: tuple (3,) or list of tuples (3,)
        List of colors to search in the image
    find_objects: bool
        If True it will calculate the number of objects that are different
        from the background and return their position in a new image.
    strel: 2d array
        Structure element to use for finding the objects.

    Returns
    -------
    report : ReportSnapshot
        This is an object with attibutes like ``colors_found`` that give
        information about what was found in the current snapshot array ``im``.

    """
    if isinstance(im, basestring):
        im = load_image(im)

    class ReportSnapshot(object):
        objects = None
        labels = None
        colors_found = False

        def __str__(self):
            msg = "Report:\n-------\n"
            msg += "objects: {}\n".format(self.objects)
            msg += "labels: \n{}\n".format(self.labels)
            msg += "colors_found: {}\n".format(self.colors_found)
            return msg

    report = ReportSnapshot()

    if colors is not None:
        if isinstance(colors, tuple):
            colors = [colors]
        flags = [False] * len(colors)
        for (i, col) in enumerate(colors):
            # find if the current color exist in the array
            flags[i] = np.any(np.any(np.all(np.equal(im[..., :3], col[:3]),
                                            axis=-1)))

        report.colors_found = flags

    if find_objects is True:
        weights = [0.299, 0.587, 0.144]
        gray = np.dot(im[..., :3], weights)
        bg_color2 = im[0, 0]
        background = np.dot(bg_color2, weights)

        if strel is None:
            strel = np.array([[1, 1, 1],
                              [1, 1, 1],
                              [1, 1, 1]])

        labels, objects = ndimage.label(gray != background, strel)
        report.labels = labels
        report.objects = objects

    return report
Esempio n. 14
0
def test_manifest_standard():
    # Test non-supported property
    test_actor = actor.text_3d('Test')
    npt.assert_warns(UserWarning, material.manifest_standard, test_actor)

    center = np.array([[0, 0, 0]])

    # Test non-supported interpolation method
    test_actor = actor.square(center, directions=(1, 1, 1), colors=(0, 0, 1))
    npt.assert_warns(UserWarning,
                     material.manifest_standard,
                     test_actor,
                     interpolation='test')

    # Create tmp dir to save and query images
    with TemporaryDirectory() as out_dir:
        tmp_fname = os.path.join(out_dir, 'tmp_img.png')  # Tmp image to test

        scene = window.Scene()  # Setup scene

        test_actor = actor.box(center,
                               directions=(1, 1, 1),
                               colors=(0, 0, 1),
                               scales=1)
        scene.add(test_actor)

        # Test basic actor
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[75, 100, :] / 1000
        desired = np.array([0, 0, 170]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 125, :] / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 75, :] / 1000
        desired = np.array([0, 0, 85]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        # Test ambient level
        material.manifest_standard(test_actor, ambient_level=1)
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[75, 100, :] / 1000
        desired = np.array([0, 0, 255]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 125, :] / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 75, :] / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        # Test ambient color
        material.manifest_standard(test_actor,
                                   ambient_level=.5,
                                   ambient_color=(1, 0, 0))
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[75, 100, :] / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 125, :] / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 75, :] / 1000
        desired = np.array([0, 0, 212]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        # Test diffuse level
        material.manifest_standard(test_actor, diffuse_level=.75)
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[75, 100, :] / 1000
        desired = np.array([0, 0, 127]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 125, :] / 1000
        desired = np.array([0, 0, 128]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 75, :] / 1000
        desired = np.array([0, 0, 64]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        # Test diffuse color
        material.manifest_standard(test_actor,
                                   diffuse_level=.5,
                                   diffuse_color=(1, 0, 0))
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[75, 100, :] / 1000
        desired = np.array([0, 0, 85]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 125, :] / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 75, :] / 1000
        desired = np.array([0, 0, 42]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        # Test specular level
        material.manifest_standard(test_actor, specular_level=1)
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[75, 100, :] / 1000
        desired = np.array([170, 170, 255]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 125, :] / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 75, :] / 1000
        desired = np.array([85, 85, 170]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        # Test specular power
        material.manifest_standard(test_actor,
                                   specular_level=1,
                                   specular_power=5)
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[75, 100, :] / 1000
        desired = np.array([34, 34, 204]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 125, :] / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 75, :] / 1000
        desired = np.array([1, 1, 86]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        # Test specular color
        material.manifest_standard(test_actor,
                                   specular_level=1,
                                   specular_color=(1, 0, 0),
                                   specular_power=5)
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[75, 100, :] / 1000
        desired = np.array([34, 0, 170]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 125, :] / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[125, 75, :] / 1000
        desired = np.array([1, 0, 85]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        scene.clear()  # Reset scene

        # Special case: Contour from roi
        data = np.zeros((50, 50, 50))
        data[20:30, 25, 25] = 1.
        data[25, 20:30, 25] = 1.
        test_actor = actor.contour_from_roi(data, color=np.array([1, 0, 1]))
        scene.add(test_actor)

        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[90, 110, :] / 1000
        desired = np.array([253, 0, 253]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[90, 60, :] / 1000
        desired = np.array([180, 0, 180]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        material.manifest_standard(test_actor)
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[90, 110, :] / 1000
        desired = np.array([253, 253, 253]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[90, 60, :] / 1000
        desired = np.array([180, 180, 180]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        material.manifest_standard(test_actor, diffuse_color=(1, 0, 1))
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[90, 110, :] / 1000
        desired = np.array([253, 0, 253]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[90, 60, :] / 1000
        desired = np.array([180, 0, 180]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
Esempio n. 15
0
def test_manifest_pbr_vtk_great_than_9():
    # Test non-supported property
    test_actor = actor.text_3d('Test')
    npt.assert_warns(UserWarning, material.manifest_pbr, test_actor)

    # Test non-supported PBR interpolation
    test_actor = actor.scalar_bar()
    npt.assert_warns(UserWarning, material.manifest_pbr, test_actor)

    # Create tmp dir to save and query images
    with TemporaryDirectory() as out_dir:
        tmp_fname = os.path.join(out_dir, 'tmp_img.png')  # Tmp image to test

        scene = window.Scene()  # Setup scene

        test_actor = actor.square(np.array([[0, 0, 0]]),
                                  directions=(0, 0, 0),
                                  colors=(0, 0, 1))

        scene.add(test_actor)

        # Test basic actor
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[100, 100, :] / 1000
        desired = np.array([0, 0, 255]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[40, 40, :] / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        # Test default parameters
        material.manifest_pbr(test_actor)
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[100, 100, :] / 1000
        desired = np.array([66, 66, 165]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[40, 40, :] / 1000
        desired = np.array([40, 40, 157]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        # Test roughness
        material.manifest_pbr(test_actor, roughness=0)
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[100, 100, :] / 1000
        desired = np.array([0, 0, 155]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[40, 40, :] / 1000
        desired = np.array([0, 0, 153]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)

        # Test metallicity
        material.manifest_pbr(test_actor, metallicity=1)
        window.record(scene,
                      out_path=tmp_fname,
                      size=(200, 200),
                      reset_camera=True)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        actual = ss[100, 100, :] / 1000
        desired = np.array([0, 0, 255]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
        actual = ss[40, 40, :] / 1000
        desired = np.array([0, 0, 175]) / 1000
        npt.assert_array_almost_equal(actual, desired, decimal=2)
Esempio n. 16
0
def test_record():
    xyzr = np.array([[0, 0, 0, 10], [100, 0, 0, 25], [200, 0, 0, 50]])
    colors = np.array([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1., 1]])
    sphere_actor = actor.sphere(centers=xyzr[:, :3],
                                colors=colors[:],
                                radii=xyzr[:, 3])
    scene = window.Scene()
    scene.add(sphere_actor)

    def test_content(filename='fury.png', colors_found=(True, True)):
        npt.assert_equal(os.path.isfile(filename), True)
        arr = io.load_image(filename)
        report = window.analyze_snapshot(arr,
                                         colors=[(0, 255, 0), (255, 0, 0)])
        npt.assert_equal(report.objects, 3)
        npt.assert_equal(report.colors_found, colors_found)
        return arr

    # Basic test
    with InTemporaryDirectory():
        window.record(scene)
        test_content()

    # test out_path and path_numbering, n_frame
    with InTemporaryDirectory():
        filename = "tmp_snapshot.png"
        window.record(scene, out_path=filename)
        test_content(filename)
        window.record(scene, out_path=filename, path_numbering=True)
        test_content(filename + "000000.png")
        window.record(scene,
                      out_path=filename,
                      path_numbering=True,
                      n_frames=3)
        test_content(filename + "000000.png")
        test_content(filename + "000001.png")
        test_content(filename + "000002.png")
        npt.assert_equal(os.path.isfile(filename + "000003.png"), False)

    # test verbose
    with captured_output() as (out, _):
        window.record(scene, verbose=True)

    npt.assert_equal(
        out.getvalue().strip(), "Camera Position (315.14, 0.00, 536.43)\n"
        "Camera Focal Point (119.89, 0.00, 0.00)\n"
        "Camera View Up (0.00, 1.00, 0.00)")
    # test camera option
    with InTemporaryDirectory():
        window.record(scene,
                      cam_pos=(310, 0, 530),
                      cam_focal=(120, 0, 0),
                      cam_view=(0, 0, 1))
        test_content()

    # test size and clipping
    # Skip it on Mac mainly due to offscreen case on Travis. It works well
    # with a display. Need to check if screen_clip works. Need to check if
    # ReadFrontBufferOff(), ShouldRerenderOn() could improved this OSX case.
    if not skip_osx:
        with InTemporaryDirectory():
            window.record(scene,
                          out_path='fury_1.png',
                          size=(1000, 1000),
                          magnification=5)
            npt.assert_equal(os.path.isfile('fury_1.png'), True)
            arr = io.load_image('fury_1.png')

            npt.assert_equal(arr.shape, (5000, 5000, 3))

            window.record(scene,
                          out_path='fury_2.png',
                          size=(5000, 5000),
                          screen_clip=True)
            npt.assert_equal(os.path.isfile('fury_2.png'), True)
            arr = io.load_image('fury_2.png')

            assert_less_equal(arr.shape[0], 5000)
            assert_less_equal(arr.shape[1], 5000)
Esempio n. 17
0
from fury import window, actor, utils, io
from fury.data import read_viz_textures, fetch_viz_textures
import math
import numpy as np
import itertools

###############################################################################
# Create a new scene, and load in the image of the Earth using
# ``fetch_viz_textures`` and ``read_viz_textures``. We will use a 16k
# resolution texture for maximum detail.

scene = window.Scene()

fetch_viz_textures()
earth_file = read_viz_textures("1_earth_16k.jpg")
earth_image = io.load_image(earth_file)
earth_actor = actor.texture_on_sphere(earth_image)
scene.add(earth_actor)

###############################################################################
# Rotate the Earth to make sure the texture is correctly oriented. Change it's
# scale using ``actor.SetScale()``.

utils.rotate(earth_actor, (-90, 1, 0, 0))
utils.rotate(earth_actor, (180, 0, 1, 0))
earth_actor.SetScale(2, 2, 2)

###############################################################################
# Define the function to convert geographical coordinates of a location in
# latitude and longitude degrees to coordinates on the ``earth_actor`` surface.
# In this function, convert to radians, then to spherical coordinates, and
Esempio n. 18
0
##############################################################################
# Create a scene to start.

scene = window.Scene()

##############################################################################
# Next, load in a texture for each of the actors. For this tutorial, we will
# be creating one textured sphere for the Earth, and another for the moon.
# Collect the Earth texture from the FURY github using ``fetch_viz_textures``
# and  ``read_viz_textures``, then use ``io.load_image`` to load in the
# image.

fetch_viz_textures()
earth_filename = read_viz_textures("1_earth_8k.jpg")
earth_image = io.load_image(earth_filename)

##############################################################################
# Using ``actor.texture_on_sphere()``, create an earth_actor with your newly
# loaded texture.

earth_actor = actor.texture_on_sphere(earth_image)

##############################################################################
# Then, do the same for the moon.

moon_filename = read_viz_textures("moon-8k.jpg")
moon_image = io.load_image(moon_filename)

moon_actor = actor.texture_on_sphere(moon_image)
Esempio n. 19
0
def test_save_load_image():
    l_ext = ["png", "jpeg", "jpg", "bmp", "tiff"]
    fury_logo_link = 'https://raw.githubusercontent.com/fury-gl/'\
                     'fury-communication-assets/main/fury-logo.png'

    invalid_link = 'https://picsum.photos/200'
    fname = "temp-io"

    for ext in l_ext:
        with InTemporaryDirectory() as odir:
            data = np.random.randint(0, 255, size=(50, 3), dtype=np.uint8)
            url_image = load_image(fury_logo_link)

            url_fname_path = pjoin(odir, f'fury_logo.{ext}')
            fname_path = pjoin(odir, "{0}.{1}".format(fname, ext))

            save_image(data, fname_path, compression_quality=100)
            save_image(url_image, url_fname_path, compression_quality=100)

            npt.assert_equal(os.path.isfile(fname_path), True)
            npt.assert_equal(os.path.isfile(url_fname_path), True)

            assert_greater(os.stat(fname_path).st_size, 0)
            assert_greater(os.stat(url_fname_path).st_size, 0)

            out_image = load_image(fname_path)
            if ext not in ["jpeg", "jpg", "tiff"]:
                npt.assert_array_equal(data[..., 0], out_image[..., 0])
            else:

                npt.assert_array_almost_equal(data[..., 0],
                                              out_image[..., 0],
                                              decimal=0)

    npt.assert_raises(IOError, load_image, invalid_link)
    npt.assert_raises(IOError, load_image, "test.vtk")
    npt.assert_raises(IOError, load_image, "test.vtk", use_pillow=False)
    npt.assert_raises(IOError, save_image,
                      np.random.randint(0, 255, size=(50, 3)), "test.vtk")
    npt.assert_raises(IOError,
                      save_image,
                      np.random.randint(0, 255, size=(50, 3)),
                      "test.vtk",
                      use_pillow=False)
    npt.assert_raises(IOError, save_image,
                      np.random.randint(0, 255, size=(50, 3, 1, 1)),
                      "test.png")

    compression_type = [None, "lzw"]

    for ct in compression_type:
        with InTemporaryDirectory() as odir:
            try:
                data = np.random.randint(0, 255, size=(50, 3), dtype=np.uint8)
                fname_path = pjoin(odir, "{0}.tif".format(fname))

                save_image(data,
                           fname_path,
                           compression_type=ct,
                           use_pillow=False)
                npt.assert_equal(os.path.isfile(fname_path), True)
                assert_greater(os.stat(fname_path).st_size, 0)
            except OSError:
                continue