Commit 6f84e4cb authored by Jiri Borovec's avatar Jiri Borovec

update, refactor, APDL reinit. patterns

parent 8475cb0c
......@@ -147,22 +147,24 @@ def create_clean_folder(path_dir):
return path_dir
def extract_image_largest_element(img):
def extract_image_largest_element(img_binary, labeled=None):
""" take a binary image and find all independent segments,
then keep just the largest segment and rest set as 0
:param img: np.array<w, h> of values {0, 1}
:param img_binary: np.array<w, h> of values {0, 1}
:return: np.array<w, h> of values {0, 1}
"""
labeled, nbObjects = ndimage.label(img)
if labeled is None or len(np.unique(labeled)) < 2:
labeled, _ = ndimage.label(img_binary)
areas = [(j, np.sum(labeled == j)) for j in np.unique(labeled)]
areas = sorted(areas, key=lambda x: x[1], reverse=True)
logger.debug('... elements area: %s', repr(areas))
img_ptn = img_binary.copy()
if len(areas) > 1:
img[:] = 0
img_ptn = np.zeros_like(img_binary)
# skip largest, assuming to be background
img[labeled == areas[1][0]] = 1
return img
img_ptn[labeled == areas[1][0]] = 1
return img_ptn
def atlas_filter_larges_components(atlas):
......
......@@ -17,7 +17,8 @@ import pattern_weights as ptn_weight
import metric_similarity as sim_metric
import dataset_utils as gen_data
DEFAULT_UNARY_BACKGROUND = 1
UNARY_BACKGROUND = 1
NB_GRAPH_CUT_ITER = 5
# TRY: init: spatial clustering
# TRY: init: use ICA
......@@ -79,14 +80,14 @@ def compute_positive_cost_images_weights(imgs, weights):
# per all images in list
for k in range(len(imgs)):
# if pixel is active
if imgs[k][i,j] == 1:
if imgs[k][i, j] == 1:
# increment all possible spots
for x in w_idx[k]:
pott_sum[i, j, x] += 1
# else:
# graphSum[i,j,0] += 1e-9
# set also the background values
pott_sum[i,j,0] = DEFAULT_UNARY_BACKGROUND
pott_sum[i, j, 0] = UNARY_BACKGROUND
# graph = 1. / (graphSum +1)
return pott_sum
......@@ -100,8 +101,8 @@ def edges_in_image_plane(im_size):
idxs = np.arange(np.product(im_size))
idxs = idxs.reshape(im_size)
# logging.debug(idxs)
eA = idxs[:,:-1].ravel().tolist() + idxs[:-1,:].ravel().tolist()
eB = idxs[:, 1:].ravel().tolist() + idxs[1:,:].ravel().tolist()
eA = idxs[:, :-1].ravel().tolist() + idxs[:-1, :].ravel().tolist()
eB = idxs[:, 1:].ravel().tolist() + idxs[1:, :].ravel().tolist()
edges = np.array([eA, eB]).transpose()
logging.debug('edges for image plane are shape {}'.format(edges.shape))
return edges
......@@ -136,7 +137,7 @@ def estimate_atlas_graphcut_simple(imgs, encoding, coef=1.):
return labels
def estimate_atlas_graphcut_general(imgs, encoding, coef=1., init_labels=None):
def estimate_atlas_graphcut_general(imgs, encoding, coef=0., init_atlas=None):
""" run the graphcut on the unary costs with specific pairwise cost
source: https://github.com/yujiali/pygco
......@@ -168,15 +169,16 @@ def estimate_atlas_graphcut_general(imgs, encoding, coef=1., init_labels=None):
pairwise_cost = np.array(pairwise , dtype=np.float64)
logging.debug('graph pairwise coefs %s', repr(pairwise_cost.shape))
if init_labels is None:
if init_atlas is None:
init_labels = np.argmin(unary_cost, axis=1)
else:
init_labels = init_labels.ravel()
init_labels = init_atlas.ravel()
logging.debug('graph initial labels %s', repr(init_labels.shape))
# run GraphCut
labels = cut_general_graph(edges, edge_weights, unary_cost, pairwise_cost,
algorithm='expansion', init_labels=init_labels)
algorithm='expansion', init_labels=init_labels,
n_iter=NB_GRAPH_CUT_ITER)
# reshape labels
labels = labels.reshape(u_cost.shape[:2])
logging.debug('resulting labelling %s of %s', repr(labels.shape),
......@@ -184,12 +186,12 @@ def estimate_atlas_graphcut_general(imgs, encoding, coef=1., init_labels=None):
return labels
def export_visualization_image(img, i, out_dir, prefix='debug', name='',
def export_visualization_image(img, idx, out_dir, prefix='debug', name='',
ration=None, labels=('', '')):
""" export visualisation as an image with some special desc.
:param img: np.array<w, h>
:param i: int, iteration to be shown in the img name
:param idx: int, iteration to be shown in the img name
:param out_dir: str, path to the resulting folder
:param prefix: str
:param name: str, name of this particular visual
......@@ -200,7 +202,7 @@ def export_visualization_image(img, i, out_dir, prefix='debug', name='',
plt.imshow(img, interpolation='none', aspect=ration)
plt.xlabel(labels[0])
plt.ylabel(labels[1])
n_fig = 'APDL_{}_{}_iter_{:04d}'.format(prefix, name, i)
n_fig = 'APDL_{}_{}_iter_{:04d}'.format(prefix, name, idx)
p_fig = os.path.join(out_dir, n_fig + '.png')
logging.debug('.. export Visualization as "%s...%s"', p_fig[:19], p_fig[-19:])
fig.savefig(p_fig, bbox_inches='tight', pad_inches=0.05)
......@@ -230,7 +232,7 @@ def export_visual_atlas(i, out_dir, atlas=None, prefix='debug'):
# 'auto', ['patterns', 'images'])
def alpe_initialisation(imgs, init_atlas, init_weights, out_dir, out_prefix):
def apdl_initialisation(imgs, init_atlas, init_weights, out_dir, out_prefix):
""" more complex initialisation depending on inputs
:param imgs: [np.array<w, h>]
......@@ -254,13 +256,13 @@ def alpe_initialisation(imgs, init_atlas, init_weights, out_dir, out_prefix):
atlas = init_atlas
w_bins = init_weights
if len(np.unique(atlas)) == 1:
logging.warning('the atlas does not contain any label... %s',
repr(np.unique(atlas)))
logging.error('the init. atlas does not contain any label... %s',
repr(np.unique(atlas)))
export_visual_atlas(0, out_dir, atlas, out_prefix)
return atlas, w_bins
def alpe_update_weights(imgs, atlas, overlap_major=False):
def apdl_update_weights(imgs, atlas, overlap_major=False):
""" single iteration of the block coordinate descent algo
:param imgs: [np.array<w, h>]
......@@ -268,7 +270,7 @@ def alpe_update_weights(imgs, atlas, overlap_major=False):
:return: np.array<nb_imgs, nb_lbs>
"""
# update w_bins
logging.debug('... perform pattern Weights')
logging.debug('... perform pattern weights')
if overlap_major:
w_bins = [ptn_weight.weights_image_atlas_overlap_major(img, atlas)
for img in imgs]
......@@ -280,22 +282,7 @@ def alpe_update_weights(imgs, atlas, overlap_major=False):
return np.array(w_bins)
def alpe_repaire_atlas_weights(imgs, atlas, w_bins, label_max):
"""
:param imgs: [np.array<w, h>]
:param atlas: np.array<w, h>
:param w_bins: np.array<nb_imgs, nb_lbs>
:return: np.array<w, h>, np.array<nb_imgs, nb_lbs>
"""
logging.debug('... perform repairing atlas & weights')
# reinit empty
atlas, w_bins = ptn_dict.reinit_atlas_likely_patterns(imgs, w_bins, atlas,
label_max)
return atlas, w_bins
def alpe_update_atlas(imgs, atlas, w_bins, label_max, gc_coef, gc_reinit, ptn_split):
def apdl_update_atlas(imgs, atlas, w_bins, label_max, gc_coef, gc_reinit, ptn_split):
""" single iteration of the block coordinate descent algo
:param imgs: [np.array<w, h>]
......@@ -322,10 +309,10 @@ def alpe_update_atlas(imgs, atlas, w_bins, label_max, gc_coef, gc_reinit, ptn_sp
return atlas_new
def alpe_pipe_atlas_learning_ptn_weights(imgs, init_atlas=None, init_weights=None,
gc_coef=0.0, tol=1e-4, max_iter=25,
def apdl_pipe_atlas_learning_ptn_weights(imgs, init_atlas=None, init_weights=None,
gc_coef=0.0, tol=1e-3, max_iter=25,
gc_reinit=True, ptn_split=True,
overlap_major=False,
overlap_major=False, ptn_compact=True,
out_prefix='debug', out_dir=''):
""" the experiments_synthetic pipeline for block coordinate descent
algo with graphcut...
......@@ -349,40 +336,38 @@ def alpe_pipe_atlas_learning_ptn_weights(imgs, init_atlas=None, init_weights=Non
os.mkdir(out_dir)
# assert initAtlas is not None or type(max_nb_lbs)==int
# initialise
atlas, w_bins = alpe_initialisation(imgs, init_atlas, init_weights,
label_max = np.max(init_atlas)
logging.debug('max nb labels set: %i', label_max)
atlas, w_bins = apdl_initialisation(imgs, init_atlas, init_weights,
out_dir, out_prefix)
label_max = np.max(atlas)
list_crit = []
for i in range(max_iter):
for iter in range(max_iter):
if len(np.unique(atlas)) == 1:
logging.warning('the atlas does not contain any label... %i',
np.unique(atlas)[0])
w_bins = alpe_update_weights(imgs, atlas, overlap_major)
# plt.subplot(221), plt.imshow(atlas, interpolation='nearest')
# plt.subplot(222), plt.imshow(w_bins, aspect='auto')
atlas_new, w_bins = alpe_repaire_atlas_weights(imgs, atlas, w_bins, label_max)
# plt.subplot(223), plt.imshow(atlas, interpolation='nearest')
# plt.subplot(224), plt.imshow(w_bins, aspect='auto')
# plt.show()
atlas_new = alpe_update_atlas(imgs, atlas_new, w_bins, label_max,
logging.warning('.. iter: %i, no labels in the atlas %s', iter,
repr(np.unique(atlas).tolist()))
w_bins = apdl_update_weights(imgs, atlas, overlap_major)
atlas_reinit, w_bins = ptn_dict.reinit_atlas_likely_patterns(imgs,
w_bins, atlas, label_max, ptn_compact)
atlas_new = apdl_update_atlas(imgs, atlas_reinit, w_bins, label_max,
gc_coef, gc_reinit, ptn_split)
step_diff = sim_metric.compare_atlas_adjusted_rand(atlas, atlas_new)
# step_diff = np.sum(abs(atlas - atlas_new)) / float(np.product(atlas.shape))
list_crit.append(step_diff)
atlas = atlas_new
atlas = sk_image.relabel_sequential(atlas_new)[0]
logging.debug('-> iter. #%i with Atlas diff %f', (i + 1), step_diff)
export_visual_atlas(i + 1, out_dir, atlas, out_prefix)
logging.debug('-> iter. #%i with Atlas diff %f', (iter + 1), step_diff)
export_visual_atlas(iter + 1, out_dir, atlas, out_prefix)
# stopping criterion
if step_diff <= tol:
if step_diff <= tol and len(np.unique(atlas)) > 1:
logging.debug('>> exit while the atlas diff %f is smaller then %f',
step_diff, tol)
break
logging.info('...terminated with %i / %i iter and step diff %f <? %f',
i, max_iter, step_diff, tol)
logging.info('APDL: terminated with iter %i / %i and step diff %f <? %f',
iter, max_iter, step_diff, tol)
logging.debug('criterion evolved:\n %s', repr(list_crit))
atlas = sk_image.relabel_sequential(atlas)[0]
# atlas = sk_image.relabel_sequential(atlas)[0]
w_bins = [ptn_weight.weights_image_atlas_overlap_major(img, atlas) for img in imgs]
return atlas, np.array(w_bins)
......@@ -51,13 +51,15 @@ PATH_RESULTS = '/datagrid/Medical/microscopy/drosophila/TEMPORARY/experiments_AP
DEFAULT_PARAMS = {
'computer': os.uname(),
'nb_samples': None,
'init_tp': 'msc1', # msc. rnd
'tol': 1e-2,
'init_tp': 'msc2', # msc. rnd
'max_iter': 250,
'gc_regul': 0.,
'nb_labels': 20,
'nb_labels': 2,
'nb_runs': NB_THREADS, # 500
'gc_reinit': True,
'ptn_split': True,
'ptn_split': False,
'ptn_compact': False,
'overlap_mj': False,
}
......@@ -77,7 +79,7 @@ SYNTH_PTN_RANGE = {
'atomicPatternDictionary_00': range(5),
'atomicPatternDictionary_v0': range(3, 15, 1),
'atomicPatternDictionary_v1': range(5, 20, 1),
'atomicPatternDictionary_v2': range(9, 40, 2),
'atomicPatternDictionary_v2': range(10, 40, 2) + [23],
'atomicPatternDictionary_v3': range(10, 40, 2),
'atomicPatternDictionary3D_v0': range(2, 14, 1),
'atomicPatternDictionary3D_v1': range(6, 30, 2),
......@@ -383,6 +385,7 @@ class ExperimentAPD_parallel(ExperimentAPD):
mproc_pool = mproc.Pool(self.nb_jobs)
for stat in mproc_pool.map(self._warp_perform_once, self.iter_values):
self.l_stat.append(stat)
self._evaluate()
# tqdm_bar.update(1)
mproc_pool.close()
mproc_pool.join()
......
......@@ -7,28 +7,35 @@ Copyright (C) 2015-2016 Jiri Borovec <jiri.borovec@fel.cvut.cz>
import logging
from scipy import ndimage
from skimage import morphology
from skimage import morphology, feature
from scipy import ndimage as ndi
import numpy as np
import dataset_utils as data
import pattern_weights as ptn_weight
REINIT_PATTERN_COMPACT = True
def initialise_atlas_random(im_size, max_lb):
# TODO: init: Otsu threshold on sum over all input images -> WaterShade on distance
# TODO: init: sum over all input images and use it negative as distance for WaterShade
def initialise_atlas_random(im_size, label_max):
""" initialise atlas with random labels
:param im_size: (w, h) size og image
:param max_lb: int, number of labels
:param label_max: int, number of labels
:return: np.array<w, h>
"""
logging.debug('initialise atlas %s as random labeling', repr(im_size))
nb_lbs = max_lb + 1
nb_lbs = label_max + 1
np.random.seed() # reinit seed to have random samples even in the same time
im = np.random.randint(1, nb_lbs, im_size)
return np.array(im, dtype=np.int)
def initialise_atlas_mosaic(im_size, max_lb, coef=1.):
def initialise_atlas_mosaic(im_size, nb_labels, coef=1.):
""" generate grids trusture and into each rectangle plase a label,
each row contains all labels (permutation)
......@@ -37,24 +44,26 @@ def initialise_atlas_mosaic(im_size, max_lb, coef=1.):
:return: np.array<w, h>
"""
logging.debug('initialise atlas %s as grid labeling', repr(im_size))
nb_lbs = int(max_lb * coef)
nb_labels = int(nb_labels * coef)
np.random.seed() # reinit seed to have random samples even in the same time
block = np.ones(np.ceil(im_size / np.array(nb_lbs, dtype=np.float)))
vec = range(1, nb_lbs + 1) * int(np.ceil(coef))
block_size = np.ceil(np.array(im_size) / float(nb_labels))
block = np.ones(block_size.astype(np.int))
vec = range(1, nb_labels + 1) * int(np.ceil(coef))
logging.debug('block size is %s', repr(block.shape))
for l in range(nb_lbs):
idx = np.random.permutation(vec)[:nb_lbs]
for k in range(nb_lbs):
for label in range(nb_labels):
idx = np.random.permutation(vec)[:nb_labels]
for k in range(nb_labels):
b = block.copy() * idx[k]
if k == 0:
row = b
else:
row = np.hstack((row, b))
if l == 0: mosaic = row
if label == 0: mosaic = row
else: mosaic = np.vstack((mosaic, row))
logging.debug('generated mosaic %s with labeling %s',
repr(mosaic.shape), repr(np.unique(mosaic).tolist()))
im = mosaic[:im_size[0], :im_size[1]]
im = np.remainder(im, nb_labels)
return np.array(im, dtype=np.int)
......@@ -86,65 +95,64 @@ def reconstruct_samples(atlas, w_bins):
return imgs
def prototype_new_pattern(imgs, imgs_rc, diffs, atlas):
def prototype_new_pattern(imgs, imgs_reconst, diffs, atlas,
ptn_compact=REINIT_PATTERN_COMPACT):
""" estimate new pattern that occurs in input images and is not cover
by any label in actual atlas, remove collision with actual atlas
:param imgs: [np.array<w, h>] list of input images
:param imgs_rc: [np.array<w, h>] list of image reconstructions
:param imgs_reconst: [np.array<w, h>] list of image reconstructions
:param diffs: [int] list of differences among input and reconstruct images
:param atlas: np.array<w, h> m-label atlas for further collision removing
:return: np.array<w, h> binary single pattern
"""
id_max = np.argmax(diffs)
im_diff = (imgs[id_max] - imgs_rc[id_max])
# im_diff = np.logical_and(imgs[id_max] == True, imgs_reconst[id_max] == False)
# take just positive differences
im_diff = im_diff > 0
im_diff = morphology.closing(im_diff, morphology.disk(1))
# find largesr connected component
ptn = data.extract_image_largest_element(im_diff)
atlas_diff = np.logical_and(ptn == True, atlas == 0)
ptn_res = atlas_diff > 0
# plt.figure()
# plt.subplot(231), plt.imshow(im_diff), plt.colorbar()
# plt.title('im_diff {}'.format(np.unique(im_diff)))
# plt.subplot(232), plt.imshow(ptn), plt.colorbar()
# plt.title('ptn {}'.format(np.unique(ptn)))
# plt.subplot(233), plt.imshow(atlas), plt.colorbar()
# plt.title('atlas {}'.format(np.unique(atlas)))
# plt.subplot(234), plt.imshow((atlas > 0)), plt.colorbar()
# plt.title('atlas {}'.format(np.unique((atlas > 0))))
# plt.subplot(235), plt.imshow(atlas_diff), plt.colorbar()
# plt.title('atlas_diff {}'.format(np.unique(atlas_diff)))
# plt.subplot(236), plt.imshow(ptn_res), plt.colorbar()
# plt.title('ptn_res {}'.format(np.unique(ptn_res)))
# plt.show()
return ptn_res
def insert_new_pattern(imgs, imgs_rc, atlas, lb):
im_diff = (imgs[id_max] - imgs_reconst[id_max]) > 0
if ptn_compact: # WaterShade
logging.debug('.. reinit pattern using WaterShade')
# im_diff = morphology.opening(im_diff, morphology.disk(3))
# http://scikit-image.org/docs/dev/auto_examples/plot_watershed.html
dist = ndi.distance_transform_edt(im_diff)
local_maxi = feature.peak_local_max(dist, indices=False, labels=im_diff,
footprint=np.ones((3, 3)))
labels = morphology.watershed(-dist, ndi.label(local_maxi)[0], mask=im_diff)
else:
logging.debug('.. reinit pattern as major component')
im_diff = morphology.closing(im_diff, morphology.disk(1))
labels = None
# find largest connected component
img_ptn = data.extract_image_largest_element(im_diff, labels)
# ptn_size = np.sum(ptn) / float(np.product(ptn.shape))
# if ptn_size < 0.01:
# logging.debug('new patterns was too small %f', ptn_size)
# ptn = data.extract_image_largest_element(im_diff)
img_ptn = np.logical_and(img_ptn == True, atlas == 0)
return img_ptn
def insert_new_pattern(imgs, imgs_reconst, atlas, label,
ptn_compact=REINIT_PATTERN_COMPACT):
""" with respect to atlas empty spots inset new patterns
:param imgs: [np.array<w, h>] list of input images
:param imgs_rc: [np.array<w, h>]
:param imgs_reconst: [np.array<w, h>]
:param atlas: np.array<w, h>
:param lb: int
:param label: int
:return: np.array<w, h> updated atlas
"""
diffs = []
# count just positive difference
for im, im_rc in zip(imgs, imgs_rc):
diff = np.sum((im - im_rc) > 0)
diffs.append(diff)
im_ptn = prototype_new_pattern(imgs, imgs_rc, diffs, atlas)
diffs = [np.sum((im - im_rc) > 0) for im, im_rc in zip(imgs, imgs_reconst)]
im_ptn = prototype_new_pattern(imgs, imgs_reconst, diffs, atlas, ptn_compact)
# logging.debug('new im_ptn: {}'.format(np.sum(im_ptn) / np.prod(im_ptn.shape)))
# plt.imshow(im_ptn), plt.title('im_ptn'), plt.show()
atlas[im_ptn == True] = lb
logging.debug('area of new pattern is %i', np.sum(atlas == lb))
atlas[im_ptn == True] = label
logging.debug('area of new pattern %i is %i', im_ptn, np.sum(atlas == label))
return atlas
def reinit_atlas_likely_patterns(imgs, w_bins, atlas, label_max=None):
def reinit_atlas_likely_patterns(imgs, w_bins, atlas, label_max=None,
ptn_compact=REINIT_PATTERN_COMPACT):
""" walk and find all all free labels and try to reinit them by new patterns
:param label_max:
......@@ -161,49 +169,50 @@ def reinit_atlas_likely_patterns(imgs, w_bins, atlas, label_max=None):
for i in range(w_bins.shape[1], label_max):
logging.debug('adding disappeared weigh column %i', i)
w_bins = np.append(w_bins, np.zeros((w_bins.shape[0], 1)), axis=1)
w_bin_ext = np.append(np.zeros((w_bins.shape[0], 1)), w_bins, axis=1)
logging.debug('IN > sum over weights: %s', repr(np.sum(w_bin_ext, axis=0)))
# w_bin_ext = np.append(np.zeros((w_bins.shape[0], 1)), w_bins, axis=1)
# logging.debug('IN > sum over weights: %s', repr(np.sum(w_bin_ext, axis=0)))
# add one while indexes does not cover 0 - bg
logging.debug('total nb labels: %i', label_max)
atlas_new = atlas.copy()
for lb in range(1, label_max + 1):
w_index = lb - 1
for label in range(1, label_max + 1):
w_index = label - 1
w_sum = np.sum(w_bins[:, w_index])
# logging.debug('reinit lb: %i with weight sum %i', lb, w_sum)
logging.debug('reinit. label: %i with weight sum %i', label, w_sum)
if w_sum > 0:
continue
imgs_rc = reconstruct_samples(atlas_new, w_bins)
atlas_new = insert_new_pattern(imgs, imgs_rc, atlas_new, lb)
imgs_reconst = reconstruct_samples(atlas_new, w_bins)
atlas_new = insert_new_pattern(imgs, imgs_reconst, atlas_new, label,
ptn_compact)
# logging.debug('w_bins before: %i', np.sum(w_bins[:, w_index]))
lim_repopulate = 100. / np.prod(atlas_new.shape)
w_bins[:, w_index] = ptn_weight.weights_label_atlas_overlap_threshold(imgs,
atlas_new, lb, lim_repopulate)
w_bins[:, w_index] = ptn_weight.weights_label_atlas_overlap_threshold(
imgs, atlas_new, label, lim_repopulate)
logging.debug('w_bins after: %i', np.sum(w_bins[:, w_index]))
return atlas_new, w_bins
def atlas_split_indep_ptn(atlas, lb_max):
def atlas_split_indep_ptn(atlas, label_max):
""" split independent patterns labeled equally
:param atlas: np.array<w, h>
:param lb_max: int
:param label_max: int
:return:
"""
patterns = []
for lb in np.unique(atlas):
labeled, nb_objects = ndimage.label(atlas == lb)
logging.debug('for label %i detected #%i', lb, nb_objects)
for label in np.unique(atlas):
labeled, nb_objects = ndimage.label(atlas == label)
logging.debug('for label %i detected #%i', label, nb_objects)
ptn = [(labeled == j) for j in np.unique(labeled)]
# skip the largest one assuming to be background
patterns += sorted(ptn, key=lambda x: np.sum(x), reverse=True)[1:]
patterns = sorted(patterns, key=lambda x: np.sum(x), reverse=True)
logging.debug('list of all areas %s', repr([np.sum(p) for p in patterns]))
atlas_new = np.zeros(atlas.shape, dtype=np.int)
# take just lb_max largest elements
for i, ptn in enumerate(patterns[:lb_max]):
lb = i + 1
# take just label_max largest elements
for i, ptn in enumerate(patterns[:label_max]):
label = i + 1
# logging.debug('pattern #%i area %i', lb, np.sum(ptn))
atlas_new[ptn] = lb
atlas_new[ptn] = label
# plt.figure()
# plt.subplot(121), plt.imshow(atlas), plt.colorbar()
......
......@@ -8,19 +8,19 @@ import logging
import numpy as np
def initialise_weights_random(nb_imgs, nb_lbs, ratio_sel=0.2):
def initialise_weights_random(nb_imgs, nb_labels, ratio_select=0.2):
"""
:param nb_imgs: int, numer of all images
:param nb_lbs: int, numer of all avalaible labels
:param ratio_sel: float<0, 1> defining how many should be set on,
:param nb_labels: int, numer of all avalaible labels
:param ratio_select: float<0, 1> defining how many should be set on,
1 means all and 0 means none
:return: np.array<nb_imgs, nb_lbs>
:return: np.array<nb_imgs, nb_labels>
"""
logging.debug('initialise weights for %i images and %i labels '
'as random selection', nb_imgs, nb_lbs)
prob = np.random.random((nb_imgs, nb_lbs))
'as random selection', nb_imgs, nb_labels)
prob = np.random.random((nb_imgs, nb_labels))
weights = np.zeros_like(prob)
weights[prob <= ratio_sel] = 1
weights[prob <= ratio_select] = 1
return weights
......@@ -68,13 +68,13 @@ def weights_image_atlas_overlap_partial(img, atlas):
return weights
def weights_image_atlas_overlap_threshold(img, atlas, thr=0.5):
def weights_image_atlas_overlap_threshold(img, atlas, threshold=0.5):
""" estimate what patterns are activated with given atlas and input image
compute overlap matrix and eval nr of overlapping and non pixels and threshold
:param img: np.array<w, h>
:param atlas: np.array<w, h>
:param thr: float, represent the ration between overlapping and non pixels
:param threshold: float, represent the ration between overlapping and non pixels
:return: [int] * nb_lbs of values {0, 1}
"""
# logging.debug('weights input image according given atlas')
......@@ -88,7 +88,7 @@ def weights_image_atlas_overlap_threshold(img, atlas, thr=0.5):
equal = np.sum(img[atlas == lb])
total = np.sum(atlas == lb)
score = equal / float(total)
if score >= thr:
if score >= threshold:
weight[lb - 1] = 1
return weight
......
......@@ -35,8 +35,10 @@ import dataset_utils as gen_data
VISUAL = False
NB_THREADS = int(mproc.cpu_count() * .9)
PATH_EXPERIMENTS = '/datagrid/Medical/microscopy/drosophila/' \
'TEMPORARY/experiments_APDL_real'
# PATH_EXPERIMENTS = '/datagrid/Medical/microscopy/drosophila/RESULTS/' \
# 'experiments_APD_real'
PATH_EXPERIMENTS = '/datagrid/Medical/microscopy/drosophila/TEMPORARY/' \
'experiments_APD_real'
DICT_PARAMS = {
'path_in': PATH_EXPERIMENTS,
......@@ -103,19 +105,26 @@ def export_fig_reconstruction(path_out, name, segm_orig, segm_reconst, img_atlas
"""
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(20, 8))
ax[0].set_title('original segmentation')
ax[0].imshow(1 - segm_orig, cmap='Greys'), ax[0].axis('off')
ax[0].imshow(1 - segm_orig, cmap='Greys', alpha=0.9)
ax[0].imshow(segm_reconst, alpha=0.1)
ax[0].axis('off')
ax[0].contour(segm_reconst > 0, linewidth=2)
ax[0].contour(segm_reconst, linewidth=2, cmap=plt.cm.jet)
ax[1].set_title('reconstructed segmentation')