Example #1
0
File: plot.py Project: jerdra/niviz
def plot_orthogonal_views(data,
                          bbox_nii=None,
                          auto_brightness=False,
                          display_modes=['x', 'y', 'z'],
                          n_cuts=10,
                          plot_func=nplot.plot_anat,
                          figure_title=""):

    if bbox_nii is None:
        bbox_nii = nimg.threshold_img(data, 1e-3)

    cuts = cuts_from_bbox(data, cuts=n_cuts)
    if auto_brightness:
        robust_params = robust_set_limits(bbox_nii.get_fdata().reshape(-1), {})
    else:
        robust_params = {}

    svgs = []
    for d in display_modes:
        plot_params = {
            "display_mode": d,
            "cut_coords": cuts[d],
            **robust_params
        }
        display = plot_func(data, **plot_params)
        svg = extract_svg(display)
        svg = svg.replace("figure_1", f"{figure_title}-{d}")
        svgs.append(fromstring(svg))
        display.close()
    return svgs
Example #2
0
    def _generate_report(self):
        anat_img = nib.load(self.inputs.in_file)
        mask_img = nib.load(self.inputs.mask_file)
        assert nvol(anat_img) == 1
        assert nvol(mask_img) == 1

        plot_params = robust_set_limits_in_mask(anat_img, mask_img)

        template = self.inputs.template
        parc_file = getresource(
            f"tpl-{template}_RegistrationCheckOverlay.nii.gz")
        assert parc_file is not None
        parc_img = nib.load(parc_file)

        levels = np.unique(np.asanyarray(parc_img.dataobj).astype(np.int32))
        levels = (levels[levels > 0] - 0.5).tolist()
        colors = color_palette("husl", len(levels))

        label = None
        if isdefined(self.inputs.label):
            label = self.inputs.label

        compress = self.inputs.compress_report

        n_cuts = 7
        cuts = cuts_from_bbox(mask_img, cuts=n_cuts)

        outfiles = []
        for dimension in ["z", "y", "x"]:
            display = plot_anat(
                anat_img,
                draw_cross=False,
                display_mode=dimension,
                cut_coords=cuts[dimension],
                title=label,
                **plot_params,
            )

            display.add_contours(parc_img,
                                 levels=levels,
                                 colors=colors,
                                 linewidths=0.25)
            display.add_contours(mask_img,
                                 levels=[0.5],
                                 colors="r",
                                 linewidths=0.5)

            label = None  # only on first

            svg = extract_svg(display, compress=compress)
            svg = svg.replace("figure_1", str(uuid4()), 1)

            outfiles.append(fromstring(svg))

        self._out_report = op.abspath(self.inputs.out_report)
        compose_view(bg_svgs=outfiles, fg_svgs=None, out_file=self._out_report)
Example #3
0
def _plot_anat_with_contours(image, segs=None, compress="auto", **plot_params):
    '''
    Patched version of _plot_anat_with_contours that will
    accept
    '''

    from niworkflows.viz.utils import extract_svg
    nsegs = len(segs or [])
    plot_params = plot_params or {}
    # plot_params' values can be None, however they MUST NOT
    # be None for colors and levels from this point on.
    colors = plot_params.pop("colors", None) or []
    levels = plot_params.pop("levels", None) or []
    filled = plot_params.pop("filled", False)
    alpha = plot_params.pop("alpha", 1)
    missing = nsegs - len(colors)
    if missing > 0:  # missing may be negative
        from seaborn import color_palette

        colors = colors + color_palette("husl", missing)

    colors = [[c] if not isinstance(c, list) else c for c in colors]

    # Handle when a sequence of RGB is given as colors
    if not isinstance(colors[0], str):
        from matplotlib.colors import to_hex
        colors = [to_hex(c) for c in colors]

    if not levels:
        levels = [[0.5]] * nsegs

    # anatomical
    # this line is problematic
    display = plot_anat(image, **plot_params)

    # remove plot_anat -specific parameters
    plot_params.pop("display_mode")
    plot_params.pop("cut_coords")

    plot_params["linewidths"] = 0.5
    for i in reversed(range(nsegs)):
        plot_params["colors"] = colors[i]
        display.add_contours(segs[i],
                             levels=levels[i],
                             filled=filled,
                             alpha=alpha,
                             **plot_params)

    svg = extract_svg(display, compress=compress)
    display.close()
    return svg
Example #4
0
    def _generate_report(self):
        in_img = nib.load(self.inputs.in_file)
        assert nvol(in_img) == 1

        mask_img = nib.load(self.inputs.mask_file)
        assert nvol(mask_img) == 1

        label = None
        if isdefined(self.inputs.label):
            label = self.inputs.label

        compress = self.inputs.compress_report

        n_cuts = 7
        cuts = cuts_from_bbox(mask_img, cuts=n_cuts)

        img_vals = in_img.get_fdata()[np.asanyarray(mask_img.dataobj).astype(
            np.bool)]
        vmin = img_vals.min()
        vmax = img_vals.max()

        outfiles = []
        for dimension in ["z", "y", "x"]:
            display = plot_epi(
                in_img,
                draw_cross=False,
                display_mode=dimension,
                cut_coords=cuts[dimension],
                title=label,
                vmin=vmin,
                vmax=vmax,
                colorbar=(dimension == "z"),
                cmap=plt.cm.gray,
            )
            display.add_contours(mask_img, levels=[0.5], colors="r")
            label = None  # only on first
            svg = extract_svg(display, compress=compress)
            svg = svg.replace("figure_1", str(uuid4()), 1)
            outfiles.append(fromstring(svg))

        self._out_report = op.abspath(self.inputs.out_report)
        compose_view(bg_svgs=outfiles, fg_svgs=None, out_file=self._out_report)
Example #5
0
File: plot.py Project: jerdra/niviz
def plot_montage(data,
                 orientation,
                 bbox_nii=None,
                 n_cuts=15,
                 n_cols=5,
                 auto_brightness=False,
                 plot_func=nplot.plot_anat,
                 figure_title="figure"):
    '''
    Plot a montage of cuts for a given orientation
    for an image
    '''

    if bbox_nii is None:
        bbox_nii = nimg.threshold_img(data, 1e-3)

    cuts = cuts_from_bbox(bbox_nii, cuts=n_cuts)
    if auto_brightness:
        robust_params = robust_set_limits(bbox_nii.get_fdata().reshape(-1), {})
    else:
        robust_params = {}

    svgs = []
    for i in range(n_cuts // n_cols):

        start = i * n_cols
        end = min(i * n_cols + n_cols, n_cuts)
        row_cuts = cuts[orientation][start:end]

        plot_params = {
            "display_mode": orientation,
            "cut_coords": row_cuts,
            **robust_params
        }

        display = plot_func(data, **plot_params)
        svg = extract_svg(display)
        svg = svg.replace("figure_1", f"{figure_title}:{start}-{end}")
        svgs.append(fromstring(svg))

    return svgs
Example #6
0
    def _generate_report(self):
        epi_img = nib.load(self.inputs.in_file)
        mask_img = nib.load(self.inputs.mask_file)
        assert nvol(epi_img) == 1
        assert nvol(mask_img) == 1

        label = None
        if isdefined(self.inputs.label):
            label = self.inputs.label

        compress = self.inputs.compress_report

        n_cuts = 7
        cuts = cuts_from_bbox(mask_img, cuts=n_cuts)

        plot_params = robust_set_limits_in_mask(epi_img, mask_img)

        outfiles = []
        for dimension in ["z", "y", "x"]:
            display = plot_epi(
                epi_img,
                draw_cross=False,
                display_mode=dimension,
                cut_coords=cuts[dimension],
                title=label,
                colorbar=(dimension == "z"),
                cmap=plt.get_cmap("gray"),
                **plot_params,
            )

            display.add_contours(mask_img, levels=[0.5], colors="r")

            label = None  # only on first

            svg = extract_svg(display, compress=compress)
            svg = svg.replace("figure_1", str(uuid4()), 1)

            outfiles.append(fromstring(svg))

        self._out_report = op.abspath(self.inputs.out_report)
        compose_view(bg_svgs=outfiles, fg_svgs=None, out_file=self._out_report)
Example #7
0
def plot_registration(anat_nii,
                      div_id,
                      plot_params=None,
                      order=('z', 'x', 'y'),
                      cuts=None,
                      estimate_brightness=False,
                      label=None,
                      contour=None,
                      compress='auto'):
    """
    Plot the foreground and background views.

    Default order is: axial, coronal, sagittal
    """
    from uuid import uuid4

    from lxml import etree
    from nilearn.plotting import plot_anat
    from svgutils.transform import SVGFigure
    from niworkflows.viz.utils import robust_set_limits, extract_svg, SVGNS

    plot_params = plot_params or {}

    # Use default MNI cuts if none defined
    if cuts is None:
        raise NotImplementedError  # TODO

    out_files = []
    if estimate_brightness:
        plot_params = robust_set_limits(anat_nii.get_data().reshape(-1),
                                        plot_params)

    # Plot each cut axis
    for i, mode in enumerate(list(order)):
        plot_params['display_mode'] = mode
        plot_params['cut_coords'] = cuts[mode]
        if i == 0:
            plot_params['title'] = label
        else:
            plot_params['title'] = None

        # Generate nilearn figure
        display = plot_anat(anat_nii, **plot_params)
        if contour is not None:
            display.add_contours(contour,
                                 colors='g',
                                 levels=[0.5],
                                 linewidths=0.5)

        svg = extract_svg(display, compress=compress)
        display.close()

        # Find and replace the figure_1 id.
        xml_data = etree.fromstring(svg)
        find_text = etree.ETXPath("//{%s}g[@id='figure_1']" % SVGNS)
        find_text(xml_data)[0].set('id', '%s-%s-%s' % (div_id, mode, uuid4()))

        svg_fig = SVGFigure()
        svg_fig.root = xml_data
        out_files.append(svg_fig)

    return out_files
Example #8
0
def plot_registration(
    anat_nii,
    div_id,
    plot_params=None,
    order=("z", "x", "y"),
    cuts=None,
    estimate_brightness=False,
    label=None,
    contour=None,
    compress="auto",
    overlay=None,
    overlay_params=None,
):
    """
    Plot the foreground and background views.

    Default order is: axial, coronal, sagittal
    """
    from uuid import uuid4

    from lxml import etree
    import matplotlib.pyplot as plt
    from nilearn.plotting import plot_anat
    from svgutils.transform import SVGFigure
    from niworkflows.viz.utils import robust_set_limits, extract_svg, SVGNS

    plot_params = plot_params or {}

    # Use default MNI cuts if none defined
    if cuts is None:
        raise NotImplementedError  # TODO

    out_files = []
    if estimate_brightness:
        plot_params = robust_set_limits(
            anat_nii.get_fdata(dtype="float32").reshape(-1), plot_params)

    # Plot each cut axis
    for i, mode in enumerate(list(order)):
        plot_params["display_mode"] = mode
        plot_params["cut_coords"] = cuts[mode]
        if i == 0:
            plot_params["title"] = label
        else:
            plot_params["title"] = None

        # Generate nilearn figure
        display = plot_anat(anat_nii, **plot_params)
        if overlay is not None:
            _overlay_params = {
                "vmin": overlay.get_fdata(dtype="float32").min(),
                "vmax": overlay.get_fdata(dtype="float32").max(),
                "cmap": plt.cm.gray,
                "interpolation": "nearest",
            }
            _overlay_params.update(overlay_params)
            display.add_overlay(overlay, **_overlay_params)
        if contour is not None:
            display.add_contours(contour,
                                 colors="g",
                                 levels=[0.5],
                                 linewidths=0.5)

        svg = extract_svg(display, compress=compress)
        display.close()

        # Find and replace the figure_1 id.
        xml_data = etree.fromstring(svg)
        find_text = etree.ETXPath("//{%s}g[@id='figure_1']" % SVGNS)
        find_text(xml_data)[0].set("id", "%s-%s-%s" % (div_id, mode, uuid4()))

        svg_fig = SVGFigure()
        svg_fig.root = xml_data
        out_files.append(svg_fig)

    return out_files