Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_model_train(tmpdir,config):
rng = np.random.RandomState(42)
K.clear_session()
X = rng.uniform(size=(4,)+(32,)*config.n_dim+(config.n_channel_in,))
Y = rng.uniform(size=(4,)+(32,)*config.n_dim+(config.n_channel_out,))
model = CARE(config,basedir=str(tmpdir))
model.train(X,Y,(X,Y))
def _build():
with pytest.raises(FileNotFoundError):
CARE(None,basedir=str(tmpdir))
CARE(config,name='model',basedir=None)
with pytest.raises(ValueError):
CARE(None,basedir=None)
CARE(config,basedir=str(tmpdir)).export_TF()
with pytest.warns(UserWarning):
CARE(config,name='model',basedir=str(tmpdir))
CARE(config,name='model',basedir=str(tmpdir))
CARE(None,name='model',basedir=str(tmpdir))
if config.is_valid():
def _build():
with pytest.raises(FileNotFoundError):
CARE(None,basedir=str(tmpdir))
CARE(config,name='model',basedir=None)
with pytest.raises(ValueError):
CARE(None,basedir=None)
CARE(config,basedir=str(tmpdir)).export_TF()
with pytest.warns(UserWarning):
CARE(config,name='model',basedir=str(tmpdir))
CARE(config,name='model',basedir=str(tmpdir))
CARE(None,name='model',basedir=str(tmpdir))
if config.is_valid():
def _build():
with pytest.raises(FileNotFoundError):
CARE(None,basedir=str(tmpdir))
CARE(config,name='model',basedir=None)
with pytest.raises(ValueError):
CARE(None,basedir=None)
CARE(config,basedir=str(tmpdir)).export_TF()
with pytest.warns(UserWarning):
CARE(config,name='model',basedir=str(tmpdir))
CARE(config,name='model',basedir=str(tmpdir))
CARE(None,name='model',basedir=str(tmpdir))
if config.is_valid():
def test_model_predict(tmpdir,config):
rng = np.random.RandomState(42)
normalizer, resizer = NoNormalizer(), NoResizer()
K.clear_session()
model = CARE(config,basedir=str(tmpdir))
axes = config.axes
def _predict(imdims,axes):
img = rng.uniform(size=imdims)
# print(img.shape, axes, config.n_channel_out)
if config.probabilistic:
prob = model.predict_probabilistic(img, axes, normalizer, resizer)
mean, scale = prob.mean(), prob.scale()
assert mean.shape == scale.shape
else:
mean = model.predict(img, axes, normalizer, resizer)
if 'C' not in axes:
if config.n_channel_out == 1:
assert mean.shape == img.shape
else:
normalizer = NoNormalizer()
if resizer is None:
resizer = NoResizer()
isinstance(resizer,Resizer) or _raise(ValueError())
isinstance(normalizer,Normalizer) or _raise(ValueError())
if normalizer.do_after:
if self.config.n_channel_in != self.config.n_channel_out:
warnings.warn('skipping normalization step after prediction because ' +
'number of input and output channels differ.')
return normalizer, resizer
class IsotropicCARE(CARE):
"""CARE network for isotropic image reconstruction.
Extends :class:`csbdeep.models.CARE` by replacing prediction
(:func:`predict`, :func:`predict_probabilistic`) to do isotropic reconstruction.
"""
def predict(self, img, axes, factor, normalizer=PercentileNormalizer(), resizer=PadAndCropResizer(), batch_size=8):
"""Apply neural network to raw image to restore isotropic resolution.
Parameters
----------
img : :class:`numpy.ndarray`
Raw input image, with image dimensions expected in the same order as in data for training.
If applicable, only the z and channel dimensions can be anywhere.
axes : str
Axes of ``img``.
from tifffile import imread, imsave
from csbdeep.utils.tf import keras_import
K = keras_import('backend')
from csbdeep.models import CARE
from csbdeep.data import PercentileNormalizer
sys.stdout.flush()
sys.stderr.flush()
# limit gpu memory
if args.gpu_memory_limit is not None:
from csbdeep.utils.tf import limit_gpu_memory
limit_gpu_memory(args.gpu_memory_limit)
# create CARE model and load weights, create normalizer
K.clear_session()
model = CARE(config=None, name=args.model_name, basedir=args.model_basedir)
if args.model_weights is not None:
print("Loading network weights from '%s'." % args.model_weights)
model.load_weights(args.model_weights)
normalizer = PercentileNormalizer(pmin=args.norm_pmin, pmax=args.norm_pmax, do_after=args.norm_undo)
n_tiles = args.n_tiles
if n_tiles is not None and len(n_tiles)==1:
n_tiles = n_tiles[0]
processed = []
# process all files
for file_in in tqdm(file_list, disable=args.quiet or (n_tiles is not None and np.prod(n_tiles)>1)):
# construct output file name
file_out = Path(args.output_dir) / args.output_name.format (
file_path = str(file_in.relative_to(args.input_dir).parent),
from zipfile import ZipFile
from .n2v_config import N2VConfig
from ..internals.N2V_DataWrapper import N2V_DataWrapper
from ..internals.n2v_losses import loss_mse, loss_mae
from ..utils import n2v_utils
from ..utils.n2v_utils import pm_identity, pm_normal_additive, pm_normal_fitted, pm_normal_withoutCP, pm_uniform_withCP
from ..nets.unet import build_single_unet_per_channel
from tifffile import imsave
import keras
from csbdeep.utils.six import tempfile
import shutil
import numpy as np
class N2V(CARE):
"""The Noise2Void training scheme to train a standard CARE network for image restoration and enhancement.
Uses a convolutional neural network created by :func:`csbdeep.internals.nets.custom_unet`.
Parameters
----------
config : :class:`n2v.models.N2VConfig` or None
Valid configuration of N2V network (see :func:`N2VConfig.is_valid`).
Will be saved to disk as JSON (``config.json``).
If set to ``None``, will be loaded from disk (must exist).
name : str or None
Model name. Uses a timestamp if set to ``None`` (default).
basedir : str
Directory that contains (or will contain) a folder with the given model name.
Use ``None`` to disable saving (or loading) any data to (or from) disk (regardless of other parameters).