Ejemplo n.º 1
0
def test_resizer(axes):
    rng = np.random.RandomState(42)

    resizer = PadAndCropResizer()
    checker = NoResizer()

    for _ in range(50):

        imdims = list(rng.randint(20,40,size=len(axes)))
        div_by = list(rng.randint(1,20,size=len(axes)))

        u = np.empty(imdims,np.float32)
        if any(s%div_n!=0 for s, div_n in zip(imdims, div_by)):
            with pytest.raises(ValueError):
                checker.before(u, axes, div_by)

        v = resizer.before(u, axes, div_by)
        assert all (
            s_v >= s_u and s_v%div_n==0
            for s_u, s_v, div_n in zip(u.shape, v.shape, div_by)
        )

        w = resizer.after(v, axes)
        assert u.shape == w.shape

        d = rng.choice(len(axes))
        _axes = axes.replace(axes[d],'')
        _u = np.take(u,0,axis=d)
        _v = np.take(v,0,axis=d)
        _w = resizer.after(_v, _axes)
        assert _u.shape == _w.shape
Ejemplo n.º 2
0
    def predict(self, img, axes, resizer=PadAndCropResizer(), n_tiles=None):
        """
        Apply the network to sofar unseen data. This method expects the raw data, i.e. not normalized.
        During prediction the mean and standard deviation, stored with the model (during data generation), are used
        for normalization.

        Parameters
        ----------
        img     : array(floats)
                  The raw images.
        axes    : String
                  Axes of the image ('YX').
        resizer : class(Resizer), optional(default=PadAndCropResizer())
        n_tiles : tuple(int)
                  Number of tiles to tile the image into, if it is too large for memory.

        Returns
        -------
        image : array(float)
                The restored image.
        """
        mean, std = float(self.config.mean), float(self.config.std)

        normalized = self.__normalize__(img, mean, std)

        pred = self._predict_mean_and_scale(normalized, axes=axes, normalizer=None, resizer=resizer, n_tiles=n_tiles)[0]

        return self.__denormalize__(pred, mean, std)
Ejemplo n.º 3
0
    def predict(self, img, axes, resizer=PadAndCropResizer(), n_tiles=None):
        """
        Apply the network to sofar unseen data. This method expects the raw data, i.e. not normalized.
        During prediction the mean and standard deviation, stored with the model (during data generation), are used
        for normalization.

        Parameters
        ----------
        img     : array(floats)
                  The raw images.
        axes    : String
                  Axes of the image ('YX').
        resizer : class(Resizer), optional(default=PadAndCropResizer())
        n_tiles : tuple(int)
                  Number of tiles to tile the image into, if it is too large for memory.

        Returns
        -------
        image : array(float)
                The restored image.
        """
        means = np.array([float(mean) for mean in self.config.means],
                         ndmin=len(img.shape),
                         dtype=np.float32)
        stds = np.array([float(std) for std in self.config.stds],
                        ndmin=len(img.shape),
                        dtype=np.float32)

        if img.dtype != np.float32:
            print(
                'The input image is of type {} and will be casted to float32 for prediction.'
                .format(img.dtype))
            img = img.astype(np.float32)

        new_axes = axes
        new_n_tiles = n_tiles
        if 'C' in axes:
            new_axes = axes.replace('C', '') + 'C'
            if n_tiles:
                new_n_tiles = tuple(
                    [n_tiles[axes.index(c)]
                     for c in axes if c != 'C']) + (n_tiles[axes.index('C')], )
            normalized = self.__normalize__(
                np.moveaxis(img, axes.index('C'), -1), means, stds)
        else:
            normalized = self.__normalize__(img[..., np.newaxis], means, stds)
            normalized = normalized[..., 0]

        pred = self._predict_mean_and_scale(normalized,
                                            axes=new_axes,
                                            normalizer=None,
                                            resizer=resizer,
                                            n_tiles=new_n_tiles)[0]

        pred = self.__denormalize__(pred, means, stds)

        if 'C' in axes:
            pred = np.moveaxis(pred, -1, axes.index('C'))

        return pred
Ejemplo n.º 4
0
    def predict(self, img, axes, resizer=PadAndCropResizer(), n_tiles=None):
        """
        Apply the network to so far unseen data. 
        Parameters
        ----------
        img     : array(floats) of images
        axes    : String
                  Axes of the image ('YX').
        resizer : class(Resizer), optional(default=PadAndCropResizer())
        n_tiles : tuple(int)
                  Number of tiles to tile the image into, if it is too large for memory.
        Returns
        -------
        image : array(float)
                The restored image.
        """

        if img.dtype != np.float32:
            print(
                'The input image is of type {} and will be casted to float32 for prediction.'
                .format(img.dtype))
            img = img.astype(np.float32)

        new_axes = axes
        normalized = img[..., np.newaxis]
        normalized = normalized[..., 0]
        pred = \
        self._predict_mean_and_scale(normalized, axes=new_axes, normalizer=None, resizer=resizer, n_tiles=n_tiles)[0]

        return pred
Ejemplo n.º 5
0
    def predict(self, img, axes, resizer=PadAndCropResizer(), n_tiles=None):
        """
        Apply the network to so far unseen data. 
        Parameters
        ----------
        img     : array(floats) of images
        axes    : String
                  Axes of the image ('YX').
        resizer : class(Resizer), optional(default=PadAndCropResizer())
        n_tiles : tuple(int)
                  Number of tiles to tile the image into, if it is too large for memory.
        Returns
        -------
        image : array(float)
                The restored image.
        """
        means = np.array([float(mean) for mean in self.config.means],
                         ndmin=len(img.shape),
                         dtype=np.float32)
        stds = np.array([float(std) for std in self.config.stds],
                        ndmin=len(img.shape),
                        dtype=np.float32)

        if img.dtype != np.float32:
            print(
                'The input image is of type {} and will be casted to float32 for prediction.'
                .format(img.dtype))
            img = img.astype(np.float32)

        # new_axes = axes
        new_axes = axes
        if 'C' in axes:
            new_axes = axes.replace('C', '') + 'C'
            normalized = self.__normalize__(
                np.moveaxis(img, axes.index('C'), -1), means, stds)
        else:
            normalized = self.__normalize__(img[..., np.newaxis], means, stds)
            normalized = normalized[..., 0]

        pred_full = self._predict_mean_and_scale(normalized,
                                                 axes=new_axes,
                                                 normalizer=None,
                                                 resizer=resizer,
                                                 n_tiles=n_tiles)[0]

        pred_denoised = self.__denormalize__(pred_full[..., :1], means, stds)

        pred = np.concatenate([pred_denoised, pred_full[..., 1:]], axis=-1)

        if 'C' in axes:
            pred = np.moveaxis(pred, -1, axes.index('C'))

        return pred
Ejemplo n.º 6
0
    def predict(self, img, resizer=PadAndCropResizer(), **predict_kwargs):
        """Predict.

        Parameters
        ----------
        img : :class:`numpy.ndarray`
            Input image
        resizer : :class:`csbdeep.data.Resizer` or None
            If necessary, input image is resized to enable neural network prediction and result is (possibly)
            resized to yield original image size.

        Returns
        -------
        (:class:`numpy.ndarray`,:class:`numpy.ndarray`)
            Returns the tuple (`prob`, `dist`) of per-pixel object probabilities and star-convex polygon distances.

        """
        if resizer is None:
            resizer = NoResizer()
        isinstance(resizer, Resizer) or _raise(ValueError())

        img.ndim in (2, 3) or _raise(ValueError())

        x = img
        if x.ndim == 2:
            x = np.expand_dims(x, (-1 if backend_channels_last() else 0))

        channel = x.ndim - 1 if backend_channels_last() else 0
        axes = 'YXC' if backend_channels_last() else 'CYX'
        self.config.n_channel_in == x.shape[channel] or _raise(ValueError())

        # resize: make divisible by power of 2 to allow downsampling steps in unet
        axes_div_by = tuple(2**self.config.unet_n_depth if a != 'C' else 1
                            for a in axes)
        x = resizer.before(x, axes, axes_div_by)

        if backend_channels_last():
            sh = x.shape[:-1] + (1, )
        else:
            sh = (1, ) + x.shape[1:]
        dummy = np.empty((1, ) + sh, np.float32)

        prob, dist = self.keras_model.predict([np.expand_dims(x, 0), dummy],
                                              **predict_kwargs)
        prob, dist = prob[0], dist[0]

        prob = resizer.after(prob, axes)
        dist = resizer.after(dist, axes)

        prob = np.take(prob, 0, axis=channel)
        dist = np.moveaxis(dist, channel, -1)

        return prob, dist
Ejemplo n.º 7
0
 def norm_and_predict(x, axes):
     nonorm = NoNormalizer()
     resizer = PadAndCropResizer()
     restored = model.predict(x, axes, subsample, nonorm, resizer)
     return restored