예제 #1
0
def test_horizon_events():
    # using here MNI template affine 2009a
    affine = np.array([[1., 0., 0., -98.],
                       [0., 1., 0., -134.],
                       [0., 0., 1., -72.],
                       [0., 0., 0., 1.]])

    data = 255 * np.random.rand(197, 233, 189)
    vox_size = (1., 1., 1.)

    images = [(data, affine)]
    # images = None
    from dipy.segment.tests.test_bundles import setup_module
    setup_module()
    from dipy.segment.tests.test_bundles import f1
    streamlines = f1.copy()
    streamlines._data += np.array([-98., -134., -72.])

    header = create_nifti_header(affine, data.shape, vox_size)
    sft = StatefulTractogram(streamlines, header, Space.RASMM)

    tractograms = [sft]

    # select all centroids and expand and click everything else
    # do not press the key shortcuts as vtk generates warning that
    # blocks recording
    fname = os.path.join(DATA_DIR, 'record_horizon.log.gz')

    horizon(tractograms=tractograms, images=images, pams=None,
            cluster=True, cluster_thr=5.0,
            random_colors=False, length_gt=0, length_lt=np.inf,
            clusters_gt=0, clusters_lt=np.inf,
            world_coords=True, interactive=True, out_png='tmp.png',
            recorded_events=fname)
예제 #2
0
def test_horizon():

    s1 = 10 * np.array([[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0]],
                       dtype='f8')

    s2 = 10 * np.array([[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 4, 0]],
                       dtype='f8')

    s3 = 10 * np.array(
        [[0, 0, 0], [1, 0.2, 0], [2, 0.2, 0], [3, 0.2, 0], [4, 0.2, 0]],
        dtype='f8')

    print(s1.shape)
    print(s2.shape)
    print(s3.shape)

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    tractograms = [streamlines]
    images = None

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=False,
            interactive=False)

    affine = np.diag([2., 1, 1, 1]).astype('f8')

    data = 255 * np.random.rand(150, 150, 150)

    images = [(data, affine)]

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=True,
            interactive=False)
예제 #3
0
def test_horizon_events2():

    affine = np.diag([2., 1, 1, 1]).astype('f8')
    data = 255 * np.random.rand(150, 150, 150)
    images = [(data, affine)]
    from dipy.segment.tests.test_bundles import f1
    streamlines = f1.copy()
    tractograms = [streamlines]
    fname = os.path.join(DATA_DIR, 'record_02.log.gz')
    horizon(tractograms, images=images, cluster=False, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=True, recorded_events=fname)
예제 #4
0
def test_roi_images():
    np.random.seed(42)
    img1 = np.random.rand(5, 5, 5)
    img2 = np.zeros((5, 5, 5))
    img2[1, 1, 1] = 1
    img3 = np.zeros((5, 5, 5))
    img3[3, 3, 3] = 1
    images = [(img1, np.eye(4)), (img2, np.eye(4)), (img3, np.eye(4))]
    with TemporaryDirectory() as out_dir:
        tmp_fname = os.path.join(out_dir, 'tmp_x.png')

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

        # If roi_images=True, all th binary images are shown as contours
        horizon(images=images, roi_images=True, interactive=False,
                out_png=tmp_fname)
        npt.assert_equal(os.path.exists(tmp_fname), True)
        ss = load_image(tmp_fname)
        npt.assert_equal(ss[150, 800, :], [147, 0, 0])
예제 #5
0
파일: test_apps.py 프로젝트: arokem/dipy
def test_horizon():

    s1 = 10 * np.array([[0, 0, 0],
                        [1, 0, 0],
                        [2, 0, 0],
                        [3, 0, 0],
                        [4, 0, 0]], dtype='f8')

    s2 = 10 * np.array([[0, 0, 0],
                        [0, 1, 0],
                        [0, 2, 0],
                        [0, 3, 0],
                        [0, 4, 0]], dtype='f8')

    s3 = 10 * np.array([[0, 0, 0],
                        [1, 0.2, 0],
                        [2, 0.2, 0],
                        [3, 0.2, 0],
                        [4, 0.2, 0]], dtype='f8')

    print(s1.shape)
    print(s2.shape)
    print(s3.shape)

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    tractograms = [streamlines]
    images = None

    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=False, interactive=False)

    affine = np.diag([2., 1, 1, 1]).astype('f8')

    data = 255 * np.random.rand(150, 150, 150)

    images = [(data, affine)]

    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)

    tractograms = []
    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)
예제 #6
0
    def run(self,
            input_files,
            cluster=False,
            cluster_thr=15.,
            random_colors=False,
            length_gt=0,
            length_lt=1000,
            clusters_gt=0,
            clusters_lt=10**8,
            native_coords=False,
            stealth=False,
            emergency_header='icbm_2009a',
            bg_color=(0, 0, 0),
            disable_order_transparency=False,
            buan=False,
            buan_thr=0.5,
            buan_highlight=(1, 0, 0),
            out_dir='',
            out_stealth_png='tmp.png'):
        """ Interactive medical visualization - Invert the Horizon!

        Interact with any number of .trk, .tck or .dpy tractograms and anatomy
        files .nii or .nii.gz. Cluster streamlines on loading.

        Parameters
        ----------
        input_files : variable string
        cluster : bool, optional
            Enable QuickBundlesX clustering.
        cluster_thr : float, optional
            Distance threshold used for clustering. Default value 15.0 for
            small animal brains you may need to use something smaller such
            as 2.0. The distance is in mm. For this parameter to be active
            ``cluster`` should be enabled.
        random_colors : bool, optional
            Given multiple tractograms have been included then each tractogram
            will be shown with different color.
        length_gt : float, optional
            Clusters with average length greater than ``length_gt`` amount
            in mm will be shown.
        length_lt : float, optional
            Clusters with average length less than ``length_lt`` amount in
            mm will be shown.
        clusters_gt : int, optional
            Clusters with size greater than ``clusters_gt`` will be shown.
        clusters_lt : int, optional
            Clusters with size less than ``clusters_gt`` will be shown.
        native_coords : bool, optional
            Show results in native coordinates.
        stealth : bool, optional
            Do not use interactive mode just save figure.
        emergency_header : str, optional
            If no anatomy reference is provided an emergency header is
            provided. Current options 'icbm_2009a' and 'icbm_2009c'.
        bg_color : variable float, optional
            Define the background color of the scene. Colors can be defined
            with 1 or 3 values and should be between [0-1].
        disable_order_transparency : bool, optional
            Use depth peeling to sort transparent objects.
            If True also enables anti-aliasing.
        buan : bool, optional
            Enables BUAN framework visualization.
        buan_thr : float, optional
            Uses the threshold value to highlight segments on the
            bundle which have pvalues less than this threshold.
        buan_highlight : variable float, optional
            Define the bundle highlight area color. Colors can be defined
            with 1 or 3 values and should be between [0-1].
            For example, a value of (1, 0, 0) would mean the red color.
        out_dir : str, optional
            Output directory. (default current directory)
        out_stealth_png : str, optional
            Filename of saved picture.

        References
        ----------
        .. [Horizon_ISMRM19] Garyfallidis E., M-A. Cote, B.Q. Chandio,
            S. Fadnavis, J. Guaje, R. Aggarwal, E. St-Onge, K.S. Juneja,
            S. Koudoro, D. Reagan, DIPY Horizon: fast, modular, unified and
            adaptive visualization, Proceedings of: International Society of
            Magnetic Resonance in Medicine (ISMRM), Montreal, Canada, 2019.
        """
        verbose = True
        tractograms = []
        images = []
        pams = []
        numpy_files = []
        interactive = not stealth
        world_coords = not native_coords
        bundle_colors = None

        mni_2009a = {}
        mni_2009a['affine'] = np.array([[1., 0., 0.,
                                         -98.], [0., 1., 0., -134.],
                                        [0., 0., 1., -72.], [0., 0., 0., 1.]])
        mni_2009a['dims'] = (197, 233, 189)
        mni_2009a['vox_size'] = (1., 1., 1.)
        mni_2009a['vox_space'] = 'RAS'

        mni_2009c = {}
        mni_2009c['affine'] = np.array([[1., 0., 0.,
                                         -96.], [0., 1., 0., -132.],
                                        [0., 0., 1., -78.], [0., 0., 0., 1.]])
        mni_2009c['dims'] = (193, 229, 193)
        mni_2009c['vox_size'] = (1., 1., 1.)
        mni_2009c['vox_space'] = 'RAS'

        if emergency_header == 'icbm_2009a':
            hdr = mni_2009c
        else:
            hdr = mni_2009c
        emergency_ref = create_nifti_header(hdr['affine'], hdr['dims'],
                                            hdr['vox_size'])

        io_it = self.get_io_iterator()

        for input_output in io_it:

            fname = input_output[0]

            if verbose:
                print('Loading file ...')
                print(fname)
                print('\n')

            fl = fname.lower()
            ends = fl.endswith

            if ends('.trk'):

                sft = load_tractogram(fname, 'same', bbox_valid_check=False)
                tractograms.append(sft)

            if ends('.dpy') or ends('.tck'):
                sft = load_tractogram(fname, emergency_ref)
                tractograms.append(sft)

            if ends('.nii.gz') or ends('.nii'):

                data, affine = load_nifti(fname)
                images.append((data, affine))
                if verbose:
                    print('Affine to RAS')
                    np.set_printoptions(3, suppress=True)
                    print(affine)
                    np.set_printoptions()

            if ends(".pam5"):

                pam = load_peaks(fname)
                pams.append(pam)

                if verbose:
                    print('Peak_dirs shape')
                    print(pam.peak_dirs.shape)

            if ends(".npy"):

                data = np.load(fname)
                numpy_files.append(data)

                if verbose:
                    print('numpy array length')
                    print(len(data))

        if buan:
            bundle_colors = []

            for i in range(len(numpy_files)):

                n = len(numpy_files[i])
                pvalues = numpy_files[i]
                bundle = tractograms[i].streamlines

                indx = assignment_map(bundle, bundle, n)
                ind = np.array(indx)

                nb_lines = len(bundle)
                lines_range = range(nb_lines)
                points_per_line = [len(bundle[i]) for i in lines_range]
                points_per_line = np.array(points_per_line, np.intp)

                cols_arr = line_colors(bundle)
                colors_mapper = np.repeat(lines_range, points_per_line, axis=0)
                vtk_colors = numpy_to_vtk_colors(255 * cols_arr[colors_mapper])
                colors = numpy_support.vtk_to_numpy(vtk_colors)
                colors = (colors - np.min(colors)) / np.ptp(colors)

                for i in range(n):

                    if pvalues[i] < buan_thr:
                        colors[ind == i] = buan_highlight

                bundle_colors.append(colors)

        if len(bg_color) == 1:
            bg_color *= 3
        elif len(bg_color) != 3:
            raise ValueError('You need 3 values to set up backgound color. '
                             'e.g --bg_color 0.5 0.5 0.5')

        order_transparent = not disable_order_transparency
        horizon(tractograms=tractograms,
                images=images,
                pams=pams,
                cluster=cluster,
                cluster_thr=cluster_thr,
                random_colors=random_colors,
                bg_color=bg_color,
                order_transparent=order_transparent,
                length_gt=length_gt,
                length_lt=length_lt,
                clusters_gt=clusters_gt,
                clusters_lt=clusters_lt,
                world_coords=world_coords,
                interactive=interactive,
                buan=buan,
                buan_colors=bundle_colors,
                out_png=pjoin(out_dir, out_stealth_png))
예제 #7
0
def test_horizon_flow():

    s1 = 10 * np.array([[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0]],
                       dtype='f8')

    s2 = 10 * np.array([[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 4, 0]],
                       dtype='f8')

    s3 = 10 * np.array(
        [[0, 0, 0], [1, 0.2, 0], [2, 0.2, 0], [3, 0.2, 0], [4, 0.2, 0]],
        dtype='f8')

    affine = np.array([[1., 0., 0., -98.], [0., 1., 0., -134.],
                       [0., 0., 1., -72.], [0., 0., 0., 1.]])

    data = 255 * np.random.rand(197, 233, 189)
    vox_size = (1., 1., 1.)

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    header = create_nifti_header(affine, data.shape, vox_size)
    sft = StatefulTractogram(streamlines, header, Space.RASMM)

    tractograms = [sft]
    images = None

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=True,
            interactive=False)

    buan_colors = np.ones(streamlines.get_data().shape)

    horizon(tractograms,
            buan=True,
            buan_colors=buan_colors,
            world_coords=True,
            interactive=False)

    data = 255 * np.random.rand(197, 233, 189)

    images = [(data, affine)]

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=True,
            interactive=False)

    with TemporaryDirectory() as out_dir:

        fimg = os.path.join(out_dir, 'test.nii.gz')
        ftrk = os.path.join(out_dir, 'test.trk')
        fnpy = os.path.join(out_dir, 'test.npy')

        save_nifti(fimg, data, affine)
        dimensions = data.shape
        nii_header = create_nifti_header(affine, dimensions, vox_size)
        sft = StatefulTractogram(streamlines, nii_header, space=Space.RASMM)
        save_tractogram(sft, ftrk, bbox_valid_check=False)

        pvalues = np.random.uniform(low=0, high=1, size=(10, ))
        np.save(fnpy, pvalues)

        input_files = [ftrk, fimg]

        npt.assert_equal(len(input_files), 2)

        hz_flow = HorizonFlow()

        hz_flow.run(input_files=input_files,
                    stealth=True,
                    out_dir=out_dir,
                    out_stealth_png='tmp_x.png')

        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)
        npt.assert_raises(ValueError,
                          hz_flow.run,
                          input_files=input_files,
                          bg_color=(0.2, 0.2))

        hz_flow.run(input_files=input_files,
                    stealth=True,
                    bg_color=[
                        0.5,
                    ],
                    out_dir=out_dir,
                    out_stealth_png='tmp_x.png')
        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)

        input_files = [ftrk, fnpy]

        npt.assert_equal(len(input_files), 2)

        hz_flow.run(input_files=input_files,
                    stealth=True,
                    bg_color=[
                        0.5,
                    ],
                    buan=True,
                    buan_thr=0.5,
                    buan_highlight=(1, 1, 0),
                    out_dir=out_dir,
                    out_stealth_png='tmp_x.png')
        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)

        npt.assert_raises(ValueError,
                          hz_flow.run,
                          input_files=input_files,
                          roi_colors=(0.2, 0.2))

        hz_flow.run(input_files=input_files,
                    stealth=True,
                    roi_colors=[
                        0.5,
                    ],
                    out_dir=out_dir,
                    out_stealth_png='tmp_x.png')
        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)
예제 #8
0
def test_horizon_flow():

    s1 = 10 * np.array([[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0], [4, 0, 0]],
                       dtype='f8')

    s2 = 10 * np.array([[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0], [0, 4, 0]],
                       dtype='f8')

    s3 = 10 * np.array(
        [[0, 0, 0], [1, 0.2, 0], [2, 0.2, 0], [3, 0.2, 0], [4, 0.2, 0]],
        dtype='f8')

    print(s1.shape)
    print(s2.shape)
    print(s3.shape)

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    tractograms = [streamlines]
    images = None

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=False,
            interactive=False)
    #
    affine = np.diag([2., 1, 1, 1]).astype('f8')
    #
    data = 255 * np.random.rand(150, 150, 150)
    #
    images = [(data, affine)]

    horizon(tractograms,
            images=images,
            cluster=True,
            cluster_thr=5,
            random_colors=False,
            length_lt=np.inf,
            length_gt=0,
            clusters_lt=np.inf,
            clusters_gt=0,
            world_coords=True,
            interactive=False)

    with TemporaryDirectory() as out_dir:

        fimg = os.path.join(out_dir, 'test.nii.gz')
        ftrk = os.path.join(out_dir, 'test.trk')

        save_nifti(fimg, data, affine)
        dimensions = data.shape
        voxel_sizes = np.array([2, 1.0, 1.0])
        nii_header = create_nifti_header(affine, dimensions, voxel_sizes)
        sft = StatefulTractogram(streamlines, nii_header, space=Space.RASMM)
        save_tractogram(sft, ftrk, bbox_valid_check=False)

        input_files = [ftrk, fimg]

        npt.assert_equal(len(input_files), 2)

        hz_flow = HorizonFlow()

        hz_flow.run(input_files=input_files,
                    stealth=True,
                    out_dir=out_dir,
                    out_stealth_png='tmp_x.png')

        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)
예제 #9
0
def test_horizon():

    s1 = 10 * np.array([[0, 0, 0],
                        [1, 0, 0],
                        [2, 0, 0],
                        [3, 0, 0],
                        [4, 0, 0]], dtype='f8')

    s2 = 10 * np.array([[0, 0, 0],
                        [0, 1, 0],
                        [0, 2, 0],
                        [0, 3, 0],
                        [0, 4, 0]], dtype='f8')

    s3 = 10 * np.array([[0, 0, 0],
                        [1, 0.2, 0],
                        [2, 0.2, 0],
                        [3, 0.2, 0],
                        [4, 0.2, 0]], dtype='f8')

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    affine = np.array([[1., 0., 0., -98.],
                       [0., 1., 0., -134.],
                       [0., 0., 1., -72.],
                       [0., 0., 0., 1.]])

    data = 255 * np.random.rand(197, 233, 189)
    vox_size = (1., 1., 1.)

    streamlines._data += np.array([-98., -134., -72.])

    header = create_nifti_header(affine, data.shape, vox_size)
    sft = StatefulTractogram(streamlines, header, Space.RASMM)

    # only tractograms
    tractograms = [sft]
    images = None
    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)

    images = [(data, affine)]

    # tractograms in native coords (not supported for now)
    with npt.assert_raises(ValueError) as ve:
        horizon(tractograms, images=images, cluster=True, cluster_thr=5,
                random_colors=False, length_lt=np.inf, length_gt=0,
                clusters_lt=np.inf, clusters_gt=0,
                world_coords=False, interactive=False)

    msg = 'Currently native coordinates are not supported for streamlines'
    npt.assert_(msg in str(ve.exception))

    # only images
    tractograms = None
    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)

    # no clustering tractograms and images
    horizon(tractograms, images=images, cluster=False, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)
예제 #10
0
파일: viz.py 프로젝트: zhongyi80/dipy
    def run(self,
            input_files,
            cluster=False,
            cluster_thr=15.,
            random_colors=False,
            length_gt=0,
            length_lt=1000,
            clusters_gt=0,
            clusters_lt=10**8,
            native_coords=False,
            stealth=False,
            out_dir='',
            out_stealth_png='tmp.png'):
        """ Highly interactive visualization - invert the Horizon!

        Interact with any number of .trk, .tck or .dpy tractograms and anatomy
        files .nii or .nii.gz. Cluster streamlines on loading.

        Parameters
        ----------
        input_files : variable string
        cluster : bool
        cluster_thr : float
        random_colors : bool
        length_gt : float
        length_lt : float
        clusters_gt : int
        clusters_lt : int
        native_coords : bool
        stealth : bool
        out_dir : string
        out_stealth_png : string


        References
        ----------
        .. [Horizon_ISMRM19] Garyfallidis E., M-A. Cote, B.Q. Chandio,
            S. Fadnavis, J. Guaje, R. Aggarwal, E. St-Onge, K.S. Juneja,
            S. Koudoro, D. Reagan, DIPY Horizon: fast, modular, unified and
            adaptive visualization, Proceedings of: International Society of
            Magnetic Resonance in Medicine (ISMRM), Montreal, Canada, 2019.
        """
        verbose = True
        tractograms = []
        images = []
        pams = []
        interactive = not stealth
        world_coords = not native_coords

        io_it = self.get_io_iterator()

        for input_output in io_it:

            fname = input_output[0]

            if verbose:
                print('Loading file ...')
                print(fname)
                print('\n')

            fl = fname.lower()
            ends = fl.endswith

            if ends('.trk') or ends('.tck'):

                streamlines = nib.streamlines.load(fname).streamlines
                tractograms.append(streamlines)
            elif ends('dpy'):

                dpy_obj = Dpy(fname, mode='r')
                streamlines = list(dpy_obj.read_tracks())
                dpy_obj.close()

            if ends('.nii.gz') or ends('.nii'):

                data, affine = load_nifti(fname)
                images.append((data, affine))
                if verbose:
                    print('Affine to RAS')
                    np.set_printoptions(3, suppress=True)
                    print(affine)
                    np.set_printoptions()

            if ends(".pam5"):

                pam = load_peaks(fname)
                pams.append(pam)

                if verbose:
                    print('Peak_dirs shape')
                    print(pam.peak_dirs.shape)

        horizon(tractograms=tractograms,
                images=images,
                pams=pams,
                cluster=cluster,
                cluster_thr=cluster_thr,
                random_colors=random_colors,
                length_gt=length_gt,
                length_lt=length_lt,
                clusters_gt=clusters_gt,
                clusters_lt=clusters_lt,
                world_coords=world_coords,
                interactive=interactive,
                out_png=pjoin(out_dir, out_stealth_png))
예제 #11
0
파일: viz.py 프로젝트: tomas-psorn/dipy
    def run(self,
            input_files,
            cluster=False,
            cluster_thr=15.,
            random_colors=False,
            length_gt=0,
            length_lt=1000,
            clusters_gt=0,
            clusters_lt=10**8,
            native_coords=False,
            stealth=False,
            emergency_header='icbm_2009a',
            bg_color=(0, 0, 0),
            disable_order_transparency=False,
            out_dir='',
            out_stealth_png='tmp.png'):
        """ Interactive medical visualization - Invert the Horizon!

        Interact with any number of .trk, .tck or .dpy tractograms and anatomy
        files .nii or .nii.gz. Cluster streamlines on loading.

        Parameters
        ----------
        input_files : variable string
        cluster : bool, optional
            Enable QuickBundlesX clustering
        cluster_thr : float, optional
            Distance threshold used for clustering. Default value 15.0 for
            small animal brains you may need to use something smaller such
            as 2.0. The distance is in mm. For this parameter to be active
            ``cluster`` should be enabled
        random_colors : bool, optional
            Given multiple tractograms have been included then each tractogram
            will be shown with different color
        length_gt : float, optional
            Clusters with average length greater than ``length_gt`` amount
            in mm will be shown
        length_lt : float, optional
            Clusters with average length less than ``length_lt`` amount in
            mm will be shown
        clusters_gt : int, optional
            Clusters with size greater than ``clusters_gt`` will be shown.
        clusters_lt : int, optional
            Clusters with size less than ``clusters_gt`` will be shown.
        native_coords : bool, optional
            Show results in native coordinates
        stealth : bool, optional
            Do not use interactive mode just save figure.
        emergency_header : str, optional
            If no anatomy reference is provided an emergency header is
            provided. Current options 'icbm_2009a' and 'icbm_2009c'.
        bg_color : variable float, optional
            Define the background color of the scene. Colors can be defined
            with 1 or 3 values and should be between [0-1].
            Default is black (e.g --bg_color 0 0 0 or --bg_color 0).
        disable_order_transparency : bool, optional
            Default False. Use depth peeling to sort transparent objects.
            If True also enables anti-aliasing.
        out_dir : str, optional
            Output directory. Default current directory.
        out_stealth_png : str, optional
            Filename of saved picture.

        References
        ----------
        .. [Horizon_ISMRM19] Garyfallidis E., M-A. Cote, B.Q. Chandio,
            S. Fadnavis, J. Guaje, R. Aggarwal, E. St-Onge, K.S. Juneja,
            S. Koudoro, D. Reagan, DIPY Horizon: fast, modular, unified and
            adaptive visualization, Proceedings of: International Society of
            Magnetic Resonance in Medicine (ISMRM), Montreal, Canada, 2019.
        """
        verbose = True
        tractograms = []
        images = []
        pams = []
        interactive = not stealth
        world_coords = not native_coords

        mni_2009a = {}
        mni_2009a['affine'] = np.array([[1., 0., 0.,
                                         -98.], [0., 1., 0., -134.],
                                        [0., 0., 1., -72.], [0., 0., 0., 1.]])
        mni_2009a['dims'] = (197, 233, 189)
        mni_2009a['vox_size'] = (1., 1., 1.)
        mni_2009a['vox_space'] = 'RAS'

        mni_2009c = {}
        mni_2009c['affine'] = np.array([[1., 0., 0.,
                                         -96.], [0., 1., 0., -132.],
                                        [0., 0., 1., -78.], [0., 0., 0., 1.]])
        mni_2009c['dims'] = (193, 229, 193)
        mni_2009c['vox_size'] = (1., 1., 1.)
        mni_2009c['vox_space'] = 'RAS'

        if emergency_header == 'icbm_2009a':
            hdr = mni_2009c
        else:
            hdr = mni_2009c
        emergency_ref = create_nifti_header(hdr['affine'], hdr['dims'],
                                            hdr['vox_size'])

        io_it = self.get_io_iterator()

        for input_output in io_it:

            fname = input_output[0]

            if verbose:
                print('Loading file ...')
                print(fname)
                print('\n')

            fl = fname.lower()
            ends = fl.endswith

            if ends('.trk'):

                sft = load_tractogram(fname, 'same', bbox_valid_check=False)
                tractograms.append(sft)

            if ends('.dpy') or ends('.tck'):
                sft = load_tractogram(fname, emergency_ref)
                tractograms.append(sft)

            if ends('.nii.gz') or ends('.nii'):

                data, affine = load_nifti(fname)
                images.append((data, affine))
                if verbose:
                    print('Affine to RAS')
                    np.set_printoptions(3, suppress=True)
                    print(affine)
                    np.set_printoptions()

            if ends(".pam5"):

                pam = load_peaks(fname)
                pams.append(pam)

                if verbose:
                    print('Peak_dirs shape')
                    print(pam.peak_dirs.shape)

        if len(bg_color) == 1:
            bg_color *= 3
        elif len(bg_color) != 3:
            raise ValueError('You need 3 values to set up backgound color. '
                             'e.g --bg_color 0.5 0.5 0.5')

        order_transparent = not disable_order_transparency
        horizon(tractograms=tractograms,
                images=images,
                pams=pams,
                cluster=cluster,
                cluster_thr=cluster_thr,
                random_colors=random_colors,
                bg_color=bg_color,
                order_transparent=order_transparent,
                length_gt=length_gt,
                length_lt=length_lt,
                clusters_gt=clusters_gt,
                clusters_lt=clusters_lt,
                world_coords=world_coords,
                interactive=interactive,
                out_png=pjoin(out_dir, out_stealth_png))
예제 #12
0
def test_horizon_flow():

    s1 = 10 * np.array([[0, 0, 0],
                        [1, 0, 0],
                        [2, 0, 0],
                        [3, 0, 0],
                        [4, 0, 0]], dtype='f8')

    s2 = 10 * np.array([[0, 0, 0],
                        [0, 1, 0],
                        [0, 2, 0],
                        [0, 3, 0],
                        [0, 4, 0]], dtype='f8')

    s3 = 10 * np.array([[0, 0, 0],
                        [1, 0.2, 0],
                        [2, 0.2, 0],
                        [3, 0.2, 0],
                        [4, 0.2, 0]], dtype='f8')

    print(s1.shape)
    print(s2.shape)
    print(s3.shape)

    streamlines = Streamlines()
    streamlines.append(s1)
    streamlines.append(s2)
    streamlines.append(s3)

    tractograms = [streamlines]
    images = None

    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=False, interactive=False)
#
    affine = np.diag([2., 1, 1, 1]).astype('f8')
#
    data = 255 * np.random.rand(150, 150, 150)
#
    images = [(data, affine)]

    horizon(tractograms, images=images, cluster=True, cluster_thr=5,
            random_colors=False, length_lt=np.inf, length_gt=0,
            clusters_lt=np.inf, clusters_gt=0,
            world_coords=True, interactive=False)

    with TemporaryDirectory() as out_dir:

        fimg = os.path.join(out_dir, 'test.nii.gz')
        ftrk = os.path.join(out_dir, 'test.trk')

        save_nifti(fimg, data, affine)
        save_tractogram(ftrk, streamlines, affine)

        input_files = [ftrk, fimg]

        npt.assert_equal(len(input_files), 2)

        hz_flow = HorizonFlow()

        hz_flow.run(input_files=input_files, stealth=True,
                    out_dir=out_dir, out_stealth_png='tmp_x.png')

        npt.assert_equal(os.path.exists(os.path.join(out_dir, 'tmp_x.png')),
                         True)