Example #1
0
def test_contour_from_roi():

    # Render volume
    scene = window.Scene()
    data = np.zeros((50, 50, 50))
    data[20:30, 25, 25] = 1.
    data[25, 20:30, 25] = 1.
    affine = np.eye(4)
    surface = actor.contour_from_roi(data,
                                     affine,
                                     color=np.array([1, 0, 1]),
                                     opacity=.5)
    scene.add(surface)

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

    # Test Errors
    npt.assert_raises(ValueError, actor.contour_from_roi, np.ones(50))

    # Test binarization
    scene2 = window.Scene()
    data2 = np.zeros((50, 50, 50))
    data2[20:30, 25, 25] = 1.
    data2[35:40, 25, 25] = 1.
    affine = np.eye(4)
    surface2 = actor.contour_from_roi(data2,
                                      affine,
                                      color=np.array([0, 1, 1]),
                                      opacity=.5)
    scene2.add(surface2)

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

    arr = window.snapshot(scene, 'test_surface.png', offscreen=True)
    arr2 = window.snapshot(scene2, 'test_surface2.png', offscreen=True)

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

    npt.assert_equal(report.objects, 1)
    npt.assert_equal(report2.objects, 2)

    # test on real streamlines using tracking example
    if have_dipy:
        from dipy.data import read_stanford_labels
        from dipy.reconst.shm import CsaOdfModel
        from dipy.data import default_sphere
        from dipy.direction import peaks_from_model
        from fury.colormap import line_colors
        from dipy.tracking import utils
        try:
            from dipy.tracking.local import ThresholdTissueClassifier \
                as ThresholdStoppingCriterion
            from dipy.tracking.local import LocalTracking
        except ImportError:
            from dipy.tracking.stopping_criterion import \
                ThresholdStoppingCriterion
            from dipy.tracking.local_tracking import LocalTracking

        hardi_img, gtab, labels_img = read_stanford_labels()
        data = np.asanyarray(hardi_img.dataobj)
        labels = np.asanyarray(labels_img.dataobj)
        affine = hardi_img.affine

        white_matter = (labels == 1) | (labels == 2)

        csa_model = CsaOdfModel(gtab, sh_order=6)
        csa_peaks = peaks_from_model(csa_model,
                                     data,
                                     default_sphere,
                                     relative_peak_threshold=.8,
                                     min_separation_angle=45,
                                     mask=white_matter)

        classifier = ThresholdStoppingCriterion(csa_peaks.gfa, .25)

        seed_mask = labels == 2
        seeds = utils.seeds_from_mask(seed_mask,
                                      density=[1, 1, 1],
                                      affine=affine)

        # Initialization of LocalTracking.
        # The computation happens in the next step.
        streamlines = LocalTracking(csa_peaks,
                                    classifier,
                                    seeds,
                                    affine,
                                    step_size=2)

        # Compute streamlines and store as a list.
        streamlines = list(streamlines)

        # Prepare the display objects.
        streamlines_actor = actor.line(streamlines, line_colors(streamlines))
        seedroi_actor = actor.contour_from_roi(seed_mask, affine, [0, 1, 1],
                                               0.5)

        # Create the 3d display.
        r = window.Scene()
        r2 = window.Scene()
        r.add(streamlines_actor)
        arr3 = window.snapshot(r, 'test_surface3.png', offscreen=True)
        report3 = window.analyze_snapshot(arr3, find_objects=True)
        r2.add(streamlines_actor)
        r2.add(seedroi_actor)
        arr4 = window.snapshot(r2, 'test_surface4.png', offscreen=True)
        report4 = window.analyze_snapshot(arr4, find_objects=True)

        # assert that the seed ROI rendering is not far
        # away from the streamlines (affine error)
        npt.assert_equal(report3.objects, report4.objects)
Example #2
0
def test_manifest_standard(interactive=False):
    scene = window.Scene()  # Setup scene

    # Setup surface
    surface_actor = _generate_surface()
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(surface_actor)
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 1)

    scene.clear()  # Reset scene

    # Contour from roi setup
    data = np.zeros((50, 50, 50))
    data[20:30, 25, 25] = 1.
    data[25, 20:30, 25] = 1.
    affine = np.eye(4)
    surface = actor.contour_from_roi(data, affine, color=np.array([1, 0, 1]))
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(surface)
    scene.reset_camera()
    scene.reset_clipping_range()
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 1)

    scene.clear()  # Reset scene

    # Contour from label setup
    data = np.zeros((50, 50, 50))
    data[5:15, 1:10, 25] = 1.
    data[25:35, 1:10, 25] = 2.
    data[40:49, 1:10, 25] = 3.
    color = np.array([[255, 0, 0],
                      [0, 255, 0],
                      [0, 0, 255]])
    surface = actor.contour_from_label(data, color=color)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(surface)
    scene.reset_camera()
    scene.reset_clipping_range()
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 3)

    scene.clear()  # Reset scene

    # Streamtube setup
    data1 = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2.]])
    data2 = data1 + np.array([0.5, 0., 0.])
    data = [data1, data2]
    colors = np.array([[1, 0, 0], [0, 0, 1.]])
    tubes = actor.streamtube(data, colors, linewidth=.1)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(tubes)
    scene.reset_camera()
    scene.reset_clipping_range()
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 2)

    scene.clear()  # Reset scene

    # ODF slicer setup
    if have_dipy:
        from dipy.data import get_sphere
        from tempfile import mkstemp
        sphere = get_sphere('symmetric362')
        shape = (11, 11, 11, sphere.vertices.shape[0])
        fid, fname = mkstemp(suffix='_odf_slicer.mmap')
        odfs = np.memmap(fname, dtype=np.float64, mode='w+', shape=shape)
        odfs[:] = 1
        affine = np.eye(4)
        mask = np.ones(odfs.shape[:3])
        mask[:4, :4, :4] = 0
        odfs[..., 0] = 1
        odf_actor = actor.odf_slicer(odfs, affine, mask=mask, sphere=sphere,
                                     scale=.25, colormap='blues')
        material.manifest_standard(surface_actor, ambient_level=.3,
                                   diffuse_level=.25)
        k = 5
        I, J, _ = odfs.shape[:3]
        odf_actor.display_extent(0, I, 0, J, k, k)
        odf_actor.GetProperty().SetOpacity(1.0)
        scene.add(odf_actor)
        scene.reset_camera()
        scene.reset_clipping_range()
        arr = window.snapshot(scene)
        report = window.analyze_snapshot(arr)
        npt.assert_equal(report.objects, 11 * 11)

    scene.clear()  # Reset scene

    # Tensor slicer setup
    if have_dipy:
        from dipy.data import get_sphere
        sphere = get_sphere('symmetric724')
        evals = np.array([1.4, .35, .35]) * 10 ** (-3)
        evecs = np.eye(3)
        mevals = np.zeros((3, 2, 4, 3))
        mevecs = np.zeros((3, 2, 4, 3, 3))
        mevals[..., :] = evals
        mevecs[..., :, :] = evecs
        affine = np.eye(4)
        scene = window.Scene()
        tensor_actor = actor.tensor_slicer(mevals, mevecs, affine=affine,
                                           sphere=sphere, scale=.3)
        material.manifest_standard(surface_actor, ambient_level=.3,
                                   diffuse_level=.25)
        _, J, K = mevals.shape[:3]
        tensor_actor.display_extent(0, 1, 0, J, 0, K)
        scene.add(tensor_actor)
        scene.reset_camera()
        scene.reset_clipping_range()
        arr = window.snapshot(scene)
        report = window.analyze_snapshot(arr)
        npt.assert_equal(report.objects, 4)

    scene.clear()  # Reset scene

    # Point setup
    points = np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0]])
    colors = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    opacity = 0.5
    points_actor = actor.point(points, colors, opacity=opacity)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(points_actor)
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 3)

    scene.clear()  # Reset scene

    # Sphere setup
    xyzr = np.array([[0, 0, 0, 10], [100, 0, 0, 25], [200, 0, 0, 50]])
    colors = np.array([[1, 0, 0, 0.3], [0, 1, 0, 0.4], [0, 0, 1., 0.99]])
    opacity = 0.5
    sphere_actor = actor.sphere(centers=xyzr[:, :3], colors=colors[:],
                                radii=xyzr[:, 3], opacity=opacity)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(sphere_actor)
    scene.reset_camera()
    scene.reset_clipping_range()
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 3)

    scene.clear()  # Reset scene

    # Advanced geometry actors setup (Arrow, cone, cylinder)
    xyz = np.array([[0, 0, 0], [50, 0, 0], [100, 0, 0]])
    dirs = np.array([[0, 1, 0], [1, 0, 0], [0, 0.5, 0.5]])
    colors = np.array([[1, 0, 0, 0.3], [0, 1, 0, 0.4], [1, 1, 0, 1]])
    heights = np.array([5, 7, 10])
    actor_list = [[actor.cone, {'directions': dirs, 'resolution': 8}],
                  [actor.arrow, {'directions': dirs, 'resolution': 9}],
                  [actor.cylinder, {'directions': dirs}]]
    for act_func, extra_args in actor_list:
        aga_actor = act_func(centers=xyz, colors=colors[:], heights=heights,
                             **extra_args)
        material.manifest_standard(surface_actor, ambient_level=.3,
                                   diffuse_level=.25)
        scene.add(aga_actor)
        scene.reset_camera()
        scene.reset_clipping_range()
        arr = window.snapshot(scene)
        report = window.analyze_snapshot(arr)
        npt.assert_equal(report.objects, 3)
        scene.clear()

    # Basic geometry actors (Box, cube, frustum, octagonalprism, rectangle,
    # square)
    centers = np.array([[4, 0, 0], [0, 4, 0], [0, 0, 0]])
    colors = np.array([[1, 0, 0, 0.4], [0, 1, 0, 0.8], [0, 0, 1, 0.5]])
    directions = np.array([[1, 1, 0]])
    scale_list = [1, 2, (1, 1, 1), [3, 2, 1], np.array([1, 2, 3]),
                  np.array([[1, 2, 3], [1, 3, 2], [3, 1, 2]])]
    actor_list = [[actor.box, {}], [actor.cube, {}], [actor.frustum, {}],
                  [actor.octagonalprism, {}], [actor.rectangle, {}],
                  [actor.square, {}]]
    for act_func, extra_args in actor_list:
        for scale in scale_list:
            scene = window.Scene()
            bga_actor = act_func(centers=centers, directions=directions,
                                 colors=colors, scales=scale, **extra_args)
            material.manifest_standard(surface_actor, ambient_level=.3,
                                       diffuse_level=.25)
            scene.add(bga_actor)
            arr = window.snapshot(scene)
            report = window.analyze_snapshot(arr)
            msg = 'Failed with {}, scale={}'.format(act_func.__name__, scale)
            npt.assert_equal(report.objects, 3, err_msg=msg)
            scene.clear()

    # Cone setup using vertices
    centers = np.array([[0, 0, 0], [20, 0, 0], [40, 0, 0]])
    directions = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
    colors = np.array([[1, 0, 0, 0.3], [0, 1, 0, 0.4], [0, 0, 1., 0.99]])
    vertices = np.array([[0.0, 0.0, 0.0], [0.0, 10.0, 0.0],
                         [10.0, 0.0, 0.0], [0.0, 0.0, 10.0]])
    faces = np.array([[0, 1, 3], [0, 1, 2]])
    cone_actor = actor.cone(centers=centers, directions=directions,
                            colors=colors[:], vertices=vertices, faces=faces)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(cone_actor)
    scene.reset_camera()
    scene.reset_clipping_range()
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 3)

    scene.clear()  # Reset scene

    # Superquadric setup
    centers = np.array([[8, 0, 0], [0, 8, 0], [0, 0, 0]])
    colors = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    directions = np.random.rand(3, 3)
    scales = [1, 2, 3]
    roundness = np.array([[1, 1], [1, 2], [2, 1]])
    sq_actor = actor.superquadric(centers, roundness=roundness,
                                  directions=directions,
                                  colors=colors.astype(np.uint8),
                                  scales=scales)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(sq_actor)
    scene.reset_camera()
    scene.reset_clipping_range()
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    ft.assert_greater_equal(report.objects, 3)

    scene.clear()  # Reset scene

    # Label setup
    text_actor = actor.label("Hello")
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(text_actor)
    scene.reset_camera()
    scene.reset_clipping_range()
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 5)

    scene.clear()  # Reset scene

    # Texture setup
    arr = (255 * np.ones((512, 212, 4))).astype('uint8')
    arr[20:40, 20:40, :] = np.array([255, 0, 0, 255], dtype='uint8')
    tp2 = actor.texture(arr)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(tp2)
    scene.reset_camera()
    scene.reset_clipping_range()
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 1)

    scene.clear()  # Reset scene

    # Texture on sphere setup
    arr = 255 * np.ones((810, 1620, 3), dtype='uint8')
    rows, cols, _ = arr.shape
    rs = rows // 2
    cs = cols // 2
    w = 150 // 2
    arr[rs - w: rs + w, cs - 10 * w: cs + 10 * w] = np.array([255, 127, 0])
    tsa = actor.texture_on_sphere(arr)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(tsa)
    scene.reset_camera()
    scene.reset_clipping_range()
    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 1)

    # NOTE: From this point on, these actors don't have full support for PBR
    # interpolation. This is, the test passes but there is no evidence of the
    # desired effect.

    """
    # Setup slicer
    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)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(slicer)
    """

    """
    # Line setup
    data1 = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2.]])
    data2 = data1 + np.array([0.5, 0., 0.])
    data = [data1, data2]
    colors = np.array([[1, 0, 0], [0, 0, 1.]])
    lines = actor.line(data, colors, linewidth=5)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(lines)
    """

    """
    # Scalar bar setup
    lut = actor.colormap_lookup_table(
        scale_range=(0., 100.), hue_range=(0., 0.1), saturation_range=(1, 1),
        value_range=(1., 1))
    sb_actor = actor.scalar_bar(lut, ' ')
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(sb_actor)
    """

    """
    # Axes setup
    axes = actor.axes()
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(axes)
    """

    """
    # Peak slicer setup
    _peak_dirs = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype='f4')
    # peak_dirs.shape = (1, 1, 1) + peak_dirs.shape
    peak_dirs = np.zeros((11, 11, 11, 3, 3))
    peak_dirs[:, :, :] = _peak_dirs
    peak_actor = actor.peak_slicer(peak_dirs)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(peak_actor)
    """

    """
    # Dots setup
    points = np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0]])
    dots_actor = actor.dots(points, color=(0, 255, 0))
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(dots_actor)
    """

    """
    # Text3D setup
    msg = 'I \nlove\n FURY'
    txt_actor = actor.text_3d(msg)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(txt_actor)
    """

    """
    # Figure setup
    arr = (255 * np.ones((512, 212, 4))).astype('uint8')
    arr[20:40, 20:40, 3] = 0
    tp = actor.figure(arr)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(tp)
    """

    """
    # SDF setup
    centers = np.array([[2, 0, 0], [0, 2, 0], [0, 0, 0]]) * 11
    colors = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    directions = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
    scales = [1, 2, 3]
    primitive = ['sphere', 'ellipsoid', 'torus']

    sdf_actor = actor.sdf(centers, directions=directions, colors=colors,
                          primitives=primitive, scales=scales)
    material.manifest_standard(surface_actor, ambient_level=.3,
                               diffuse_level=.25)
    scene.add(sdf_actor)
    """

    # NOTE: For these last set of actors, there is not support for PBR
    # interpolation at all.

    """
    # Billboard setup
    centers = np.array([[0, 0, 0], [5, -5, 5], [-7, 7, -7], [10, 10, 10],
                        [10.5, 11.5, 11.5], [12, -12, -12], [-17, 17, 17],
                        [-22, -22, 22]])
    colors = np.array([[1, 1, 0], [0, 0, 0], [1, 0, 1], [0, 0, 1], [1, 1, 1],
                       [1, 0, 0], [0, 1, 0], [0, 1, 1]])
    scales = [6, .4, 1.2, 1, .2, .7, 3, 2]
    """
    fake_sphere = \
        """
        float len = length(point);
        float radius = 1.;
        if (len > radius)
            discard;
        vec3 normalizedPoint = normalize(vec3(point.xy, sqrt(1. - len)));
        vec3 direction = normalize(vec3(1., 1., 1.));
        float df_1 = max(0, dot(direction, normalizedPoint));
        float sf_1 = pow(df_1, 24);
        fragOutput0 = vec4(max(df_1 * color, sf_1 * vec3(1)), 1);
        """
    """
    billboard_actor = actor.billboard(centers, colors=colors, scales=scales,
                                      fs_impl=fake_sphere)
    material.manifest_pbr(billboard_actor)
    scene.add(billboard_actor)
    """

    if interactive:
        window.show(scene)
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()

    assert_inputs_exist(parser, args.in_volume)
    assert_outputs_exist(parser, args, args.out_image)

    output_names = [
        'axial_superior', 'axial_inferior', 'coronal_posterior',
        'coronal_anterior', 'sagittal_left', 'sagittal_right'
    ]

    for filename in args.in_bundles:
        if not is_header_compatible(args.in_volume, filename):
            parser.error('{} does not have a compatible header with {}'.format(
                filename, args.in_volume))

    output_dir = os.path.dirname(args.out_image)
    if output_dir:
        assert_output_dirs_exist_and_empty(parser,
                                           args,
                                           output_dir,
                                           create_dir=True)

    # ----------------------------------------------------------------------- #
    # Mosaic, column 0: orientation names and data description
    # ----------------------------------------------------------------------- #
    width = args.resolution_of_thumbnails
    height = args.resolution_of_thumbnails
    rows = 6
    cols = len(args.in_bundles)
    text_pos_x = 50
    text_pos_y = 50

    # Creates a new empty image, RGB mode
    mosaic = Image.new('RGB', ((cols + 1) * width, (rows + 1) * height))

    # Prepare draw and font objects to render text
    draw = ImageDraw.Draw(mosaic)
    font = get_font(args)

    # Data of the volume used as background
    ref_img = nib.load(args.in_volume)
    data = ref_img.get_fdata(dtype=np.float32)
    affine = ref_img.affine
    mean, std = data[data > 0].mean(), data[data > 0].std()
    value_range = (mean - 0.5 * std, mean + 1.5 * std)

    # First column with rows description
    draw_column_with_names(draw, output_names, text_pos_x, text_pos_y, height,
                           font)

    # ----------------------------------------------------------------------- #
    # Columns with bundles
    # ----------------------------------------------------------------------- #
    random.seed(args.random_coloring)
    for idx_bundle, bundle_file in enumerate(args.in_bundles):

        bundle_file_name = os.path.basename(bundle_file)
        bundle_name, bundle_ext = split_name_with_nii(bundle_file_name)

        # !! It creates a temporary folder to create
        # the images to concatenate in the mosaic !!
        output_bundle_dir = os.path.join(output_dir, bundle_name)
        if not os.path.isdir(output_bundle_dir):
            os.makedirs(output_bundle_dir)

        output_paths = [
            os.path.join(output_bundle_dir, '{}_' +
                         os.path.basename(output_bundle_dir)).format(name)
            for name in output_names
        ]

        i = (idx_bundle + 1) * width

        if not os.path.isfile(bundle_file):
            print('\nInput file {} doesn\'t exist.'.format(bundle_file))

            number_streamlines = 0

            view_number = 6
            j = height * view_number

            draw_bundle_information(draw, bundle_file_name, number_streamlines,
                                    i + text_pos_x, j + text_pos_y, font)

        else:
            if args.uniform_coloring:
                colors = args.uniform_coloring
            elif args.random_coloring is not None:
                colors = random_rgb()
            # Select the streamlines to plot
            if bundle_ext in ['.tck', '.trk']:
                if args.random_coloring is None and args.uniform_coloring is None:
                    colors = None
                bundle_tractogram_file = nib.streamlines.load(bundle_file)
                streamlines = bundle_tractogram_file.streamlines
                bundle_actor = actor.line(streamlines, colors)
                nbr_of_elem = len(streamlines)
            # Select the volume to plot
            elif bundle_ext in ['.nii.gz', '.nii']:
                if not args.random_coloring and not args.uniform_coloring:
                    colors = [1.0, 1.0, 1.0]
                bundle_img_file = nib.load(bundle_file)
                roi = get_data_as_mask(bundle_img_file)
                bundle_actor = actor.contour_from_roi(roi,
                                                      bundle_img_file.affine,
                                                      colors)
                nbr_of_elem = np.count_nonzero(roi)

            # Render
            ren = window.Scene()
            zoom = args.zoom
            opacity = args.opacity_background

            # Structural data
            slice_actor = actor.slicer(data, affine, value_range)
            slice_actor.opacity(opacity)
            ren.add(slice_actor)

            # Streamlines
            ren.add(bundle_actor)
            ren.reset_camera()
            ren.zoom(zoom)
            view_number = 0
            set_img_in_cell(mosaic, ren, view_number,
                            output_paths[view_number], width, height, i)

            ren.pitch(180)
            ren.reset_camera()
            ren.zoom(zoom)
            view_number = 1
            set_img_in_cell(mosaic, ren, view_number,
                            output_paths[view_number], width, height, i)

            ren.rm(slice_actor)
            slice_actor2 = slice_actor.copy()
            slice_actor2.display(None, slice_actor2.shape[1] // 2, None)
            slice_actor2.opacity(opacity)
            ren.add(slice_actor2)

            ren.pitch(90)
            ren.set_camera(view_up=(0, 0, 1))
            ren.reset_camera()
            ren.zoom(zoom)
            view_number = 2
            set_img_in_cell(mosaic, ren, view_number,
                            output_paths[view_number], width, height, i)

            ren.pitch(180)
            ren.set_camera(view_up=(0, 0, 1))
            ren.reset_camera()
            ren.zoom(zoom)
            view_number = 3
            set_img_in_cell(mosaic, ren, view_number,
                            output_paths[view_number], width, height, i)

            ren.rm(slice_actor2)
            slice_actor3 = slice_actor.copy()
            slice_actor3.display(slice_actor3.shape[0] // 2, None, None)
            slice_actor3.opacity(opacity)
            ren.add(slice_actor3)

            ren.yaw(90)
            ren.reset_camera()
            ren.zoom(zoom)
            view_number = 4
            set_img_in_cell(mosaic, ren, view_number,
                            output_paths[view_number], width, height, i)

            ren.yaw(180)
            ren.reset_camera()
            ren.zoom(zoom)
            view_number = 5
            set_img_in_cell(mosaic, ren, view_number,
                            output_paths[view_number], width, height, i)

            view_number = 6
            j = height * view_number
            draw_bundle_information(draw, bundle_file_name, nbr_of_elem,
                                    i + text_pos_x, j + text_pos_y, font)

        shutil.rmtree(output_bundle_dir)

    # Save image to file
    mosaic.save(args.out_image)
Example #4
0
def test_grid(_interactive=False):

    vol1 = np.zeros((100, 100, 100))
    vol1[25:75, 25:75, 25:75] = 100
    contour_actor1 = actor.contour_from_roi(vol1, np.eye(4), (1., 0, 0), 1.)

    vol2 = np.zeros((100, 100, 100))
    vol2[25:75, 25:75, 25:75] = 100

    contour_actor2 = actor.contour_from_roi(vol2, np.eye(4), (1., 0.5, 0), 1.)
    vol3 = np.zeros((100, 100, 100))
    vol3[25:75, 25:75, 25:75] = 100

    contour_actor3 = actor.contour_from_roi(vol3, np.eye(4), (1., 0.5, 0.5),
                                            1.)

    scene = window.Scene()
    actors = []
    texts = []

    actors.append(contour_actor1)
    text_actor1 = actor.text_3d('cube 1', justification='center')
    texts.append(text_actor1)

    actors.append(contour_actor2)
    text_actor2 = actor.text_3d('cube 2', justification='center')
    texts.append(text_actor2)

    actors.append(contour_actor3)
    text_actor3 = actor.text_3d('cube 3', justification='center')
    texts.append(text_actor3)

    actors.append(shallow_copy(contour_actor1))
    text_actor1 = 'cube 4'
    texts.append(text_actor1)

    actors.append(shallow_copy(contour_actor2))
    text_actor2 = 'cube 5'
    texts.append(text_actor2)

    actors.append(shallow_copy(contour_actor3))
    text_actor3 = 'cube 6'
    texts.append(text_actor3)

    # show the grid without the captions
    container = grid(actors=actors,
                     captions=None,
                     caption_offset=(0, -40, 0),
                     cell_padding=(10, 10),
                     dim=(2, 3))

    scene.add(container)

    scene.projection('orthogonal')

    counter = itertools.count()

    show_m = window.ShowManager(scene)

    show_m.initialize()

    def timer_callback(_obj, _event):
        cnt = next(counter)
        # show_m.scene.zoom(1)
        show_m.render()
        if cnt == 4:
            show_m.exit()
            show_m.destroy_timers()

    show_m.add_timer_callback(True, 200, timer_callback)
    show_m.start()

    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects, 6)

    scene.rm_all()

    counter = itertools.count()
    show_m = window.ShowManager(scene)
    show_m.initialize()
    # show the grid with the captions
    container = grid(actors=actors,
                     captions=texts,
                     caption_offset=(0, -50, 0),
                     cell_padding=(10, 10),
                     dim=(3, 3))

    scene.add(container)

    show_m.add_timer_callback(True, 200, timer_callback)
    show_m.start()

    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects > 6, True)
showManager = window.ShowManager()

# Renderer
renderer = showManager.scene


## inital view

# streamlines
stream_actor = actor.line(streamlines)
renderer.add(stream_actor)

# ROI
roiActor = actor.contour_from_roi(handknob_left.get_data(),
                                  affine=handknob_left.affine,
                                  color=np.array([1, 0, 0]),
                                  opacity=0.5)
renderer.AddActor(roiActor)
roiActor = actor.contour_from_roi(handknob_right.get_data(),
                                  affine=handknob_right.affine,
                                  color=np.array([0, 0, 1]),
                                  opacity=0.5)
renderer.AddActor(roiActor)

# Render Window
renderWindow = showManager.window
renderWindow.AddRenderer(renderer)

# Interactor
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)
Example #6
0
def test_grid_ui(interactive=False):

    vol1 = np.zeros((100, 100, 100))
    vol1[25:75, 25:75, 25:75] = 100

    colors = distinguishable_colormap(nb_colors=3)
    contour_actor1 = actor.contour_from_roi(vol1, np.eye(4), colors[0], 1.)

    vol2 = np.zeros((100, 100, 100))
    vol2[25:75, 25:75, 25:75] = 100

    contour_actor2 = actor.contour_from_roi(vol2, np.eye(4), colors[1], 1.)

    vol3 = np.zeros((100, 100, 100))
    vol3[25:75, 25:75, 25:75] = 100

    contour_actor3 = actor.contour_from_roi(vol3, np.eye(4), colors[2], 1.)

    scene = window.Scene()
    actors = []
    texts = []

    actors.append(contour_actor1)
    text_actor1 = actor.text_3d('cube 1', justification='center')
    texts.append(text_actor1)

    actors.append(contour_actor2)
    text_actor2 = actor.text_3d('cube 2', justification='center')
    texts.append(text_actor2)

    actors.append(contour_actor3)
    text_actor3 = actor.text_3d('cube 3', justification='center')
    texts.append(text_actor3)

    actors.append(shallow_copy(contour_actor1))
    text_actor1 = actor.text_3d('cube 4', justification='center')
    texts.append(text_actor1)

    actors.append(shallow_copy(contour_actor2))
    text_actor2 = actor.text_3d('cube 5', justification='center')
    texts.append(text_actor2)

    actors.append(shallow_copy(contour_actor3))
    text_actor3 = actor.text_3d('cube 6', justification='center')
    texts.append(text_actor3)

    actors.append(shallow_copy(contour_actor1))
    text_actor1 = actor.text_3d('cube 7', justification='center')
    texts.append(text_actor1)

    actors.append(shallow_copy(contour_actor2))
    text_actor2 = actor.text_3d('cube 8', justification='center')
    texts.append(text_actor2)

    actors.append(shallow_copy(contour_actor3))
    text_actor3 = actor.text_3d('cube 9', justification='center')
    texts.append(text_actor3)

    counter = itertools.count()
    show_m = window.ShowManager(scene)
    show_m.initialize()

    def timer_callback(_obj, _event):
        cnt = next(counter)
        show_m.scene.zoom(1)
        show_m.render()
        if cnt == 10:
            show_m.exit()

    # show the grid with the captions
    grid_ui = ui.GridUI(actors=actors,
                        captions=texts,
                        caption_offset=(0, -50, 0),
                        cell_padding=(60, 60),
                        dim=(3, 3),
                        rotation_axis=(1, 0, 0))

    scene.add(grid_ui)

    show_m.add_timer_callback(True, 200, timer_callback)
    show_m.start()

    arr = window.snapshot(scene)
    report = window.analyze_snapshot(arr)
    npt.assert_equal(report.objects > 9, True)

    # this needs to happen automatically when start() ends.
    for act in actors:
        act.RemoveAllObservers()

    filename = "test_grid_ui"
    recording_filename = pjoin(DATA_DIR, filename + ".log.gz")
    expected_events_counts_filename = pjoin(DATA_DIR, filename + ".pkl")

    current_size = (900, 600)
    scene = window.Scene()
    show_manager = window.ShowManager(scene,
                                      size=current_size,
                                      title="FURY GridUI")
    show_manager.initialize()

    grid_ui2 = ui.GridUI(actors=actors,
                         captions=texts,
                         caption_offset=(0, -50, 0),
                         cell_padding=(60, 60),
                         dim=(3, 3),
                         rotation_axis=None)

    scene.add(grid_ui2)

    event_counter = EventCounter()
    event_counter.monitor(grid_ui2)

    if interactive:
        show_manager.start()
    recording = False

    if recording:
        # Record the following events
        # 1. Left click on top left box (will rotate the box)
        show_manager.record_events_to_file(recording_filename)
        print(list(event_counter.events_counts.items()))
        event_counter.save(expected_events_counts_filename)

    else:
        show_manager.play_events_from_file(recording_filename)
        expected = EventCounter.load(expected_events_counts_filename)
        event_counter.check_counts(expected)
Example #7
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')

    scene = window.Scene()  # Setup scene

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

    # scene.reset_camera()
    # window.show(scene)
    ss = window.snapshot(scene, size=(200, 200))
    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
    # TODO: check if camera affects this assert
    # npt.assert_array_almost_equal(actual, desired, decimal=2)

    # Test ambient level
    material.manifest_standard(test_actor, ambient_level=1)
    ss = window.snapshot(scene, size=(200, 200))
    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))
    ss = window.snapshot(scene, size=(200, 200))
    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
    # TODO: check what affects this
    # npt.assert_array_almost_equal(actual, desired, decimal=2)

    # Test diffuse level
    material.manifest_standard(test_actor, diffuse_level=.75)
    ss = window.snapshot(scene, size=(200, 200))
    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
    # TODO: check what affects this
    # 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))
    ss = window.snapshot(scene, size=(200, 200))
    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
    # TODO: check what affects the line below
    # npt.assert_array_almost_equal(actual, desired, decimal=2)

    # Test specular level
    material.manifest_standard(test_actor, specular_level=1)
    ss = window.snapshot(scene, size=(200, 200))
    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
    # TODO: check what affects the line below
    # npt.assert_array_almost_equal(actual, desired, decimal=2)

    # Test specular power
    material.manifest_standard(test_actor, specular_level=1,
                               specular_power=5)
    ss = window.snapshot(scene, size=(200, 200))
    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
    # TODO: check what affects the line below
    # 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)
    ss = window.snapshot(scene, size=(200, 200))
    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
    # TODO: check what affects the line below
    # 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)

    ss = window.snapshot(scene, size=(200, 200))
    actual = ss[90, 110, :] / 1000
    desired = np.array([253, 0, 253]) / 1000
    # TODO: check what affects the line below
    # npt.assert_array_almost_equal(actual, desired, decimal=2)
    actual = ss[90, 60, :] / 1000
    desired = np.array([180, 0, 180]) / 1000
    # TODO: check what affects the line below
    # npt.assert_array_almost_equal(actual, desired, decimal=2)

    material.manifest_standard(test_actor)
    ss = window.snapshot(scene, size=(200, 200))
    actual = ss[90, 110, :] / 1000
    desired = np.array([253, 253, 253]) / 1000
    # TODO: check what affects the line below
    # npt.assert_array_almost_equal(actual, desired, decimal=2)
    actual = ss[90, 60, :] / 1000
    desired = np.array([180, 180, 180]) / 1000
    # TODO: check what affects the line below
    # npt.assert_array_almost_equal(actual, desired, decimal=2)

    material.manifest_standard(test_actor, diffuse_color=(1, 0, 1))
    ss = window.snapshot(scene, size=(200, 200))
    actual = ss[90, 110, :] / 1000
    desired = np.array([253, 0, 253]) / 1000
    # TODO: check what affects the line below
    # npt.assert_array_almost_equal(actual, desired, decimal=2)
    actual = ss[90, 60, :] / 1000
    desired = np.array([180, 0, 180]) / 1000
Example #8
0
def structural_plotting(conn_matrix,
                        uatlas,
                        streamlines_mni,
                        template_mask,
                        interactive=False):
    """

    :param conn_matrix:
    :param uatlas:
    :param streamlines_mni:
    :param template_mask:
    :param interactive:
    :return:
    """
    import nibabel as nib
    import numpy as np
    import networkx as nx
    import os
    import pkg_resources
    from nibabel.affines import apply_affine
    from fury import actor, window, colormap, ui
    from dipy.tracking.utils import streamline_near_roi
    from nilearn.plotting import find_parcellation_cut_coords
    from nilearn.image import resample_to_img
    from pynets.thresholding import normalize
    from pynets.nodemaker import mmToVox

    ch2better_loc = pkg_resources.resource_filename(
        "pynets", "templates/ch2better.nii.gz")

    # Instantiate scene
    r = window.Renderer()

    # Set camera
    r.set_camera(position=(-176.42, 118.52, 128.20),
                 focal_point=(113.30, 128.31, 76.56),
                 view_up=(0.18, 0.00, 0.98))

    # Load atlas rois
    atlas_img = nib.load(uatlas)
    atlas_img_data = atlas_img.get_data()

    # Collapse list of connected streamlines for visualization
    streamlines = nib.streamlines.load(streamlines_mni).streamlines
    parcels = []
    i = 0
    for roi in np.unique(atlas_img_data)[1:]:
        parcels.append(atlas_img_data == roi)
        i = i + 1

    # Add streamlines as cloud of 'white-matter'
    streamlines_actor = actor.line(streamlines,
                                   colormap.create_colormap(np.ones(
                                       [len(streamlines)]),
                                                            name='Greys_r',
                                                            auto=True),
                                   lod_points=10000,
                                   depth_cue=True,
                                   linewidth=0.2,
                                   fake_tube=True,
                                   opacity=1.0)
    r.add(streamlines_actor)

    # Creat palette of roi colors and add them to the scene as faint contours
    roi_colors = np.random.rand(int(np.max(atlas_img_data)), 3)
    parcel_contours = []
    i = 0
    for roi in np.unique(atlas_img_data)[1:]:
        include_roi_coords = np.array(np.where(atlas_img_data == roi)).T
        x_include_roi_coords = apply_affine(np.eye(4), include_roi_coords)
        bool_list = []
        for sl in streamlines:
            bool_list.append(
                streamline_near_roi(sl,
                                    x_include_roi_coords,
                                    tol=1.0,
                                    mode='either_end'))
        if sum(bool_list) > 0:
            print('ROI: ' + str(i))
            parcel_contours.append(
                actor.contour_from_roi(atlas_img_data == roi,
                                       color=roi_colors[i],
                                       opacity=0.2))
        else:
            pass
        i = i + 1

    for vol_actor in parcel_contours:
        r.add(vol_actor)

    # Get voxel coordinates of parcels and add them as 3d spherical centroid nodes
    [coords, labels] = find_parcellation_cut_coords(atlas_img,
                                                    background_label=0,
                                                    return_labels=True)

    coords_vox = []
    for i in coords:
        coords_vox.append(mmToVox(atlas_img.affine, i))
    coords_vox = list(set(list(tuple(x) for x in coords_vox)))

    # Build an edge list of 3d lines
    G = nx.from_numpy_array(normalize(conn_matrix))
    for i in G.nodes():
        nx.set_node_attributes(G, {i: coords_vox[i]}, labels[i])

    G.remove_nodes_from(list(nx.isolates(G)))
    G_filt = nx.Graph()
    fedges = filter(lambda x: G.degree()[x[0]] > 0 and G.degree()[x[1]] > 0,
                    G.edges())
    G_filt.add_edges_from(fedges)

    coord_nodes = []
    for i in range(len(G.edges())):
        edge = list(G.edges())[i]
        [x, y] = edge
        x_coord = list(G.nodes[x].values())[0]
        x_label = list(G.nodes[x].keys())[0]
        l_x = actor.label(text=str(x_label),
                          pos=x_coord,
                          scale=(1, 1, 1),
                          color=(50, 50, 50))
        r.add(l_x)
        y_coord = list(G.nodes[y].values())[0]
        y_label = list(G.nodes[y].keys())[0]
        l_y = actor.label(text=str(y_label),
                          pos=y_coord,
                          scale=(1, 1, 1),
                          color=(50, 50, 50))
        r.add(l_y)
        coord_nodes.append(x_coord)
        coord_nodes.append(y_coord)
        c = actor.line([(x_coord, y_coord)],
                       window.colors.coral,
                       linewidth=100 * (float(G.get_edge_data(x, y)['weight']))
                       ^ 2)
        r.add(c)

    point_actor = actor.point(list(set(coord_nodes)),
                              window.colors.grey,
                              point_radius=0.75)
    r.add(point_actor)

    # Load glass brain template and resample to MNI152_2mm brain
    template_img = nib.load(ch2better_loc)
    template_target_img = nib.load(template_mask)
    res_brain_img = resample_to_img(template_img, template_target_img)
    template_img_data = res_brain_img.get_data().astype('bool')
    template_actor = actor.contour_from_roi(template_img_data,
                                            color=(50, 50, 50),
                                            opacity=0.05)
    r.add(template_actor)

    # Show scene
    if interactive is True:
        window.show(r, size=(600, 600), reset_camera=False)
    else:
        fig_path = os.path.dirname(streamlines_mni) + '/3d_connectome_fig.png'
        window.record(r, out_path=fig_path, size=(600, 600))

    return
Example #9
0
    #         pass
    #     i = i + 1

    visible_callback.parcel_contours = parcel_contours
    # for vol_actor in parcel_contours:
    #     # vol_actor.AddObserver('LeftButtonPressEvent',
    #     #                       point_left_click_callback,
    #     #                       1.0)
    #     scene.add(vol_actor)

    # Load glass brain template and resample to MNI152_2mm brain
    template_img = nib.load(ch2bet)
    template_target_img = nib.load(ch2bet_target)
    res_brain_img = resample_to_img(template_img, template_target_img)
    template_img_data = res_brain_img.get_data().astype('bool')
    template_actor = actor.contour_from_roi(template_img_data, color=(50, 50, 50), opacity=0.05)
    scene.add(template_actor)
    visible_callback.brain_actor = template_actor

    # Get voxel coordinates of parcels and add them as 3d spherical centroid nodes
    [coords, label_names] = find_parcellation_cut_coords(atlas_img, background_label=0, return_label_names=True)

    coords_vox = []
    for i in coords:
        coords_vox.append(mmToVox(atlas_img, i))
    coords_vox = list(set(list(tuple(x) for x in coords_vox)))

    # Build an edge list of 3d lines
    df = pd.read_csv(graph_properties)
    node_cols = [s for s in list(df.columns) if isinstance(s, int) or any(c.isdigit() for c in s)]
Example #10
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)
Example #11
0
###############################################################################
# We will create a streamline actor from the streamlines.

streamlines_actor = actor.line(streamlines, line_colors(streamlines))

###############################################################################
# Next, we create a surface actor from the corpus callosum seed ROI. We
# provide the ROI data, the affine, the color in [R,G,B], and the opacity as
# a decimal between zero and one. Here, we set the color as blue/green with
# 50% opacity.

surface_opacity = 0.5
surface_color = [0, 1, 1]

seedroi_actor = actor.contour_from_roi(seed_mask, affine, surface_color,
                                       surface_opacity)

###############################################################################
# Next, we initialize a ''Renderer'' object and add both actors
# to the rendering.

ren = window.Renderer()
ren.add(streamlines_actor)
ren.add(seedroi_actor)

###############################################################################
# If you uncomment the following line, the rendering will pop up in an
# interactive window.

interactive = False
if interactive: