Exemplo 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
Exemplo n.º 2
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