def _plot_mri_contours(mri_fname, surfaces, src, orientation='coronal', slices=None, show=True, show_indices=False, show_orientation=False, img_output=False):
    'Plot BEM contours on anatomical slices.'
    import matplotlib.pyplot as plt
    from matplotlib import patheffects
    _check_option('orientation', orientation, ('coronal', 'axial', 'sagittal'))
    (_, vox_mri_t, _, _, _, nim) = _read_mri_info(mri_fname, units='mm', return_img=True)
    mri_vox_t = invert_transform(vox_mri_t)['trans']
    del vox_mri_t
    ((x, y, z), (flip_x, flip_y, flip_z), order) = _mri_orientation(nim, orientation)
    transpose = (x < y)
    data = _get_img_fdata(nim)
    shift_x = (data.shape[x] if (flip_x < 0) else 0)
    shift_y = (data.shape[y] if (flip_y < 0) else 0)
    n_slices = data.shape[z]
    if (slices is None):
        slices = np.round(np.linspace(0, (n_slices - 1), 14)).astype(int)[1:(- 1)]
    slices = np.atleast_1d(slices).copy()
    slices[(slices < 0)] += n_slices
    if ((not np.array_equal(np.sort(slices), slices)) or (slices.ndim != 1) or (slices.size < 1) or (slices[0] < 0) or (slices[(- 1)] >= n_slices) or (slices.dtype.kind not in 'iu')):
        raise ValueError(('slices must be a sorted 1D array of int with unique elements, at least one element, and no elements greater than %d, got %s' % ((n_slices - 1), slices)))
    if (flip_z < 0):
        slices = slices[::(- 1)]
    surfs = list()
    for (file_name, color) in surfaces:
        surf = dict()
        (surf['rr'], surf['tris']) = read_surface(file_name)
        surf['rr'] = apply_trans(mri_vox_t, surf['rr'])
        surfs.append((surf, color))
    sources = list()
    if (src is not None):
        _ensure_src(src, extra=' or None')
        if (src[0]['coord_frame'] != FIFF.FIFFV_COORD_MRI):
            raise ValueError(f"Source space must be in MRI coordinates, got {_frame_to_str[src[0]['coord_frame']]}")
        for src_ in src:
            points = src_['rr'][src_['inuse'].astype(bool)]
            sources.append(apply_trans(mri_vox_t, (points * 1000.0)))
        sources = np.concatenate(sources, axis=0)
    if img_output:
        n_col = n_axes = 1
        (fig, ax) = plt.subplots(1, 1, figsize=(7.0, 7.0))
        axs = ([ax] * len(slices))
        w = fig.get_size_inches()[0]
        fig.set_size_inches([w, ((w / data.shape[x]) * data.shape[y])])
        plt.close(fig)
    else:
        n_col = 4
        (fig, axs, _, _) = _prepare_trellis(len(slices), n_col)
        n_axes = len(axs)
    fig.set_facecolor('k')
    bounds = np.concatenate([[(- np.inf)], (slices[:(- 1)] + (np.diff(slices) / 2.0)), [np.inf]])
    slicer = ([slice(None)] * 3)
    ori_labels = dict(R='LR', A='PA', S='IS')
    (xlabels, ylabels) = (ori_labels[order[0]], ori_labels[order[1]])
    path_effects = [patheffects.withStroke(linewidth=4, foreground='k', alpha=0.75)]
    out = (list() if img_output else fig)
    for (ai, (ax, sl, lower, upper)) in enumerate(zip(axs, slices, bounds[:(- 1)], bounds[1:])):
        slicer[z] = sl
        dat = data[tuple(slicer)]
        dat = (dat.T if transpose else dat)
        dat = dat[::flip_y, ::flip_x]
        if img_output:
            ax.clear()
        ax.imshow(dat, cmap=plt.cm.gray, origin='lower')
        ax.set_autoscale_on(False)
        ax.axis('off')
        ax.set_aspect('equal')
        for (surf, color) in surfs:
            with warnings.catch_warnings(record=True):
                warnings.simplefilter('ignore')
                ax.tricontour(((flip_x * surf['rr'][:, x]) + shift_x), ((flip_y * surf['rr'][:, y]) + shift_y), surf['tris'], surf['rr'][:, z], levels=[sl], colors=color, linewidths=1.0, zorder=1)
        if len(sources):
            in_slice = ((sources[:, z] >= lower) & (sources[:, z] < upper))
            ax.scatter(((flip_x * sources[(in_slice, x)]) + shift_x), ((flip_y * sources[(in_slice, y)]) + shift_y), marker='.', color='#FF00FF', s=1, zorder=2)
        if show_indices:
            ax.text(((dat.shape[1] // 8) + 0.5), 0.5, str(sl), color='w', fontsize='x-small', va='bottom', ha='left')
        kwargs = dict(color='#66CCEE', fontsize='medium', path_effects=path_effects, family='monospace', clip_on=False, zorder=5, weight='bold')
        if show_orientation:
            if ((ai % n_col) == 0):
                ax.text(0, (dat.shape[0] / 2.0), xlabels[0], va='center', ha='left', **kwargs)
            if (((ai % n_col) == (n_col - 1)) or (ai == (n_axes - 1))):
                ax.text((dat.shape[1] - 1), (dat.shape[0] / 2.0), xlabels[1], va='center', ha='right', **kwargs)
            if (ai >= (n_axes - n_col)):
                ax.text((dat.shape[1] / 2.0), 0, ylabels[0], ha='center', va='bottom', **kwargs)
            if ((ai < n_col) or (n_col == 1)):
                ax.text((dat.shape[1] / 2.0), (dat.shape[0] - 1), ylabels[1], ha='center', va='top', **kwargs)
        if img_output:
            output = BytesIO()
            fig.savefig(output, bbox_inches='tight', pad_inches=0, format='png')
            out.append(base64.b64encode(output.getvalue()).decode('ascii'))
    fig.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0, wspace=0.0, hspace=0.0)
    plt_show(show, fig=fig)
    return out
Plot BEM contours on anatomical slices.
def _plot_mri_contours(mri_fname, surfaces, src, orientation='coronal', slices=None, show=True, show_indices=False, show_orientation=False, img_output=False):
    
    import matplotlib.pyplot as plt
    from matplotlib import patheffects
    _check_option('orientation', orientation, ('coronal', 'axial', 'sagittal'))
    (_, vox_mri_t, _, _, _, nim) = _read_mri_info(mri_fname, units='mm', return_img=True)
    mri_vox_t = invert_transform(vox_mri_t)['trans']
    del vox_mri_t
    ((x, y, z), (flip_x, flip_y, flip_z), order) = _mri_orientation(nim, orientation)
    transpose = (x < y)
    data = _get_img_fdata(nim)
    shift_x = (data.shape[x] if (flip_x < 0) else 0)
    shift_y = (data.shape[y] if (flip_y < 0) else 0)
    n_slices = data.shape[z]
    if (slices is None):
        slices = np.round(np.linspace(0, (n_slices - 1), 14)).astype(int)[1:(- 1)]
    slices = np.atleast_1d(slices).copy()
    slices[(slices < 0)] += n_slices
    if ((not np.array_equal(np.sort(slices), slices)) or (slices.ndim != 1) or (slices.size < 1) or (slices[0] < 0) or (slices[(- 1)] >= n_slices) or (slices.dtype.kind not in 'iu')):
        raise ValueError(('slices must be a sorted 1D array of int with unique elements, at least one element, and no elements greater than %d, got %s' % ((n_slices - 1), slices)))
    if (flip_z < 0):
        slices = slices[::(- 1)]
    surfs = list()
    for (file_name, color) in surfaces:
        surf = dict()
        (surf['rr'], surf['tris']) = read_surface(file_name)
        surf['rr'] = apply_trans(mri_vox_t, surf['rr'])
        surfs.append((surf, color))
    sources = list()
    if (src is not None):
        _ensure_src(src, extra=' or None')
        if (src[0]['coord_frame'] != FIFF.FIFFV_COORD_MRI):
            raise ValueError(f"Source space must be in MRI coordinates, got {_frame_to_str[src[0]['coord_frame']]}")
        for src_ in src:
            points = src_['rr'][src_['inuse'].astype(bool)]
            sources.append(apply_trans(mri_vox_t, (points * 1000.0)))
        sources = np.concatenate(sources, axis=0)
    if img_output:
        n_col = n_axes = 1
        (fig, ax) = plt.subplots(1, 1, figsize=(7.0, 7.0))
        axs = ([ax] * len(slices))
        w = fig.get_size_inches()[0]
        fig.set_size_inches([w, ((w / data.shape[x]) * data.shape[y])])
        plt.close(fig)
    else:
        n_col = 4
        (fig, axs, _, _) = _prepare_trellis(len(slices), n_col)
        n_axes = len(axs)
    fig.set_facecolor('k')
    bounds = np.concatenate([[(- np.inf)], (slices[:(- 1)] + (np.diff(slices) / 2.0)), [np.inf]])
    slicer = ([slice(None)] * 3)
    ori_labels = dict(R='LR', A='PA', S='IS')
    (xlabels, ylabels) = (ori_labels[order[0]], ori_labels[order[1]])
    path_effects = [patheffects.withStroke(linewidth=4, foreground='k', alpha=0.75)]
    out = (list() if img_output else fig)
    for (ai, (ax, sl, lower, upper)) in enumerate(zip(axs, slices, bounds[:(- 1)], bounds[1:])):
        slicer[z] = sl
        dat = data[tuple(slicer)]
        dat = (dat.T if transpose else dat)
        dat = dat[::flip_y, ::flip_x]
        if img_output:
            ax.clear()
        ax.imshow(dat, cmap=plt.cm.gray, origin='lower')
        ax.set_autoscale_on(False)
        ax.axis('off')
        ax.set_aspect('equal')
        for (surf, color) in surfs:
            with warnings.catch_warnings(record=True):
                warnings.simplefilter('ignore')
                ax.tricontour(((flip_x * surf['rr'][:, x]) + shift_x), ((flip_y * surf['rr'][:, y]) + shift_y), surf['tris'], surf['rr'][:, z], levels=[sl], colors=color, linewidths=1.0, zorder=1)
        if len(sources):
            in_slice = ((sources[:, z] >= lower) & (sources[:, z] < upper))
            ax.scatter(((flip_x * sources[(in_slice, x)]) + shift_x), ((flip_y * sources[(in_slice, y)]) + shift_y), marker='.', color='#FF00FF', s=1, zorder=2)
        if show_indices:
            ax.text(((dat.shape[1] // 8) + 0.5), 0.5, str(sl), color='w', fontsize='x-small', va='bottom', ha='left')
        kwargs = dict(color='#66CCEE', fontsize='medium', path_effects=path_effects, family='monospace', clip_on=False, zorder=5, weight='bold')
        if show_orientation:
            if ((ai % n_col) == 0):
                ax.text(0, (dat.shape[0] / 2.0), xlabels[0], va='center', ha='left', **kwargs)
            if (((ai % n_col) == (n_col - 1)) or (ai == (n_axes - 1))):
                ax.text((dat.shape[1] - 1), (dat.shape[0] / 2.0), xlabels[1], va='center', ha='right', **kwargs)
            if (ai >= (n_axes - n_col)):
                ax.text((dat.shape[1] / 2.0), 0, ylabels[0], ha='center', va='bottom', **kwargs)
            if ((ai < n_col) or (n_col == 1)):
                ax.text((dat.shape[1] / 2.0), (dat.shape[0] - 1), ylabels[1], ha='center', va='top', **kwargs)
        if img_output:
            output = BytesIO()
            fig.savefig(output, bbox_inches='tight', pad_inches=0, format='png')
            out.append(base64.b64encode(output.getvalue()).decode('ascii'))
    fig.subplots_adjust(left=0.0, bottom=0.0, right=1.0, top=1.0, wspace=0.0, hspace=0.0)
    plt_show(show, fig=fig)
    return out