code stringlengths 17 6.64M |
|---|
def shape2d(a):
'\n a: a int or tuple/list of length 2\n '
if (type(a) == int):
return [a, a]
if isinstance(a, (list, tuple)):
assert (len(a) == 2)
return list(a)
raise RuntimeError('Illegal shape: {}'.format(a))
|
class StoppableThread(threading.Thread):
"\n A thread that has a 'stop' event.\n "
def __init__(self):
super(StoppableThread, self).__init__()
self._stop_evt = threading.Event()
def stop(self):
' stop the thread'
self._stop_evt.set()
def stopped(self):
... |
class LoopThread(StoppableThread):
' A pausable thread that simply runs a loop'
def __init__(self, func, pausable=True):
'\n :param func: the function to run\n '
super(LoopThread, self).__init__()
self._func = func
self._pausable = pausable
if pausable:
... |
class DIE(object):
' A placeholder class indicating end of queue '
pass
|
def ensure_proc_terminate(proc):
if isinstance(proc, list):
for p in proc:
ensure_proc_terminate(p)
return
def stop_proc_by_weak_ref(ref):
proc = ref()
if (proc is None):
return
if (not proc.is_alive()):
return
proc.terminate... |
@contextmanager
def mask_sigint():
sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
(yield)
signal.signal(signal.SIGINT, sigint_handler)
|
def start_proc_mask_signal(proc):
if (not isinstance(proc, list)):
proc = [proc]
with mask_sigint():
for p in proc:
p.start()
|
def subproc_call(cmd, timeout=None):
try:
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True, timeout=timeout)
return output
except subprocess.TimeoutExpired as e:
logger.warn('Command timeout!')
logger.warn(e.output)
except subprocess.CalledProcessE... |
class OrderedContainer(object):
'\n Like a priority queue, but will always wait for item with index (x+1) before producing (x+2).\n '
def __init__(self, start=0):
self.ranks = []
self.data = []
self.wait_for = start
def put(self, rank, val):
idx = bisect.bisect(self... |
class OrderedResultGatherProc(multiprocessing.Process):
'\n Gather indexed data from a data queue, and produce results with the\n original index-based order.\n '
def __init__(self, data_queue, nr_producer, start=0):
'\n :param data_queue: a multiprocessing.Queue to produce input dp\n ... |
def enable_call_trace():
def tracer(frame, event, arg):
if (event == 'call'):
co = frame.f_code
func_name = co.co_name
if ((func_name == 'write') or (func_name == 'print')):
return
func_line_no = frame.f_lineno
func_filename = co... |
@memoized
def log_once(s):
logger.warn(s)
|
@six.add_metaclass(ABCMeta)
class Discretizer(object):
@abstractmethod
def get_nr_bin(self):
pass
@abstractmethod
def get_bin(self, v):
pass
|
class Discretizer1D(Discretizer):
pass
|
class UniformDiscretizer1D(Discretizer1D):
def __init__(self, minv, maxv, spacing):
'\n :params minv: minimum value of the first bin\n :params maxv: maximum value of the last bin\n :param spacing: width of a bin\n '
self.minv = float(minv)
self.maxv = float(max... |
class UniformDiscretizerND(Discretizer):
def __init__(self, *min_max_spacing):
'\n :params min_max_spacing: (minv, maxv, spacing) for each dimension\n '
self.n = len(min_max_spacing)
self.discretizers = [UniformDiscretizer1D(*k) for k in min_max_spacing]
self.nr_bins... |
def mkdir_p(dirname):
' make a dir recursively, but do nothing if the dir exists'
assert (dirname is not None)
if ((dirname == '') or os.path.isdir(dirname)):
return
try:
os.makedirs(dirname)
except OSError as e:
if (e.errno != errno.EEXIST):
raise e
|
def download(url, dir):
mkdir_p(dir)
fname = url.split('/')[(- 1)]
fpath = os.path.join(dir, fname)
def _progress(count, block_size, total_size):
sys.stdout.write(('\r>> Downloading %s %.1f%%' % (fname, (min((float((count * block_size)) / total_size), 1.0) * 100.0))))
sys.stdout.flush... |
def recursive_walk(rootdir):
for (r, dirs, files) in os.walk(rootdir):
for f in files:
(yield os.path.join(r, f))
|
def use_global_argument(args):
'\n Add the content of argparse.Namespace to globalns\n :param args: Argument\n '
assert isinstance(args, argparse.Namespace), type(args)
for (k, v) in six.iteritems(vars(args)):
setattr(globalns, k, v)
|
def change_gpu(val):
val = str(val)
if (val == '-1'):
val = ''
return change_env('CUDA_VISIBLE_DEVICES', val)
|
def get_nr_gpu():
env = os.environ.get('CUDA_VISIBLE_DEVICES', None)
assert (env is not None), 'gpu not set!'
return len(env.split(','))
|
def get_gpus():
' return a list of GPU physical id'
env = os.environ.get('CUDA_VISIBLE_DEVICES', None)
assert (env is not None), 'gpu not set!'
return map(int, env.strip().split(','))
|
class CaffeLayerProcessor(object):
def __init__(self, net):
self.net = net
self.layer_names = net._layer_names
self.param_dict = {}
self.processors = {'Convolution': self.proc_conv, 'InnerProduct': self.proc_fc, 'BatchNorm': self.proc_bn, 'Scale': self.proc_scale}
def process... |
def load_caffe(model_desc, model_file):
'\n :return: a dict of params\n '
with change_env('GLOG_minloglevel', '2'):
import caffe
caffe.set_mode_cpu()
net = caffe.Net(model_desc, model_file, caffe.TEST)
param_dict = CaffeLayerProcessor(net).process()
logger.info(('Model lo... |
def get_caffe_pb():
dir = get_dataset_path('caffe')
caffe_pb_file = os.path.join(dir, 'caffe_pb2.py')
if (not os.path.isfile(caffe_pb_file)):
assert os.path.isfile(os.path.join(dir, 'caffe.proto'))
ret = os.system('cd {} && protoc caffe.proto --python_out .'.format(dir))
assert (re... |
class _MyFormatter(logging.Formatter):
def format(self, record):
date = colored('[%(asctime)s @%(filename)s:%(lineno)d]', 'green')
msg = '%(message)s'
if (record.levelno == logging.WARNING):
fmt = ((((date + ' ') + colored('WRN', 'red', attrs=['blink'])) + ' ') + msg)
... |
def _getlogger():
logger = logging.getLogger('tensorpack')
logger.propagate = False
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(_MyFormatter(datefmt='%m%d %H:%M:%S'))
logger.addHandler(handler)
return logger
|
def get_time_str():
return datetime.now().strftime('%m%d-%H%M%S')
|
def _set_file(path):
if os.path.isfile(path):
backup_name = ((path + '.') + get_time_str())
shutil.move(path, backup_name)
info("Log file '{}' backuped to '{}'".format(path, backup_name))
hdl = logging.FileHandler(filename=path, encoding='utf-8', mode='w')
hdl.setFormatter(_MyForma... |
def set_logger_dir(dirname, action=None):
'\n Set the directory for global logging.\n :param dirname: log directory\n :param action: an action (k/b/d/n) to be performed. Will ask user by default.\n '
global LOG_FILE, LOG_DIR
if os.path.isdir(dirname):
if (not action):
_logg... |
def disable_logger():
' disable all logging ability from this moment'
for func in _LOGGING_METHOD:
globals()[func] = (lambda x: None)
|
def auto_set_dir(action=None, overwrite=False):
" set log directory to a subdir inside 'train_log', with the name being\n the main python file currently running"
if ((LOG_DIR is not None) and (not overwrite)):
return
mod = sys.modules['__main__']
basename = os.path.basename(mod.__file__)
... |
def warn_dependency(name, dependencies):
warn("Failed to import '{}', {} won't be available'".format(dependencies, name))
|
class LookUpTable(object):
def __init__(self, objlist):
self.idx2obj = dict(enumerate(objlist))
self.obj2idx = {v: k for (k, v) in six.iteritems(self.idx2obj)}
def size(self):
return len(self.idx2obj)
def get_obj(self, idx):
return self.idx2obj[idx]
def get_idx(self... |
def dumps(obj):
return msgpack.dumps(obj, use_bin_type=True)
|
def loads(buf):
return msgpack.loads(buf)
|
class StatCounter(object):
' A simple counter'
def __init__(self):
self.reset()
def feed(self, v):
self._values.append(v)
def reset(self):
self._values = []
@property
def count(self):
return len(self._values)
@property
def average(self):
ass... |
class RatioCounter(object):
' A counter to count ratio of something'
def __init__(self):
self.reset()
def reset(self):
self._tot = 0
self._cnt = 0
def feed(self, cnt, tot=1):
self._tot += tot
self._cnt += cnt
@property
def ratio(self):
if (se... |
class Accuracy(RatioCounter):
' A RatioCounter with a fancy name '
@property
def accuracy(self):
return self.ratio
|
class BinaryStatistics(object):
'\n Statistics for binary decision,\n including precision, recall, false positive, false negative\n '
def __init__(self):
self.reset()
def reset(self):
self.nr_pos = 0
self.nr_neg = 0
self.nr_pred_pos = 0
self.nr_pred_neg =... |
class OnlineMoments(object):
'Compute 1st and 2nd moments online\n See algorithm at: https://www.wikiwand.com/en/Algorithms_for_calculating_variance#/Online_algorithm\n '
def __init__(self):
self._mean = 0
self._M2 = 0
self._n = 0
def feed(self, x):
self._n += 1
... |
class IterSpeedCounter(object):
' To count how often some code gets reached'
def __init__(self, print_every, name=None):
self.cnt = 0
self.print_every = int(print_every)
self.name = (name if name else 'IterSpeed')
def reset(self):
self.start = time.time()
def __call_... |
@contextmanager
def timed_operation(msg, log_start=False):
if log_start:
logger.info('Start {} ...'.format(msg))
start = time.time()
(yield)
logger.info('{} finished, time:{:.2f}sec.'.format(msg, (time.time() - start)))
|
@contextmanager
def total_timer(msg):
start = time.time()
(yield)
t = (time.time() - start)
_TOTAL_TIMER_DATA[msg].feed(t)
|
def print_total_timer():
if (len(_TOTAL_TIMER_DATA) == 0):
return
for (k, v) in six.iteritems(_TOTAL_TIMER_DATA):
logger.info('Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time'.format(k, v.sum, v.count, v.average))
|
@contextmanager
def change_env(name, val):
oldval = os.environ.get(name, None)
os.environ[name] = val
(yield)
if (oldval is None):
del os.environ[name]
else:
os.environ[name] = oldval
|
def get_rng(obj=None):
' obj: some object to use to generate random seed'
seed = (((id(obj) + os.getpid()) + int(datetime.now().strftime('%Y%m%d%H%M%S%f'))) % 4294967295)
return np.random.RandomState(seed)
|
def execute_only_once():
'\n when called with:\n if execute_only_once():\n # do something\n The body is guranteed to be executed only the first time.\n '
f = inspect.currentframe().f_back
ident = (f.f_code.co_filename, f.f_lineno)
if (ident in _EXECUTE_HISTORY):
retu... |
def get_dataset_path(*args):
d = os.environ.get('TENSORPACK_DATASET', None)
if (d is None):
d = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'dataflow', 'dataset'))
if execute_only_once():
from . import logger
logger.info('TENSORPACK_DATASET not set, us... |
def get_tqdm_kwargs(**kwargs):
default = dict(smoothing=0.5, dynamic_ncols=True, ascii=True, bar_format='{l_bar}{bar}|{n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_noinv_fmt}]')
f = kwargs.get('file', sys.stderr)
if f.isatty():
default['mininterval'] = 0.5
else:
default['mininterval'... |
def get_tqdm(**kwargs):
return tqdm(**get_tqdm_kwargs(**kwargs))
|
def ukbiobank_data():
data_dir = config.data_root
code_dir = config.code_root
statistics_file = os.path.join(code_dir, 'Preprocessing', 'statistics_record.txt')
doubtful_case_file = os.path.join(code_dir, 'Preprocessing', 'doubtful_segmentation_cases2.txt')
base_slices_file = os.path.join(code_dir... |
def ukbiobank_data():
data_dir = config.data_root
code_dir = config.code_root
statistics_file = os.path.join(code_dir, 'Preprocessing', 'statistics_record.txt')
doubtful_case_file = os.path.join(code_dir, 'Preprocessing', 'doubtful_segmentation_cases2.txt')
base_slices_file = os.path.join(code_dir... |
def net_module(input_shape, num_outputs):
'Builds a net architecture.\n Args:\n input_shape: The input shape in the form (nb_rows, nb_cols, nb_channels)\n num_outputs: The number of outputs at final softmax layer\n Returns:\n The keras `Model`.\n '
CHANNEL_AXIS = 3
ha... |
def train_lvrv_net():
code_path = config.code_root
initial_lr = config.lvrv_net_initial_lr
decay_rate = config.lvrv_net_decay_rate
batch_size = config.lvrv_net_batch_size
input_img_size = config.lvrv_net_imput_img_size
epochs = config.lvrv_net_epochs
current_epoch = 0
new_start_epoch =... |
def ukbiobank_data():
data_dir = config.data_root
code_dir = config.code_root
statistics_file = os.path.join(code_dir, 'Preprocessing', 'statistics_record.txt')
doubtful_case_file = os.path.join(code_dir, 'Preprocessing', 'doubtful_segmentation_cases2.txt')
base_slices_file = os.path.join(code_dir... |
def ukbiobank_data():
data_dir = config.data_root
code_dir = config.code_root
statistics_file = os.path.join(code_dir, 'Preprocessing', 'statistics_record.txt')
doubtful_case_file = os.path.join(code_dir, 'Preprocessing', 'doubtful_segmentation_cases2.txt')
base_slices_file = os.path.join(code_dir... |
def net_module(input_shape, num_outputs):
'Builds a net architecture.\n Args:\n input_shape: The input shape in the form (nb_rows, nb_cols, nb_channels)\n num_outputs: The number of outputs at final softmax layer\n Returns:\n The keras `Model`.\n '
CHANNEL_AXIS = 3
ha... |
def train_lv_net():
code_path = config.code_root
initial_lr = config.lv_net_initial_lr
decay_rate = config.lv_net_decay_rate
batch_size = config.lv_net_batch_size
input_img_size = config.lv_net_imput_img_size
epochs = config.lv_net_epochs
current_epoch = 0
new_start_epoch = current_epo... |
def adapt_ground_truth(adapt_original=True):
data_dir = config.data_root
code_dir = config.code_root
statistics_file = os.path.join(code_dir, 'Preprocessing', 'statistics_record.txt')
doubtful_case_file = os.path.join(code_dir, 'Preprocessing', 'doubtful_segmentation_cases2.txt')
if adapt_original... |
def ukbiobank_data():
data_dir = config.data_root
code_dir = config.code_root
statistics_file = os.path.join(code_dir, 'Preprocessing', 'statistics_record.txt')
doubtful_case_file = os.path.join(code_dir, 'Preprocessing', 'doubtful_segmentation_cases2.txt')
with open(statistics_file) as s_file:
... |
def ukbiobank_data():
data_dir = config.data_root
code_dir = config.code_root
statistics_file = os.path.join(code_dir, 'Preprocessing', 'statistics_record.txt')
doubtful_case_file = os.path.join(code_dir, 'Preprocessing', 'doubtful_segmentation_cases2.txt')
base_slices_file = os.path.join(code_dir... |
def net_module(input_shape, num_outputs):
'Builds a net architecture.\n Args:\n input_shape: The input shape in the form (nb_rows, nb_cols, nb_channels)\n num_outputs: The number of outputs at final softmax layer\n Returns:\n The keras `Model`.\n '
CHANNEL_AXIS = 3
ha... |
def train_roi_net():
code_path = config.code_root
initial_lr = config.roi_net_initial_lr
decay_rate = config.roi_net_decay_rate
batch_size = config.roi_net_batch_size
input_img_size = config.roi_net_imput_img_size
epochs = config.roi_net_epochs
current_epoch = 0
new_start_epoch = curre... |
def download_weights():
if (sys.version_info >= (3, 0)):
import urllib.request as urltool
else:
import urllib as urltool
code_dir = config.code_root
print('Downloading pretrained ROI-net')
roi_net_source = 'http://www-sop.inria.fr/members/Qiao.Zheng/CardiacSegmentationPropagation/R... |
def PSNR(gt, img):
mse = np.mean(np.square((gt - img)))
return ((20 * np.log10(255)) - (10 * np.log10(mse)))
|
def loss_mse():
def n2v_mse(y_true, y_pred):
(target, mask) = tf.split(y_true, 2, axis=(len(y_true.shape) - 1))
loss = (tf.reduce_sum(K.square((target - (y_pred * mask)))) / tf.reduce_sum(mask))
return loss
return n2v_mse
|
def loss_mae():
def n2v_abs(y_true, y_pred):
(target, mask) = tf.split(y_true, 2, axis=(len(y_true.shape) - 1))
loss = (tf.reduce_sum(K.abs((target - (y_pred * mask)))) / tf.reduce_sum(mask))
return loss
return n2v_abs
|
class N2VConfig(argparse.Namespace):
"Default configuration for a N2V trainable CARE model.\n\n This class is meant to be used with :class:`N2V`.\n\n Parameters\n ----------\n X : array(float)\n The training data 'X', with dimensions 'SZYXC' or 'SYXC'\n kwargs : dict\n ... |
class N2V(CARE):
"The Noise2Void training scheme to train a standard CARE network for image restoration and enhancement.\n\n Uses a convolutional neural network created by :func:`csbdeep.internals.nets.custom_unet`.\n\n Parameters\n ----------\n config : :class:`n2v.models.N2VConfig` o... |
class MaxBlurPool2D(Layer):
'\n MaxBlurPool proposed in:\n Zhang, Richard. "Making convolutional networks shift-invariant again."\n International conference on machine learning. PMLR, 2019.\n\n Implementation inspired by: https://github.com/csvance/blur-pool-keras\n '
def __init__(self, pool, ... |
def unet_block(n_depth=2, n_filter_base=16, kernel_size=(3, 3), n_conv_per_depth=2, activation='relu', batch_norm=False, dropout=0.0, last_activation=None, pool=(2, 2), kernel_init='glorot_uniform', prefix='', blurpool=False, skip_skipone=False):
if (len(pool) != len(kernel_size)):
raise ValueError('kerne... |
def PSNR(gt, img, range):
'\n Compute Peak Signal-to-Noise Ratio.\n\n Parameters:\n gt: np.array\n The ground truth target image.\n img: np.array\n The image of interest.\n range: float\n Intensity range e.g. gt.max() - gt.min() used for the PSNR\n ... |
def best_PSNR(gt, img, range):
'\n Compute best Peak Signal-to-Noise Ratio by normalizing img such that\n MSE is minimized to the gt image.\n\n Parameters:\n gt: np.array\n The ground truth target image.\n img: np.array\n The image of interest.\n range: float\n ... |
class Extensions(Enum):
BIOIMAGE_EXT = '.bioimage.io.zip'
KERAS_EXT = '.h5'
TF_EXT = '.zip'
|
class Format(Enum):
H5 = 'h5'
TF = 'tf'
|
class Algorithm(Enum):
N2V = 0
StructN2V = 1
N2V2 = 2
@staticmethod
def get_name(algorithm: int) -> str:
if (algorithm == 1):
return 'structN2V'
elif (algorithm == 2):
return 'N2V2'
else:
return 'Noise2Void'
|
class PixelManipulator(Enum):
UNIFORM_WITH_CP = 'uniform_withCP'
UNIFORM_WITHOUT_CP = 'uniform_withoutCP'
NORMAL_WITHOUT_CP = 'normal_withoutCP'
NORMAL_ADDITIVE = 'normal_additive'
NORMAL_FITTED = 'normal_fitted'
IDENTITY = 'identity'
MEAN = 'mean'
MEDIAN = 'median'
|
def which_algorithm(config: N2VConfig):
'\n Checks which algorithm the model is configured for (N2V, N2V2, structN2V).\n '
if (config.structN2Vmask is not None):
return Algorithm.StructN2V
elif ((config.n2v_manipulator == PixelManipulator.MEDIAN.value) and (not config.unet_residual) and conf... |
def generate_bioimage_md(name: str, cite: list, path: Path):
'\n Generate a generic document.md file for the bioimage.io format.\n '
file = (path / 'napari-n2v.md')
with open(file, 'w') as f:
text = cite[0]['text']
content = f'''## {name}
This network was trained using [napari-n2v](h... |
def get_algorithm_details(algorithm: Algorithm):
'\n Returns name, authors and citation related to the algorithm, formatted as expected by bioimage.io\n model builder.\n '
if (algorithm == Algorithm.StructN2V):
citation = [{'text': 'C. Broaddus, A. Krull, M. Weigert, U. Schmidt and G. Myers, ... |
def build_modelzoo(result_path: Union[(str, Path)], weights_path: Union[(str, Path)], bundle_path: Union[(str, Path)], inputs: str, outputs: str, preprocessing: list, postprocessing: list, doc: Union[(str, Path)], name: str, authors: list, algorithm: Algorithm, tf_version: str, cite: List[Dict], axes: str='byxc', fil... |
def save_model_tf(model, config, model_path, config_path):
model_folder_path = (model_path.parent / model_path.stem)
tf.keras.models.save_model(model, model_folder_path, save_format=Format.TF.value, include_optimizer=False)
save_json(vars(config), config_path)
final_archive = model_path.absolute()
... |
def get_subpatch(patch, coord, local_sub_patch_radius, crop_patch=True):
(crop_neg, crop_pos) = (0, 0)
if crop_patch:
start = (np.array(coord) - local_sub_patch_radius)
end = ((start + (local_sub_patch_radius * 2)) + 1)
crop_neg = np.minimum(start, 0)
crop_pos = np.maximum(0, (... |
def random_neighbor(shape, coord):
rand_coords = sample_coords(shape, coord)
while np.any((rand_coords == coord)):
rand_coords = sample_coords(shape, coord)
return rand_coords
|
def sample_coords(shape, coord, sigma=4):
return [normal_int(c, sigma, s) for (c, s) in zip(coord, shape)]
|
def normal_int(mean, sigma, w):
return int(np.clip(np.round(np.random.normal(mean, sigma)), 0, (w - 1)))
|
def mask_center(local_sub_patch_radius, ndims=2):
size = ((local_sub_patch_radius * 2) + 1)
patch_wo_center = np.ones(((size,) * ndims))
if (ndims == 2):
patch_wo_center[(local_sub_patch_radius, local_sub_patch_radius)] = 0
elif (ndims == 3):
patch_wo_center[(local_sub_patch_radius, lo... |
def pm_normal_withoutCP(local_sub_patch_radius):
def normal_withoutCP(patch, coords, dims, structN2Vmask=None):
vals = []
for coord in zip(*coords):
rand_coords = random_neighbor(patch.shape, coord)
vals.append(patch[tuple(rand_coords)])
return vals
return norm... |
def pm_mean(local_sub_patch_radius):
def patch_mean(patch, coords, dims, structN2Vmask=None):
patch_wo_center = mask_center(local_sub_patch_radius, ndims=dims)
vals = []
for coord in zip(*coords):
(sub_patch, crop_neg, crop_pos) = get_subpatch(patch, coord, local_sub_patch_rad... |
def pm_median(local_sub_patch_radius):
def patch_median(patch, coords, dims, structN2Vmask=None):
patch_wo_center = mask_center(local_sub_patch_radius, ndims=dims)
vals = []
for coord in zip(*coords):
(sub_patch, crop_neg, crop_pos) = get_subpatch(patch, coord, local_sub_patch... |
def pm_uniform_withCP(local_sub_patch_radius):
def random_neighbor_withCP_uniform(patch, coords, dims, structN2Vmask=None):
vals = []
for coord in zip(*coords):
(sub_patch, _, _) = get_subpatch(patch, coord, local_sub_patch_radius)
rand_coords = [np.random.randint(0, s) fo... |
def pm_uniform_withoutCP(local_sub_patch_radius):
def random_neighbor_withoutCP_uniform(patch, coords, dims, structN2Vmask=None):
patch_wo_center = mask_center(local_sub_patch_radius, ndims=dims)
vals = []
for coord in zip(*coords):
(sub_patch, crop_neg, crop_pos) = get_subpat... |
def pm_normal_additive(pixel_gauss_sigma):
def pixel_gauss(patch, coords, dims, structN2Vmask=None):
vals = []
for coord in zip(*coords):
vals.append(np.random.normal(patch[tuple(coord)], pixel_gauss_sigma))
return vals
return pixel_gauss
|
def pm_normal_fitted(local_sub_patch_radius):
def local_gaussian(patch, coords, dims, structN2Vmask=None):
vals = []
for coord in zip(*coords):
(sub_patch, _, _) = get_subpatch(patch, coord, local_sub_patch_radius)
axis = tuple(range(dims))
vals.append(np.rando... |
def pm_identity(local_sub_patch_radius):
def identity(patch, coords, dims, structN2Vmask=None):
vals = []
for coord in zip(*coords):
vals.append(patch[coord])
return vals
return identity
|
def manipulate_val_data(X_val, Y_val, perc_pix=0.198, shape=(64, 64), value_manipulation=pm_uniform_withCP(5)):
dims = len(shape)
if (dims == 2):
box_size = np.round(np.sqrt((100 / perc_pix))).astype(np.int32)
get_stratified_coords = dw.__get_stratified_coords2D__
rand_float = dw.__ran... |
def autocorrelation(x):
'\n nD autocorrelation\n remove mean per-patch (not global GT)\n normalize stddev to 1\n value at zero shift normalized to 1...\n '
x = ((x - np.mean(x)) / np.std(x))
x = np.fft.fftn(x)
x = (np.abs(x) ** 2)
x = np.fft.ifftn(x).real
x = (x / x.flat[0])
... |
def tta_forward(x):
'\n Augments x 8-fold: all 90 deg rotations plus lr flip of the four rotated versions.\n\n Parameters\n ----------\n x: data to augment\n\n Returns\n -------\n Stack of augmented x.\n '
x_aug = [x, np.rot90(x, 1), np.rot90(x, 2), np.rot90(x, 3)]
x_aug_flip = x_a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.