Commit c2c9d7ae authored by Jirka's avatar Jirka

disc segm

parent c5746c43
"""
run experiments with Stat-of-the-art methods
Example run:
"""
# to suppress all visu, has to be on the beginning
# import matplotlib
# matplotlib.use('Agg')
import os
import glob
import time
import numpy as np
import pandas as pd
from skimage import io
from skimage import morphology as morph
from scipy import ndimage
import matplotlib.pyplot as plt
import multiprocessing as mproc
import logging
import src.segmentation.pipelines as segm
logger = logging.getLogger(__name__)
jirka = True
if jirka:
PATH_DATA = '/home/jirka/TEMP/APD_real_data'
PATH_OUTPUT = '/home/jirka/TEMP/APD_real_data'
else:
PATH_DATA = '/datagrid/Medical/microscopy/drosophila/real_segmentations'
PATH_OUTPUT = '/datagrid/temporary/Medical'
DEFAULT_NB_THREADS = int(mproc.cpu_count() * .8)
PATH_INPUT_IMAGES = os.path.join(PATH_DATA, 'original')
PATH_OUTPUT_RESULTS = os.path.join(PATH_OUTPUT, 'segmentation')
DEFAULT_PARAMS = {
'computer': os.uname(),
'name': 'name',
'sp_size': 15,
'sp_regul': 0.01,
'gc_regul': 0.,
'nb_lbs': 3,
# 'fts': {'clr': ['mean', 'std', 'eng']},
'fts': {'clr': ['mean', 'eng']},
'clr': 'rgb'
}
def segments_filled(seg):
# plt.figure()
lb_sum = {}
for i, lb in enumerate(np.unique(seg)):
im = (seg == lb)
im = morph.binary_closing(im, morph.disk(25))
im = ndimage.binary_fill_holes(im)
lb_sum[lb] = np.sum(im)
# plt.subplot(1, 3, i+1), plt.imshow(im)
lbs = sorted(lb_sum, key=lambda x: lb_sum[x], reverse=True)
logger.debug('lb_sum: {}'.format(lb_sum))
# plt.show()
return lbs
def segment_image(params, p_im, p_out):
n_img = os.path.basename(p_im)
img = io.imread(p_im)
logger.debug('image name: {}'.format(n_img))
logger.debug('img values range: {} - {}'.format(np.min(img), np.max(img)))
t = time.time()
seg = segm.pipe_color2d_spx_features_gmm_graphcut(img, nb_cls=params['nb_lbs'],
clr=params['clr'], sp_size=params['sp_size'], sp_reg=params['sp_regul'],
gc_reg=params['gc_regul'], ls_fts=params['fts'])
logger.info('exection time [s]: {}'.format(time.time()-t))
lbs = segments_filled(seg)
seg_sml = (seg == lbs[-1])
# io.imsave(os.path.join(p_out, n_img), np.array(seg, dtype=np.uint8))
io.imsave(os.path.join(p_out, n_img), np.array(seg_sml * 255, dtype=np.uint8))
fig = plt.figure()
plt.subplot(131), plt.imshow(img), plt.axis('off')
plt.subplot(132), plt.imshow(seg), plt.axis('off')
plt.subplot(133), plt.imshow(seg_sml), plt.axis('off')
p_fig = os.path.join(p_out, 'visu_' + n_img)
fig.savefig(p_fig, bbox_inches='tight')
plt.close()
return
def segment_image_folder(p_in=PATH_INPUT_IMAGES, p_out=PATH_OUTPUT_RESULTS,
params=DEFAULT_PARAMS, im_pattern='*.png'):
logger.info('input dir: ({}) <- {}'.format(os.path.exists(p_in), p_in))
logger.info('output dir: ({}) <- {}'.format(os.path.exists(p_out), p_out))
p_imgs = glob.glob(os.path.join(p_in, im_pattern))
logger.info('found {} images'.format(len(p_imgs)))
for p_im in p_imgs:
segment_image(params, p_im, p_out)
return None
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
logger.info('running...')
segment_image_folder()
logger.info('DONE')
# plt.show()
\ No newline at end of file
......@@ -146,6 +146,9 @@ def experiment_pipeline_alpe_showcase(p_out=exp_sta.DEFAULT_PATH_OUTPUT):
class ExperimentALPE(exp_sta.ExperimentAPD):
"""
the main experiment or our Atlas Learning Pattern Encoding
"""
def _init_atlas(self):
""" init atlas according an param
......@@ -189,14 +192,41 @@ class ExperimentALPE(exp_sta.ExperimentAPD):
return atlas, img_rct
def _perform_once(self, v):
""" perform single experiment
:param v: value
:return:
"""
atlas, img_rct = self._estimate_atlas(v)
self._export_atlas(atlas, '_{}_{}'.format(self.iter_n_var, v))
stat = self._compute_statistic_gt(atlas, img_rct)
stat.update({self.iter_n_var: v})
return stat
class ExperimentALPE_mp(ExperimentALPE, exp_sta.ExperimentAPD_mp):
pass
"""
parrallel version of ALPE
"""
pass
def experiments_test():
""" simple test of the experiments
:return:
"""
# experiment_pipeline_alpe_showcase()
params = exp_sta.SYNTH_PARAMS.copy()
params['nb_runs'] = 3
expt = ExperimentALPE(params)
expt.run(n_var='case', v_range=range(params['nb_runs']))
expt_p = ExperimentALPE_mp(params)
expt_p.run(n_var='case', v_range=range(params['nb_runs']))
return
def experiments_synthetic(dataset=None):
......@@ -254,33 +284,15 @@ def experiments_real(dataset=None):
return
def experiments_test():
""" simple test of the experiments
:return:
"""
# experiment_pipeline_alpe_showcase()
params = exp_sta.SYNTH_PARAMS.copy()
params['nb_runs'] = 3
expt = ExperimentALPE(params)
expt.run(n_var='case', v_range=range(params['nb_runs']))
expt_p = ExperimentALPE_mp(params)
expt_p.run(n_var='case', v_range=range(params['nb_runs']))
return
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
logger.info('running...')
# test_encoding(atlas, imgs, encoding)
# test_atlasLearning(atlas, imgs, encoding)
experiments_test()
# experiments_test()
# experiments_synthetic()
experiments_synthetic()
# experiments_real()
# experiments_real('1000_imgs_binary')
......
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment