How to use the csbdeep.utils.axes_check_and_normalize function in csbdeep

To help you get started, we’ve selected a few csbdeep examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mpicbg-csbd / stardist / stardist / models / base.py View on Github external
def _axes_tile_overlap(self, query_axes):
        query_axes = axes_check_and_normalize(query_axes)
        try:
            self._tile_overlap
        except AttributeError:
            self._tile_overlap = self._compute_receptive_field()
        overlap = dict(zip(
            self.config.axes.replace('C',''),
            tuple(max(rf) for rf in self._tile_overlap)
        ))
        return tuple(overlap.get(a,0) for a in query_axes)
github CSBDeep / CSBDeep / csbdeep / models / care_projection.py View on Github external
def _axes_div_by(self, query_axes):
        query_axes = axes_check_and_normalize(query_axes)
        proj = self.proj_params
        div_by = {
            a : max(a_proj_pool**proj.n_depth, 1 if a==proj.axis else 2**self.config.unet_n_depth)
            for a,a_proj_pool in zip(self.config.axes.replace('C',''),proj.pool)
        }
        return tuple(div_by.get(a,1) for a in query_axes)
github mpicbg-csbd / stardist / stardist / models / base.py View on Github external
def _normalize_axes(self, img, axes):
        if axes is None:
            axes = self.config.axes
            assert 'C' in axes
            if img.ndim == len(axes)-1 and self.config.n_channel_in == 1:
                # img has no dedicated channel axis, but 'C' always part of config axes
                axes = axes.replace('C','')
        return axes_check_and_normalize(axes, img.ndim)
github CSBDeep / CSBDeep / csbdeep / models.py View on Github external
See :func:`predict` for parameter explanations.

        Returns
        -------
        tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray` or None)
            If model is probabilistic, returns a tuple `(mean, scale)` that defines the parameters
            of per-pixel Laplace distributions. Otherwise, returns the restored image via a tuple `(restored,None)`

        Todo
        ----
        - :func:`scipy.ndimage.interpolation.zoom` differs from :func:`gputools.scale`. Important?

        """
        normalizer, resizer = self._check_normalizer_resizer(normalizer, resizer)
        axes = axes_check_and_normalize(axes,img.ndim)
        'Z' in axes or _raise(ValueError())
        axes_tmp = 'CZ' + axes.replace('Z','').replace('C','')
        _permute_axes = self._make_permute_axes(axes, axes_tmp)
        channel = 0

        x = _permute_axes(img)

        self.config.n_channel_in == x.shape[channel] or _raise(ValueError())
        np.isscalar(factor) and factor > 0 or _raise(ValueError())

        def scale_z(arr,factor):
            return zoom(arr,(1,factor,1,1),order=1)

        # normalize
        x = normalizer.before(x,axes_tmp)
github CSBDeep / CSBDeep / csbdeep / io / __init__.py View on Github external
----------
    file : str
        File name
    X : :class:`numpy.ndarray`
        Array of patches extracted from source images.
    Y : :class:`numpy.ndarray`
        Array of corresponding target patches.
    axes : str
        Axes of the extracted patches.

    """
    isinstance(file,(Path,string_types)) or _raise(ValueError())
    file = Path(file).with_suffix('.npz')
    file.parent.mkdir(parents=True,exist_ok=True)

    axes = axes_check_and_normalize(axes)
    len(axes) == X.ndim or _raise(ValueError())
    np.savez(str(file), X=X, Y=Y, axes=axes)
github CSBDeep / CSBDeep / csbdeep / datagen.py View on Github external
Note that input images must have compatible axes, i.e.
    they must be a permutation of the target axis.

    Parameters
    ----------
    axes : str
        Target axis, to which the input images will be permuted.

    Returns
    -------
    Transform
        Returns a :class:`Transform` object whose `generator` will
        perform the axes permutation of `x`, `y`, and `mask`.

    """
    axes = axes_check_and_normalize(axes)
    def _generator(inputs):
        for x, y, axes_in, mask in inputs:
            axes_in = axes_check_and_normalize(axes_in)
            if axes_in != axes:
                # print('permuting axes from %s to %s' % (axes_in,axes))
                x = move_image_axes(x, axes_in, axes, True)
                y = move_image_axes(y, axes_in, axes, True)
                if mask is not None:
                    mask = move_image_axes(mask, axes_in, axes)
            yield x, y, axes, mask

    return Transform('Permute axes to %s' % axes, _generator, 1)
github CSBDeep / CSBDeep / csbdeep / io / __init__.py View on Github external
Can be used to display information about the loaded images.

    Returns
    -------
    tuple( tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray`), tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray`), str )
        Returns two tuples (`X_train`, `Y_train`), (`X_val`, `Y_val`) of training and validation sets
        and the axes of the input images.
        The tuple of validation data will be ``None`` if ``validation_split = 0``.

    """

    f = np.load(file)
    X, Y = f['X'], f['Y']
    if axes is None:
        axes = f['axes']
    axes = axes_check_and_normalize(axes)

    # assert X.shape == Y.shape
    assert X.ndim == Y.ndim
    assert len(axes) == X.ndim
    assert 'C' in axes
    if n_images is None:
        n_images = X.shape[0]
    assert X.shape[0] == Y.shape[0]
    assert 0 < n_images <= X.shape[0]
    assert 0 <= validation_split < 1

    X, Y = X[:n_images], Y[:n_images]
    channel = axes_dict(axes)['C']

    if validation_split > 0:
        n_val   = int(round(n_images * validation_split))
github CSBDeep / CSBDeep / csbdeep / models / care_standard.py View on Github external
See :func:`predict` for parameter explanations.

        Returns
        -------
        tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray` or None)
            If model is probabilistic, returns a tuple `(mean, scale)` that defines the parameters
            of per-pixel Laplace distributions. Otherwise, returns the restored image via a tuple `(restored,None)`

        """
        normalizer, resizer = self._check_normalizer_resizer(normalizer, resizer)
        # axes = axes_check_and_normalize(axes,img.ndim)

        # different kinds of axes
        # -> typical case: net_axes_in = net_axes_out, img_axes_in = img_axes_out
        img_axes_in = axes_check_and_normalize(axes,img.ndim)
        net_axes_in = self.config.axes
        net_axes_out = axes_check_and_normalize(self._axes_out)
        set(net_axes_out).issubset(set(net_axes_in)) or _raise(ValueError("different kinds of output than input axes"))
        net_axes_lost = set(net_axes_in).difference(set(net_axes_out))
        img_axes_out = ''.join(a for a in img_axes_in if a not in net_axes_lost)
        # print(' -> '.join((img_axes_in, net_axes_in, net_axes_out, img_axes_out)))
        tiling_axes = net_axes_out.replace('C','') # axes eligible for tiling

        _permute_axes = self._make_permute_axes(img_axes_in, net_axes_in, net_axes_out, img_axes_out)
        # _permute_axes: (img_axes_in -> net_axes_in), undo: (net_axes_out -> img_axes_out)
        x = _permute_axes(img)
        # x has net_axes_in semantics
        x_tiling_axis = tuple(axes_dict(net_axes_in)[a] for a in tiling_axes) # numerical axis ids for x

        channel_in = axes_dict(net_axes_in)['C']
        channel_out = axes_dict(net_axes_out)['C']
github CSBDeep / CSBDeep / csbdeep / models / care_isotropic.py View on Github external
def _predict_mean_and_scale(self, img, axes, factor, normalizer, resizer, batch_size):
        """Apply neural network to raw image to restore isotropic resolution.

        See :func:`predict` for parameter explanations.

        Returns
        -------
        tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray` or None)
            If model is probabilistic, returns a tuple `(mean, scale)` that defines the parameters
            of per-pixel Laplace distributions. Otherwise, returns the restored image via a tuple `(restored,None)`

        """
        normalizer, resizer = self._check_normalizer_resizer(normalizer, resizer)
        axes = axes_check_and_normalize(axes,img.ndim)
        'Z' in axes or _raise(ValueError())
        axes_tmp = 'CZ' + axes.replace('Z','').replace('C','')
        _permute_axes = self._make_permute_axes(axes, axes_tmp)
        channel = 0

        x = _permute_axes(img)

        self.config.n_channel_in == x.shape[channel] or _raise(ValueError())
        np.isscalar(factor) and factor > 0 or _raise(ValueError())

        def scale_z(arr,factor):
            return zoom(arr,(1,factor,1,1),order=1)

        # normalize
        x = normalizer.before(x,axes_tmp)
github CSBDeep / CSBDeep / csbdeep / models / care_standard.py View on Github external
def _axes_div_by(self, query_axes):
        query_axes = axes_check_and_normalize(query_axes)
        # default: must be divisible by power of 2 to allow down/up-sampling steps in unet
        pool_div_by = 2**self.config.unet_n_depth
        return tuple((pool_div_by if a in 'XYZT' else 1) for a in query_axes)