Beispiel #1
0
def check_images(img_spec1, img_spec2, bkground_thresh=0.05):
    """Reads the two images and assers identical shape."""

    img1 = read_image(img_spec1, bkground_thresh)
    img2 = read_image(img_spec2, bkground_thresh)

    if img1.shape != img2.shape:
        raise ValueError(
            'size mismatch! First image: {} Second image: {}\n'
            'Two images to be compared must be of the same size in all dimensions.'
            .format(img1.shape, img2.shape))

    return img1, img2
Beispiel #2
0
def test_collage_class():

    img_path = pjoin(base_dir, '3569_bl_PPMI.nii')
    img = read_image(img_path, None)
    scaled = scale_0to1(img)
    c = Collage(num_slices=15, view_set=(0, 1), num_rows=3)

    try:
        c.attach(scaled)
    except:
        raise ValueError('Attach does not work')

    try:
        c.transform_and_attach(scaled, np.square)
    except:
        raise ValueError('transform_and_attach does not work')

    try:
        print(c)
    except:
        raise ValueError('repr implementation failed')
Beispiel #3
0
def test_slice_picker():

    img_path = pjoin(base_dir, '3569_bl_PPMI.nii')
    img = read_image(img_path, None)
    sp = SlicePicker(img, num_slices=15, view_set=(0, 1))

    try:
        for dim, sl_num, data in sp.get_slices(extended=True):
            print(dim, sl_num, data.shape)
    except:
        raise ValueError('get_slices() does not work')

    try:
        for d1, d2 in sp.get_slices_multi((img, img)):
            assert np.allclose(d1, d2)
    except:
        raise ValueError('get_slices_multi() does not work')

    try:
        print(sp)
    except:
        raise ValueError('repr implementation failed')

    def density_over(img2d, min_density=0.65):

        return (np.count_nonzero(img2d.flatten()) / img2d.size) <= min_density

    print('testing different sampling strategies .. ')
    for sname, sampler in zip(('linear', 'percent', 'callable'),
                              ('linear', (5, 50, 95), density_over)):
        sp = SlicePicker(img, sampler=sampler)
        print(sname)
        print(repr(sp))

    print('testing linear sampling')
    for ns in np.random.randint(0, min(img.shape), 10):

        sp_linear = SlicePicker(img, sampler='linear', num_slices=ns)
        print(repr(sp_linear))
        if 3 * ns != len(sp_linear.get_slice_indices()):
            raise ValueError('error in linear sampling')

    print('testing percentage sampling')
    perc_list = [5, 10, 45, 60, 87]
    sp_perc = SlicePicker(img, sampler=perc_list)
    print(repr(sp_perc))
    if 3 * len(perc_list) != len(sp_perc.get_slice_indices()):
        raise ValueError('error in percentage sampling')

    print('testing ability to save to gif')
    import tempfile
    gif_path = tempfile.NamedTemporaryFile(suffix='.gif').name
    print(gif_path)
    sp.save_as_gif(gif_path)
    if not pexists(gif_path):
        raise IOError('Saving to GIF failed')

    try:
        import imageio
        gif = imageio.mimread(gif_path, format='gif')
    except:
        raise ValueError('Saved GIF file could not be read properly!')

    print()

    print()
Beispiel #4
0
                                                   img_format)))
        for idx in range(5)
    ]
    if all(scr_shot_exist):
        continue

    try:
        t1_path = pjoin(in_dir, subject_id,
                        '{}_{}.nii'.format(subject_id, 't1'))
        lesion_path = pjoin(in_dir, subject_id,
                            '{}_{}.nii'.format(subject_id, 'AutoSeg_linda'))

        # img = nib.load(t1_path)
        # # print("image shape", img.shape)

        t1w = read_image(t1_path, None)
        max_shape = max(t1w.shape)
        lesion = read_image(lesion_path, None)
        lesion = lesion.astype('int')

        # casting to remove any negligible differences due to interpolation
        # removing background - 0 stays 0
        unique_labels = np.setdiff1d(np.unique(lesion.flatten()), 0)

        LesionSlicePicker = SlicePicker(lesion,
                                        view_set=[
                                            2,
                                        ],
                                        num_slices=5,
                                        min_density=0.0001)
        idx = 0
Beispiel #5
0
def aseg_on_mri(mri_spec,
                aseg_spec,
                alpha_mri=1.0,
                alpha_seg=1.0,
                num_rows=2,
                num_cols=6,
                rescale_method='global',
                aseg_cmap='freesurfer',
                sub_cortical=False,
                annot=None,
                padding=5,
                bkground_thresh=0.05,
                output_path=None,
                figsize=None,
                **kwargs):
    "Produces a collage of various slices from different orientations in the given 3D image"

    num_rows, num_cols, padding = check_params(num_rows, num_cols, padding)

    mri = read_image(mri_spec, bkground_thresh=bkground_thresh)
    seg = read_image(aseg_spec, bkground_thresh=0)
    mri, seg = crop_to_seg_extents(mri, seg, padding)

    num_slices_per_view = num_rows * num_cols
    slices = pick_slices(seg, num_slices_per_view)

    plt.style.use('dark_background')

    num_axes = 3
    if figsize is None:
        figsize = [5 * num_axes * num_rows, 5 * num_cols]
    fig, ax = plt.subplots(num_axes * num_rows, num_cols, figsize=figsize)

    # displaying some annotation text if provided
    if annot is not None:
        fig.suptitle(annot, backgroundcolor='black', color='g')

    display_params_mri = dict(interpolation='none',
                              aspect='equal',
                              origin='lower',
                              cmap='gray',
                              alpha=alpha_mri,
                              vmin=mri.min(),
                              vmax=mri.max())
    display_params_seg = dict(interpolation='none',
                              aspect='equal',
                              origin='lower',
                              alpha=alpha_seg)

    normalize_labels = colors.Normalize(vmin=seg.min(),
                                        vmax=seg.max(),
                                        clip=True)
    fs_cmap = get_freesurfer_cmap(sub_cortical)
    label_mapper = cm.ScalarMappable(norm=normalize_labels, cmap=fs_cmap)

    ax = ax.flatten()
    ax_counter = 0
    for dim_index in range(3):
        for slice_num in slices[dim_index]:
            plt.sca(ax[ax_counter])
            ax_counter = ax_counter + 1

            slice_mri = get_axis(mri, dim_index, slice_num)
            slice_seg = get_axis(seg, dim_index, slice_num)

            # # masking data to set no-value pixels to transparent
            # seg_background = np.isclose(slice_seg, 0.0)
            # slice_seg = np.ma.masked_where(seg_background, slice_seg)
            # slice_mri = np.ma.masked_where(np.logical_not(seg_background), slice_mri)

            seg_rgb = label_mapper.to_rgba(slice_seg)
            plt.imshow(seg_rgb, **display_params_seg)
            plt.imshow(slice_mri, **display_params_mri)
            plt.axis('off')

    # plt.subplots_adjust(wspace=0.0, hspace=0.0)
    plt.subplots_adjust(left=0.01,
                        right=0.99,
                        bottom=0.01,
                        top=0.99,
                        wspace=0.05,
                        hspace=0.02)
    # fig.tight_layout()

    if output_path is not None:
        output_path = output_path.replace(' ', '_')
        fig.savefig(output_path + '.png', bbox_inches='tight')

    # plt.close()

    return fig
Beispiel #6
0
def collage(img_spec,
            num_rows=2,
            num_cols=6,
            rescale_method='global',
            cmap='gray',
            annot=None,
            padding=5,
            bkground_thresh=None,
            output_path=None,
            figsize=None,
            **kwargs):
    "Produces a collage of various slices from different orientations in the given 3D image"

    num_rows, num_cols, padding = check_params(num_rows, num_cols, padding)

    img = read_image(img_spec, bkground_thresh=bkground_thresh)
    img = crop_image(img, padding)

    img, (min_value, max_value) = check_rescaling_collage(img,
                                                          rescale_method,
                                                          return_extrema=True)
    num_slices_per_view = num_rows * num_cols
    slices = pick_slices(img, num_slices_per_view)

    plt.style.use('dark_background')

    num_axes = 3
    if figsize is None:
        figsize = [3 * num_axes * num_rows, 3 * num_cols]
    fig, ax = plt.subplots(num_axes * num_rows, num_cols, figsize=figsize)

    # displaying some annotation text if provided
    if annot is not None:
        fig.suptitle(annot, backgroundcolor='black', color='g')

    display_params = dict(interpolation='none',
                          cmap=cmap,
                          aspect='equal',
                          origin='lower',
                          vmin=min_value,
                          vmax=max_value)

    ax = ax.flatten()
    ax_counter = 0
    for dim_index in range(3):
        for slice_num in slices[dim_index]:
            plt.sca(ax[ax_counter])
            ax_counter = ax_counter + 1
            slice1 = get_axis(img, dim_index, slice_num)
            # slice1 = crop_image(slice1, padding)
            plt.imshow(slice1, **display_params)
            plt.axis('off')

    fig.tight_layout()

    if output_path is not None:
        output_path = output_path.replace(' ', '_')
        fig.savefig(output_path + '.png', bbox_inches='tight')

    # plt.close()

    return fig