コード例 #1
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
コード例 #2
0
def test_save_and_load_polydata():
    l_ext = ["vtk", "fib", "ply", "xml"]
    fname = "temp-io"

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

            pd = vtk.vtkPolyData()
            pd.SetPoints(numpy_to_vtk_points(data))

            fname_path = pjoin(odir, "{0}.{1}".format(fname, ext))
            save_polydata(pd, fname_path)

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

            out_pd = load_polydata(fname_path)
            out_data = numpy_support.vtk_to_numpy(out_pd.GetPoints().GetData())

            npt.assert_array_equal(data, out_data)

    npt.assert_raises(IOError, save_polydata, vtk.vtkPolyData(), "test.vti")
    npt.assert_raises(IOError, save_polydata, vtk.vtkPolyData(), "test.obj")
    npt.assert_raises(IOError, load_polydata, "test.vti")
コード例 #3
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)
コード例 #4
0
def test_save_and_load_options():
    l_ext = ["ply", "vtk"]
    l_options = [{
        'color_array_name': 'horizon',
    }, {
        'binary': True,
    }]
    fname = "temp-io"

    for ext, option in zip(l_ext, l_options):
        with InTemporaryDirectory() as odir:
            data = np.random.randint(0, 255, size=(50, 3))

            pd = PolyData()
            pd.SetPoints(numpy_to_vtk_points(data))

            fname_path = pjoin(odir, "{0}.{1}".format(fname, ext))
            save_polydata(pd, fname_path, **option)

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

            out_pd = load_polydata(fname_path)
            out_data = numpy_support.vtk_to_numpy(out_pd.GetPoints().GetData())

            npt.assert_array_equal(data, out_data)

    l_ext = ["vtk", "vtp", "ply", "stl", "mni.obj"]
    l_options = [{}, {
        'binary': False,
    }]
    for ext, option in zip(l_ext, l_options):
        with InTemporaryDirectory() as odir:
            data = np.random.randint(0, 255, size=(50, 3))

            pd = PolyData()
            pd.SetPoints(numpy_to_vtk_points(data))

            fname_path = pjoin(odir, "{0}.{1}".format(fname, ext))
            save_polydata(pd, fname_path, **option)

            npt.assert_equal(os.path.isfile(fname_path), True)
            assert_greater(os.stat(fname_path).st_size, 0)
コード例 #5
0
def test_load_text():
    with InTemporaryDirectory() as tdir:
        test_file_name = 'test.txt'

        # Test file does not exist
        npt.assert_raises(IOError, load_text, test_file_name)

        # Saving file with content
        test_file_contents = 'This is some test text.'
        test_fname = os.path.join(tdir, test_file_name)
        test_file = open(test_fname, 'w')
        test_file.write(test_file_contents)
        test_file.close()

        npt.assert_string_equal(load_text(test_fname), test_file_contents)
コード例 #6
0
def test_load_shader():
    fname_test = 'test.text'

    # Test invalid file extension
    npt.assert_raises(IOError, load_shader, fname_test)

    with InTemporaryDirectory() as tdir:
        fname_test = 'test.frag'
        fname_test = os.path.join(tdir, fname_test)
        str_test = 'Test1'
        test_file = open(fname_test, 'w')
        test_file.write(str_test)
        test_file.close()

        npt.assert_string_equal(load_shader(fname_test), str_test)
コード例 #7
0
ファイル: io.py プロジェクト: m-agour/fury
def load_sprite_sheet(sheet_path, nb_rows, nb_cols, as_vtktype=False):
    """Process and load sprites from a sprite sheet.

    Parameters
    ----------
    sheet_path: str
        Path to the sprite sheet
    nb_rows: int
        Number of rows in the sprite sheet
    nb_cols: int
        Number of columns in the sprite sheet
    as_vtktype: bool, optional
        If True, the output is a vtkImageData

    Returns
    -------
    Dict containing the processed sprites.

    """
    sprite_dicts = {}
    sprite_sheet = load_image(sheet_path)
    width, height = sprite_sheet.shape[:2]

    sprite_size_x = int(np.ceil(width / nb_rows))
    sprite_size_y = int(np.ceil(height / nb_cols))

    for row, col in np.ndindex((nb_rows, nb_cols)):
        nxt_row = row + 1
        nxt_col = col + 1

        box = (row * sprite_size_x, col * sprite_size_y,
               nxt_row * sprite_size_x, nxt_col * sprite_size_y)

        sprite_arr = sprite_sheet[box[0]:box[2], box[1]:box[3]]
        if as_vtktype:
            with InTemporaryDirectory() as tdir:
                tmp_img_path = os.path.join(tdir, f'{row}{col}.png')
                save_image(sprite_arr, tmp_img_path, compression_quality=100)

                sprite_dicts[(row, col)] = load_image(tmp_img_path,
                                                      as_vtktype=True)
        else:
            sprite_dicts[(row, col)] = sprite_arr

    return sprite_dicts
コード例 #8
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)
コード例 #9
0
    def record_events(self):
        """Record events during the interaction.

        The recording is represented as a list of VTK events that happened
        during the interaction. The recorded events are then returned.

        Returns
        -------
        events : str
            Recorded events (one per line).

        Notes
        -----
        Since VTK only allows recording events to a file, we use a
        temporary file from which we then read the events.

        """
        with InTemporaryDirectory():
            filename = "recorded_events.log"
            recorder = InteractorEventRecorder()
            recorder.SetInteractor(self.iren)
            recorder.SetFileName(filename)

            def _stop_recording_and_close(_obj, _evt):
                if recorder:
                    recorder.Stop()
                self.iren.TerminateApp()

            self.iren.AddObserver("ExitEvent", _stop_recording_and_close)

            recorder.EnabledOn()
            recorder.Record()

            self.initialize()
            self.render()
            self.iren.Start()
            # Deleting this object is the unique way
            # to close the file.
            recorder = None
            # Retrieved recorded events.
            with open(filename, 'r') as f:
                events = f.read()
        return events
コード例 #10
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)
コード例 #11
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)
コード例 #12
0
def test_slicer(verbose=False):
    scene = window.Scene()
    data = (255 * np.random.rand(50, 50, 50))
    affine = np.eye(4)
    slicer = actor.slicer(data, affine, value_range=[data.min(), data.max()])
    slicer.display(None, None, 25)
    scene.add(slicer)

    scene.reset_camera()
    scene.reset_clipping_range()
    # window.show(scene)

    # copy pixels in numpy array directly
    arr = window.snapshot(scene, 'test_slicer.png', offscreen=True)

    if verbose:
        print(arr.sum())
        print(np.sum(arr == 0))
        print(np.sum(arr > 0))
        print(arr.shape)
        print(arr.dtype)

    report = window.analyze_snapshot(arr, find_objects=True)

    npt.assert_equal(report.objects, 1)
    # print(arr[..., 0])

    # The slicer can cut directly a smaller part of the image
    slicer.display_extent(10, 30, 10, 30, 35, 35)
    scene.ResetCamera()

    scene.add(slicer)

    # save pixels in png file not a numpy array
    with InTemporaryDirectory() as tmpdir:
        fname = os.path.join(tmpdir, 'slice.png')
        window.snapshot(scene, fname, offscreen=True)
        report = window.analyze_snapshot(fname, find_objects=True)
        npt.assert_equal(report.objects, 1)

    # Test Errors
    data_4d = (255 * np.random.rand(50, 50, 50, 50))
    npt.assert_raises(ValueError, actor.slicer, data_4d)
    npt.assert_raises(ValueError, actor.slicer, np.ones(10))

    scene.clear()

    rgb = np.zeros((30, 30, 30, 3), dtype='f8')
    rgb[..., 0] = 255
    rgb_actor = actor.slicer(rgb)

    scene.add(rgb_actor)

    scene.reset_camera()
    scene.reset_clipping_range()

    arr = window.snapshot(scene, offscreen=True)
    report = window.analyze_snapshot(arr, colors=[(255, 0, 0)])
    npt.assert_equal(report.objects, 1)
    npt.assert_equal(report.colors_found, [True])

    lut = actor.colormap_lookup_table(scale_range=(0, 255),
                                      hue_range=(0.4, 1.),
                                      saturation_range=(1, 1.),
                                      value_range=(0., 1.))
    scene.clear()
    slicer_lut = actor.slicer(data, lookup_colormap=lut)

    slicer_lut.display(10, None, None)
    slicer_lut.display(None, 10, None)
    slicer_lut.display(None, None, 10)

    slicer_lut.opacity(0.5)
    slicer_lut.tolerance(0.03)
    slicer_lut2 = slicer_lut.copy()
    npt.assert_equal(slicer_lut2.GetOpacity(), 0.5)
    npt.assert_equal(slicer_lut2.picker.GetTolerance(), 0.03)
    slicer_lut2.opacity(1)
    slicer_lut2.tolerance(0.025)
    slicer_lut2.display(None, None, 10)
    scene.add(slicer_lut2)

    scene.reset_clipping_range()

    arr = window.snapshot(scene, offscreen=True)
    report = window.analyze_snapshot(arr, find_objects=True)
    npt.assert_equal(report.objects, 1)

    scene.clear()

    data = (255 * np.random.rand(50, 50, 50))
    affine = np.diag([1, 3, 2, 1])
    slicer = actor.slicer(data, affine, interpolation='nearest')
    slicer.display(None, None, 25)

    scene.add(slicer)
    scene.reset_camera()
    scene.reset_clipping_range()

    arr = window.snapshot(scene, offscreen=True)
    report = window.analyze_snapshot(arr, find_objects=True)
    npt.assert_equal(report.objects, 1)
    npt.assert_equal(data.shape, slicer.shape)
    slicer2 = slicer.copy()
    npt.assert_equal(slicer2.shape, slicer.shape)
コード例 #13
0
ファイル: test_window.py プロジェクト: zoq/fury
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)
コード例 #14
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
コード例 #15
0
def test_ui_file_menu_2d(interactive=False):
    filename = "test_ui_file_menu_2d"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".json")

    tmpdir = InTemporaryDirectory()
    test_dir = os.path.join(tmpdir.name, "testdir")
    os.mkdir(test_dir)
    os.chdir(test_dir)
    os.mkdir(os.path.join(test_dir, "tempdir"))
    for i in range(10):
        open(os.path.join(test_dir, "tempdir", f"test{i}.txt"),
                'wt').close()
    open("testfile.txt", 'wt').close()

    filemenu = ui.FileMenu2D(size=(500, 500), extensions=["txt"],
                                directory_path=os.getcwd())

    # We will collect the sequence of files that have been selected.
    selected_files = []

    def _on_change():
        selected_files.append(list(filemenu.listbox.selected))

    # Set up a callback when selection changes.
    filemenu.listbox.on_change = _on_change

    # Assign the counter callback to every possible event.
    event_counter = EventCounter()
    event_counter.monitor(filemenu)

    # Create a show manager and record/play events.
    show_manager = window.ShowManager(size=(600, 600),
                                        title="FURY FileMenu")
    show_manager.scene.add(filemenu)

    # Recorded events:
    #  1. Click on 'testfile.txt'
    #  2. Click on 'tempdir/'
    #  3. Click on 'test0.txt'.
    #  4. Shift + Click on 'test6.txt'.
    #  5. Click on '../'.
    #  2. Click on 'testfile.txt'.
    show_manager.play_events_from_file(recording_filename)
    expected = EventCounter.load(expected_events_counts_filename)
    event_counter.check_counts(expected)

    # Check if the right files were selected.
    expected = [["testfile.txt"], ["tempdir"], ["test0.txt"],
                ["test0.txt", "test1.txt", "test2.txt", "test3.txt",
                "test4.txt", "test5.txt", "test6.txt"],
                ["../"], ["testfile.txt"]]

    npt.assert_equal(len(selected_files), len(expected))
    assert_arrays_equal(selected_files, expected)

    if interactive:
        filemenu = ui.FileMenu2D(size=(500, 500),
                                    directory_path=os.getcwd())
        show_manager = window.ShowManager(size=(600, 600),
                                            title="FURY FileMenu")
        show_manager.scene.add(filemenu)
        show_manager.start()

        shutil.rmtree(os.path.join(tmpdir.name, "testdir"))