예제 #1
0
파일: data.py 프로젝트: h4nyu/aplf
def resize(inpath: Path, outpath: Path, size: float) -> Path:
    if outpath.exists():
        return outpath
    image = io.imread(inpath)
    image = _resize(image, size)
    io.imsave(outpath, image)
    return outpath
예제 #2
0
파일: load_eth80.py 프로젝트: kharyuk/gbtd
def buildNpzETH80(data_filename, data_dirname='', resizeValue=None):
    Nobjects = 10  # fixed values
    Nclasses = 8  # fixed value
    data_dirname_new = data_dirname + data_filename.split('.')[0] + '/'
    all_filenames = _os.listdir(data_dirname_new)
    all_filenames = sorted(all_filenames, key=_io_work.stringSplitByNumbers)
    data = []
    classes = []
    for i in xrange(Nclasses):
        locDirnames = all_filenames[i * Nobjects:(i + 1) * Nobjects]
        class_data = []
        className = filter(lambda x: not x.isdigit(), locDirnames[0])
        classes.append(className)
        for j in xrange(Nobjects):
            fnms = _os.listdir(data_dirname_new + locDirnames[j])
            fnms = filter(lambda x: x.endswith('.png'), fnms)
            fnms = sorted(fnms, key=_io_work.stringSplitByNumbers)
            object_data = []
            for k in xrange(len(fnms)):
                local_dirname_lv2 = data_dirname_new + locDirnames[j] + '/'
                tmp = _imageio.imread(local_dirname_lv2 + fnms[k])
                if resizeValue is not None:
                    newShape = [resizeValue] * 2
                    tmp = _resize(tmp, newShape, mode='constant')
                object_data.append(tmp.copy())
            class_data.append(_copy.deepcopy(object_data))
        data.append(_copy.deepcopy(class_data))
    data = _np.array(data)
    if data.max() > 1.:
        data = data / 255.
    return data, classes
예제 #3
0
def resize(mask, output_shape):
    """Resize a mask to the requested output shape with nearest neighbors

    Parameters
    ----------
    mask : ndarray
        binary array
    output_shape : tuple
        requested shape

    Returns
    -------
    output_shape : tuple
        requested output shape


    TODO: It might be possible to combine this function with one of the transforms
    """
    assert_nD(mask, 2, 'mask')
    assert_binary(mask, 'mask')

    out = _resize(
        mask.astype(np.float), output_shape, order=0, mode='constant', cval=0,
        clip=True, preserve_range=False)

    return out.astype('uint8')
예제 #4
0
def resize():
    img = data2array(request.data)
    size = request.args.get('size', '50%')
    # size can be either "30%" or "200x300"
    if size.endswith('%'):
        def conv(val):
            return int(val * float(size[:-1])/100.0)
        width, height = [conv(v) for v in img.shape[:2]]
    else:
        width, height = [int(v) for v in size.split('x')]

    resized = _resize(img, (width, height))
    return img_resonse(resized)
예제 #5
0
def resize():
    img = data2array(request.data)
    size = request.args.get('size', '50%')
    # size can be either "30%" or "200x300"
    if size.endswith('%'):

        def conv(val):
            return int(val * float(size[:-1]) / 100.0)

        width, height = [conv(v) for v in img.shape[:2]]
    else:
        width, height = [int(v) for v in size.split('x')]

    resized = _resize(img, (width, height))
    return img_resonse(resized)
예제 #6
0
def sig_to_thumbnail(s, out_path, dpi=92):
    """
    Generate a preview thumbnail from an arbitrary HyperSpy signal. For a 2D
    signal, the signal from the first navigation position is used (most
    likely the top- and left-most position. For a 1D signal (*i.e.* a
    spectrum or spectrum image), the output depends on the
    number of navigation dimensions:

    - 0: Image of spectrum
    - 1: Image of linescan (*a la* DigitalMicrograph)
    - 2: Image of spectra sampled from navigation space
    - 2+: As for 2 dimensions

    Parameters
    ----------
    s : :py:class:`hyperspy.signal.BaseSignal` (or subclass)
        The HyperSpy signal for which a thumbnail should be generated
    out_path : str
        A path to the desired thumbnail filename. All formats supported by
        :py:meth:`~matplotlib.figure.Figure.savefig` can be used.
    dpi : int
        The "dots per inch" resolution for the outputted figure

    Returns
    -------
    f : :py:class:`matplotlib.figure.Figure`
        Handle to a matplotlib Figure

    Notes
    -----
    This method heavily utilizes HyperSpy's existing plotting functions to
    figure out how to best display the image
    """
    def _set_extent_and_save():
        _set_title(ax, s.metadata.General.title)
        items = [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
        for labels in _get_visible_labels(ax):
            items += labels
        extent = _full_extent(ax, items, pad=0.05).transformed(
            ax.figure.dpi_scale_trans.inverted())
        f.savefig(out_path, bbox_inches=extent, dpi=dpi)
        _pad_to_square(out_path, 500)
        # _plt.close(f)

    # close all currently open plots to ensure we don't leave a mess behind
    # in memory
    _plt.close('all')
    _plt.rcParams['image.cmap'] = 'gray'

    # Processing 1D signals (spectra, spectrum images, etc)
    if isinstance(s, _hsapi.signals.Signal1D):
        # signal is single spectrum
        if s.axes_manager.navigation_dimension == 0:
            s.plot()
            # get signal plot figure
            f = s._plot.signal_plot.figure
            ax = f.get_axes()[0]
            # Change line color to matplotlib default
            ax.get_lines()[0].set_color(_plt.get_cmap('tab10')(0))
            _set_extent_and_save()
            return f
        # signal is 1D linescan
        elif s.axes_manager.navigation_dimension == 1:
            s.plot()
            s._plot.pointer.set_on(False)  # remove pointer
            f = s._plot.navigator_plot.figure
            f.get_axes()[1].remove()  # remove colorbar scale
            ax = f.get_axes()[0]
            _set_extent_and_save()
            return f
        elif s.axes_manager.navigation_dimension > 1:
            nav_size = s.axes_manager.navigation_size
            if nav_size >= 9:
                n_to_plot = 9
            else:
                n_to_plot = nav_size

            # temporarily unfold the signal so we can get spectra from all
            # over the navigation space easily:
            with s.unfolded():
                idx_to_plot = _np.linspace(0,
                                           nav_size - 1,
                                           n_to_plot,
                                           dtype=int)
                s_to_plot = [s.inav[i] for i in idx_to_plot]

            f = _plt.figure()
            _hsapi.plot.plot_spectra(s_to_plot,
                                     style='cascade',
                                     padding=0.1,
                                     fig=f)
            ax = _plt.gca()

            desc = r'\ x\ '.join(
                [str(x) for x in s.axes_manager.navigation_shape])

            _set_title(ax, s.metadata.General.title)
            ax.set_title(ax.get_title() + '\n' + r"$\bf{" + desc +
                         r'\ Spectrum\ Image}$')

            # Load "watermark" stamp and rescale to be appropriately sized
            stamp = _imread(
                _os.path.join(_dir_path, 'spectrum_image_logo.svg.png'))
            width, height = ax.figure.get_size_inches() * f.dpi
            stamp_width = int(width / 2.5)
            scaling = (stamp_width / float(stamp.shape[0]))
            stamp_height = int(float(stamp.shape[1]) * float(scaling))
            stamp = _resize(stamp, (stamp_width, stamp_height),
                            mode='wrap',
                            anti_aliasing=True)

            # Create matplotlib annotation with image in center
            imagebox = _OIm(stamp, zoom=1, alpha=.15)
            imagebox.image.axes = ax
            ao = _AOb('center', pad=1, borderpad=0, child=imagebox)
            ao.patch.set_alpha(0)
            ax.add_artist(ao)

            # Pack figure and save
            f.tight_layout()
            f.savefig(out_path, dpi=dpi)
            _pad_to_square(out_path, 500)
            return f

    # Signal is an image of some sort, so we'll use hs.plot.plot_images
    elif isinstance(s, _hsapi.signals.Signal2D):
        # signal is single image
        if s.axes_manager.navigation_dimension == 0:
            # check to see if this is a dm3/dm4; if so try to plot with
            # annotations
            orig_fname = s.metadata.General.original_filename
            if '.dm3' in orig_fname or '.dm4' in orig_fname:
                add_annotation_markers(s)
                s.plot(colorbar=False)
                _plt.gca().axis('off')
            else:
                _hsapi.plot.plot_images([s],
                                        axes_decor='off',
                                        colorbar=False,
                                        scalebar='all',
                                        label=None)

            f = _plt.gcf()
            ax = _plt.gca()
            _set_title(ax, s.metadata.General.title)
            f.tight_layout()
            f.savefig(out_path, dpi=dpi)
            _pad_to_square(out_path, 500)
            return f

        # we're looking at an image stack
        elif s.axes_manager.navigation_dimension == 1:
            _plt.figure()
            _plt.imshow(
                _project_image_stack(s,
                                     num=min(5,
                                             s.axes_manager.navigation_size),
                                     dpi=dpi))
            ax = _plt.gca()
            ax.set_position([0, 0, 1, .8])
            ax.set_axis_off()
            _set_title(ax, s.metadata.General.title)
            ax.set_title(ax.get_title() + '\n' + r"$\bf{" +
                         str(s.axes_manager.navigation_size) + r'-member' +
                         r'\ Image\ Series}$')
            # use _full_extent to determine the bounding box needed to pick
            # out just the items we're interested in
            extent = _full_extent(ax, [ax, ax.title], pad=0.1).transformed(
                ax.figure.dpi_scale_trans.inverted())
            ax.figure.savefig(out_path, bbox_inches=extent, dpi=300)
            _pad_to_square(out_path, 500)
            return ax.figure

        # This is a 4D-STEM type image, so display as tableau
        elif s.axes_manager.navigation_dimension == 2:
            asp_ratio = s.axes_manager.signal_shape[
                1] / s.axes_manager.signal_shape[0]
            width = 6
            f = _plt.figure(figsize=(width, width * asp_ratio))
            if s.axes_manager.navigation_size >= 9:
                square_n = 3
            elif s.axes_manager.navigation_size >= 4:
                square_n = 2
            else:
                square_n = 1
            num_to_plot = square_n**2
            im_list = [None] * num_to_plot
            desc = r'\ x\ '.join(
                [str(x) for x in s.axes_manager.navigation_shape])
            s.unfold_navigation_space()
            chunk_size = s.axes_manager.navigation_size // num_to_plot
            for i in range(num_to_plot):
                if square_n == 1:
                    im_list = [s]
                else:
                    im_list[i] = s.inav[i * chunk_size:(i + 1) *
                                        chunk_size].inav[chunk_size // 2]
            axlist = _hsapi.plot.plot_images(im_list,
                                             colorbar=None,
                                             axes_decor='off',
                                             tight_layout=True,
                                             scalebar=[0],
                                             per_row=square_n,
                                             fig=f)

            # Make sure scalebar is fully on plot:
            txt = axlist[0].texts[0]
            left_extent = txt.get_window_extent().transformed(
                axlist[0].transData.inverted()).bounds[0]
            if left_extent < 0:
                # Move scalebar text over if it overlaps outside of axis
                txt.set_x(txt.get_position()[0] + left_extent * -1)
            # txt.set_y(txt.get_position()[1]*1.1)
            f.suptitle(
                _textwrap.fill(s.metadata.General.title, 60) + '\n' +
                r"$\bf{" + desc + r'\ Hyperimage}$')
            f.tight_layout(rect=(0, 0, 1,
                                 f.texts[0].get_window_extent().transformed(
                                     f.transFigure.inverted()).bounds[1]))
            f.savefig(out_path, dpi=dpi)
            _pad_to_square(out_path, 500)
            return f

    # Complex image, so plot power spectrum (like an FFT)
    elif isinstance(s, _hsapi.signals.ComplexSignal2D):
        # in tests, setting minimum to a percentile around 66% looks good
        s.amplitude.plot(interpolation='bilinear',
                         norm='log',
                         vmin=_np.nanpercentile(s.amplitude.data, 66),
                         colorbar=None,
                         axes_off=True)
        f = _plt.gcf()
        ax = _plt.gca()
        _set_title(ax, s.metadata.General.title)
        extent = _full_extent(ax, [ax, ax.title], pad=0.1).transformed(
            ax.figure.dpi_scale_trans.inverted())
        f.savefig(out_path, dpi=dpi, bbox_inches=extent)
        _pad_to_square(out_path, 500)
        return f

    # if we have a different type of signal, just output a graphical
    # representation of the axis manager
    else:
        f, ax = _plt.subplots()
        ax.set_position([0, 0, 1, 1])
        ax.set_axis_off()

        # Remove axes_manager text
        ax_m = s.axes_manager.__repr__()
        ax_m = ax_m.split('\n')
        ax_m = ax_m[1:]
        ax_m = '\n'.join(ax_m)

        ax.text(0.03,
                .9,
                s.metadata.General.title,
                fontweight='bold',
                va='top')
        ax.text(0.03,
                0.85,
                'Could not generate preview image',
                va='top',
                color='r')
        ax.text(0.03, 0.8, 'Axes information:', va='top', fontstyle='italic')
        ax.text(0.03, .75, ax_m, fontfamily='monospace', va='top')

        extent = _full_extent(ax, ax.texts, pad=0.1).transformed(
            ax.figure.dpi_scale_trans.inverted())

        f.savefig(out_path, bbox_inches=extent, dpi=300)
        _pad_to_square(out_path, 500)
        return f