示例#1
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)
示例#2
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
示例#3
0
def test_load_sprite_sheet():
    sprite_URL = 'https://raw.githubusercontent.com/'\
                 'antrikshmisri/DATA/master/fury/0yKFTBQ.png'

    with InTemporaryDirectory() as tdir:
        sprites = load_sprite_sheet(sprite_URL, 5, 5)

        for idx, sprite in enumerate(list(sprites.values())):
            img_name = f"{idx}.png"
            save_image(sprite, os.path.join(tdir, img_name))

        sprite_count = len(os.listdir(tdir))
        npt.assert_equal(sprite_count, 25)

        vtktype_sprites = load_sprite_sheet(sprite_URL, 5, 5, as_vtktype=True)

        for vtk_sprite in list(vtktype_sprites.values()):
            npt.assert_equal(isinstance(vtk_sprite, ImageData), True)
示例#4
0
def test_load_cubemap_texture():
    l_ext = ['jpg', 'jpeg', 'png', 'bmp', 'tif', 'tiff']
    for ext in l_ext:
        with InTemporaryDirectory() as odir:
            data = np.random.randint(0, 255, size=(50, 50, 3), dtype=np.uint8)
            fname_path = pjoin(odir, f'test.{ext}')
            save_image(data, fname_path)

            fnames = [fname_path] * 5
            npt.assert_raises(IOError, load_cubemap_texture, fnames)

            fnames = [fname_path] * 6
            texture = load_cubemap_texture(fnames)
            npt.assert_equal(texture.GetCubeMap(), True)
            npt.assert_equal(texture.GetMipmap(), True)
            npt.assert_equal(texture.GetInterpolate(), 1)
            npt.assert_equal(texture.GetNumberOfInputPorts(), 6)
            npt.assert_equal(
                texture.GetInputDataObject(0, 0).GetDimensions(), (50, 50, 1))

            fnames = [fname_path] * 7
            npt.assert_raises(IOError, load_cubemap_texture, fnames)
示例#5
0
def snapshot(scene, fname=None, size=(300, 300), offscreen=True,
             order_transparent=False, stereo='off',
             multi_samples=8, max_peels=4,
             occlusion_ratio=0.0):
    """Save a snapshot of the scene in a file or in memory.

    Parameters
    -----------
    scene : Scene() or vtkRenderer
        Scene instance
    fname : str or None
        Save PNG file. If None return only an array without saving PNG.
    size : (int, int)
        ``(width, height)`` of the window. Default is (300, 300).
    offscreen : bool
        Default True. Go stealth mode no window should appear.
    order_transparent : bool
        Default False. Use depth peeling to sort transparent objects.
        If True also enables anti-aliasing.

    stereo: string
        Set the stereo type. Default is 'off'. Other types include:

        * 'opengl': OpenGL frame-sequential stereo. Referred to as
          'CrystalEyes' by VTK.
        * 'anaglyph': For use with red/blue glasses. See VTK docs to
          use different colors.
        * 'interlaced': Line interlaced.
        * 'checkerboard': Checkerboard interlaced.
        * 'left': Left eye only.
        * 'right': Right eye only.
        * 'horizontal': Side-by-side.

    multi_samples : int
        Number of samples for anti-aliazing (Default 8).
        For no anti-aliasing use 0.
    max_peels : int
        Maximum number of peels for depth peeling (Default 4).
    occlusion_ratio : float
        Occlusion ration for depth peeling (Default 0 - exact image).

    Returns
    -------
    arr : ndarray
        Color array of size (width, height, 3) where the last dimension
        holds the RGB values.

    """
    width, height = size

    render_window = RenderWindow()
    if offscreen:
        render_window.SetOffScreenRendering(1)
    if stereo.lower() != 'off':
        enable_stereo(render_window, stereo)
    render_window.AddRenderer(scene)
    render_window.SetSize(width, height)

    if order_transparent:
        antialiasing(scene, render_window, multi_samples, max_peels,
                     occlusion_ratio)

    render_window.Render()

    window_to_image_filter = WindowToImageFilter()
    window_to_image_filter.SetInput(render_window)
    window_to_image_filter.Update()

    vtk_image = window_to_image_filter.GetOutput()
    h, w, _ = vtk_image.GetDimensions()
    vtk_array = vtk_image.GetPointData().GetScalars()
    components = vtk_array.GetNumberOfComponents()
    arr = numpy_support.vtk_to_numpy(vtk_array).reshape(w, h, components)

    if fname is None:
        return arr

    save_image(arr, fname)
    return arr
示例#6
0
def record(scene=None, cam_pos=None, cam_focal=None, cam_view=None,
           out_path=None, path_numbering=False, n_frames=1, az_ang=10,
           magnification=1, size=(300, 300), reset_camera=True,
           screen_clip=False, stereo='off', verbose=False):
    """Record a video of your scene.

    Records a video as a series of ``.png`` files of your scene by rotating the
    azimuth angle az_angle in every frame.

    Parameters
    -----------
    scene : Scene() or vtkRenderer() object
        Scene instance
    cam_pos : None or sequence (3,), optional
        Camera's position. If None then default camera's position is used.
    cam_focal : None or sequence (3,), optional
        Camera's focal point. If None then default camera's focal point is
        used.
    cam_view : None or sequence (3,), optional
        Camera's view up direction. If None then default camera's view up
        vector is used.
    out_path : str, optional
        Output path for the frames. If None a default fury.png is created.
    path_numbering : bool
        When recording it changes out_path to out_path + str(frame number)
    n_frames : int, optional
        Number of frames to save, default 1
    az_ang : float, optional
        Azimuthal angle of camera rotation.
    magnification : int, optional
        How much to magnify the saved frame. Default is 1. A value greater
        than 1 increases the quality of the image. However, the output
        size will be larger. For example, 200x200 image with magnification
        of 2 will be a 400x400 image.
    size : (int, int)
        ``(width, height)`` of the window. Default is (300, 300).
    screen_clip: bool
        Clip the png based on screen resolution. Default is False.
    reset_camera : bool
        If True Call ``scene.reset_camera()``. Otherwise you need to set the
         camera before calling this function.
    stereo: string
        Set the stereo type. Default is 'off'. Other types include:

        * 'opengl': OpenGL frame-sequential stereo. Referred to as
          'CrystalEyes' by VTK.
        * 'anaglyph': For use with red/blue glasses. See VTK docs to
          use different colors.
        * 'interlaced': Line interlaced.
        * 'checkerboard': Checkerboard interlaced.
        * 'left': Left eye only.
        * 'right': Right eye only.
        * 'horizontal': Side-by-side.

    verbose : bool
        print information about the camera. Default is False.

    Examples
    ---------
    >>> from fury import window, actor
    >>> scene = window.Scene()
    >>> a = actor.axes()
    >>> scene.add(a)
    >>> # uncomment below to record
    >>> # window.record(scene)
    >>> # check for new images in current directory

    """
    if scene is None:
        scene = Scene()

    renWin = RenderWindow()

    renWin.SetOffScreenRendering(1)
    renWin.SetBorders(screen_clip)
    renWin.AddRenderer(scene)
    renWin.SetSize(size[0], size[1])
    iren = RenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # scene.GetActiveCamera().Azimuth(180)

    if reset_camera:
        scene.ResetCamera()

    if stereo.lower() != 'off':
        enable_stereo(renWin, stereo)

    renderLarge = RenderLargeImage()
    renderLarge.SetInput(scene)
    renderLarge.SetMagnification(magnification)
    renderLarge.Update()

    ang = 0

    if cam_pos is not None:
        cx, cy, cz = cam_pos
        scene.GetActiveCamera().SetPosition(cx, cy, cz)
    if cam_focal is not None:
        fx, fy, fz = cam_focal
        scene.GetActiveCamera().SetFocalPoint(fx, fy, fz)
    if cam_view is not None:
        ux, uy, uz = cam_view
        scene.GetActiveCamera().SetViewUp(ux, uy, uz)

    cam = scene.GetActiveCamera()
    if verbose:
        print('Camera Position (%.2f, %.2f, %.2f)' % cam.GetPosition())
        print('Camera Focal Point (%.2f, %.2f, %.2f)' % cam.GetFocalPoint())
        print('Camera View Up (%.2f, %.2f, %.2f)' % cam.GetViewUp())

    for i in range(n_frames):
        scene.GetActiveCamera().Azimuth(ang)
        renderLarge = RenderLargeImage()
        renderLarge.SetInput(scene)
        renderLarge.SetMagnification(magnification)
        renderLarge.Update()

        if path_numbering:
            if out_path is None:
                filename = str(i).zfill(6) + '.png'
            else:
                filename = out_path + str(i).zfill(6) + '.png'
        else:
            if out_path is None:
                filename = 'fury.png'
            else:
                filename = out_path

        arr = numpy_support.vtk_to_numpy(renderLarge.GetOutput().GetPointData()
                                         .GetScalars())
        w, h, _ = renderLarge.GetOutput().GetDimensions()
        components = renderLarge.GetOutput().GetNumberOfScalarComponents()
        arr = arr.reshape((h, w, components))
        save_image(arr, filename)

        ang = +az_ang
示例#7
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