def morph_snakes(data, mask, slice=None, scale=0.5, alpha=1000, sigma=1, smoothing_ls=1, threshold=0.3, balloon=1, max_iters=50, show=False, show_now=True): data_o = data.copy() mask_o = mask.copy() if scale != 1: # data = skitra.rescale(data, scale=scale, preserve_range=True).astype(np.uint8) # mask = skitra.rescale(mask, scale=scale, preserve_range=True).astype(np.bool) data = tools.resize3D(data, scale, sliceId=0) mask = tools.resize3D(mask, scale, sliceId=0) gI = morphsnakes.gborders(data, alpha=alpha, sigma=sigma) # Morphological GAC. Initialization of the level-set. mgac = morphsnakes.MorphGAC(gI, smoothing=smoothing_ls, threshold=threshold, balloon=balloon) mgac.levelset = mask mgac.run(iterations=max_iters) seg = mgac.levelset if scale != 1: # data = tools.resize_ND(data, shape=orig_shape) # mask = tools.resize_ND(mask, shape=orig_shape) seg = tools.resize_ND(seg, shape=data_o.shape) if show: tools.visualize_seg(data_o, seg, mask_o, slice=slice, title='morph snakes', show_now=show_now) return data, mask, seg
def lankton_ls(im, mask, method='sfm', slice=None, max_iters=1000, rad=10, alpha=0.1, scale=1., show=False, show_now=True): if scale != 1: # im = skitra.rescale(im, scale=scale, preserve_range=True).astype(np.uint8) # mask = skitra.rescale(mask, scale=scale, preserve_range=True).astype(np.bool) im = tools.resize_ND(im, scale=scale).astype(np.uint8) mask = tools.resize_ND(mask, scale=scale).astype(np.bool) seg = lankton_lls.run( im, mask, method='sfm', max_iter=1000, rad=rad, alpha=alpha, # slice=slice, show=show, show_now=show_now) slice=slice, show=True, show_now=True) if show: tools.visualize_seg(data, mask, seg, slice=slice, title='morph snakes', show_now=show_now) return im, mask, seg
min_diff = 1 alpha = 0.9 scale = 0.5 max_iters = 100 smoothing = True show = True show_now = False _, seeds = tools.initialize_graycom(data, slice=slice_ind, show=show, show_now=show_now) # seeds = tools.eroding3D(seeds, np.ones((3, 3))).astype(np.uint8) seeds = tools.morph_ND(seeds, 'erosion', selem=np.ones((3, 3)), slicewise=True, sliceId=0).astype(np.uint8) plt.figure() plt.subplot(121), plt.imshow(data[slice_ind,...], 'gray') plt.subplot(122), plt.imshow(seeds[slice_ind,...], 'jet') plt.show() lrg = LoReGro(data, seeds, ball_r_out=ball_r_out, ball_r=ball_r, min_diff=min_diff, alpha=alpha, scale=scale, max_iters=max_iters, smoothing=smoothing, show=show, show_now=show_now) lrg.run_segmentation() seg = lrg.segmentation # plt.figure() # plt.suptitle('LoReGro segmentation') # plt.subplot(131), plt.imshow(data, 'gray'), plt.title('input') # plt.subplot(132), plt.imshow(seeds, 'jet'), plt.title('seeds') # plt.subplot(133), plt.imshow(seg[0,...].astype(np.uint8), 'gray'), plt.title('segmentation') # plt.show() tools.visualize_seg(data, seg[0,...], mask=seeds, title='loregro')
def run_param_tuning_morphsnakes(im_in, gt_mask, slice_ind, smoothing=True, scale=0.5, init_scale=0.5): if smoothing: im_in = tools.smoothing(im_in, sigmaSpace=10, sigmaColor=10, sliceId=0) im = im_in.copy() mask_init = tools.initialize_graycom(im, slice, distances=[ 1, ], scale=init_scale) # parameters tuning --------------------------------------------------------------- alpha_v = (10, 100, 500) sigma_v = (1, 5) threshold_v = (0.1, 0.5, 0.9) balloon_v = (1, 2, 4) method = 'morphsnakes' # create workbook for saving the resulting pracision, recall and f-measure workbook = xlsxwriter.Workbook( '/home/tomas/Dropbox/Data/liver_segmentation/%s/%s.xlsx' % (method, method)) worksheet = workbook.add_worksheet() # Add a bold format to use to highlight cells. bold = workbook.add_format({'bold': True}) # green = workbook.add_format({'bg_color': '#C6EFCE'}) worksheet.write(0, 0, 'F-MEASURE', bold) worksheet.write(0, 1, 'PRECISION', bold) worksheet.write(0, 2, 'RECALL', bold) worksheet.write(0, 4, 'alpha', bold) worksheet.write(0, 5, 'sigma', bold) worksheet.write(0, 6, 'threshold', bold) worksheet.write(0, 7, 'ballon', bold) worksheet.write(0, 8, 'scale', bold) worksheet.write(0, 9, 'scale_init', bold) params_tune = [] for p in itertools.product(alpha_v, sigma_v, threshold_v, balloon_v): params_tune.append(p) # for i, (alpha, sigma, threshold, balloon) in enumerate(itertools.product(alpha_v, sigma_v, threshold_v, balloon_v)): for i in range(len(params_tune)): alpha, sigma, threshold, balloon = params_tune[i] # threshold = 0.9 # balloon = 4 print '\n -- it #%i/%i --' % (i + 1, len(params_tune)) print 'Working with alpha=%i, sigma=%i, threshold=%.1f, balloon=%i' % ( alpha, sigma, threshold, balloon) params = { 'alpha': alpha, 'sigma': sigma, 'smoothing_ls': 1, 'threshold': threshold, 'balloon': balloon, 'max_iters': 1000, 'scale': scale, 'init_scale': init_scale, 'smoothing': False, 'save_fig': False, 'show': True, 'show_now': False } im, mask, seg = run(im_in, slice=slice_ind, mask=mask_init, method=method, **params) # print 'shapes 1: im={}, mask={}, seg={}'.format(im.shape, mask.shape, seg.shape) if im.shape != im_in.shape: im = tools.resize_ND(im, shape=im_in.shape) if mask.shape != gt_mask.shape: mask = tools.resize_ND(mask, shape=gt_mask.shape) if seg.shape != gt_mask.shape: seg = tools.resize_ND(seg, shape=gt_mask.shape) # print 'shapes 2: im={}, mask={}, seg={}'.format(im.shape, mask.shape, seg.shape) # calculating precision, recall and f_measure precision, recall, f_measure = calc_statistics(seg, gt_mask) # print 'shapes 3: im={}, mask={}, seg={}'.format(im.shape, mask.shape, seg.shape) # saving data datap = {'im': im, 'mask': mask, 'seg': seg, 'params': params} dirname = '/home/tomas/Dropbox/Data/liver_segmentation/%s/' % method dataname = '%s_al%i_si%i_th%s_ba%i.pklz' % ( method, alpha, sigma, str(threshold).replace('.', ''), balloon) f = gzip.open(os.path.join(dirname, dataname), 'w') pickle.dump(datap, f) f.close() # saving results cols = [0, 1, 2, 4, 5, 6, 7, 8, 9] items = (f_measure, precision, recall, alpha, sigma, threshold, balloon, params['scale'], params['init_scale']) for j, it in enumerate(items): worksheet.write(i + 1, cols[j], it) # creating visualization fig = tools.visualize_seg(im, seg, mask, slice=slice_ind, title=method, for_save=True, show_now=False) fname = '/home/tomas/Dropbox/Data/liver_segmentation/%s/%s_al%i_si%i_th%s_ba%i.png' \ % (method, method, alpha, sigma, str(threshold).replace('.', ''), balloon) fig.savefig(fname) plt.close('all') workbook.close()
plt.subplot(121), plt.imshow(data[slice_ind, ...], 'gray') plt.subplot(122), plt.imshow(seeds[slice_ind, ...], 'jet') # plt.show() lrg = LoReGro(data, seeds, ball_r_out=ball_r_out, ball_r=ball_r, min_diff=min_diff, alpha=alpha, scale=scale, max_iters=max_iters, smoothing=smoothing, show=show, show_now=show_now) lrg.run_segmentation() seg = lrg.segmentation # plt.figure() # plt.suptitle('LoReGro segmentation') # plt.subplot(131), plt.imshow(data, 'gray'), plt.title('input') # plt.subplot(132), plt.imshow(seeds, 'jet'), plt.title('seeds') # plt.subplot(133), plt.imshow(seg[0,...].astype(np.uint8), 'gray'), plt.title('segmentation') # plt.show() # tools.visualize_seg(data, seg[0,...], mask=seeds, title='loregro') tools.visualize_seg(data, seg, mask=seeds, slice=slice_ind, title='loregro')
def segmentation_stats(data_struc, scale=1, smoothing=True): # fnames = load_data(datadir) # fnames = ['/home/tomas/Dropbox/Data/medical/dataset/180_arterial-.pklz',] # creating workbook workbook = xlsxwriter.Workbook('/home/tomas/Dropbox/Data/liver_segmentation/final_alg/liver_seg_stats.xlsx') worksheet = workbook.add_worksheet() # Add a bold format to use to highlight cells. bold = workbook.add_format({'bold': True}) # green = workbook.add_format({'bg_color': '#C6EFCE'}) col_gc_fmea = 3 col_gc_prec = 6 col_gc_rec = 9 col_ls_fmea = 4 col_ls_prec = 7 col_ls_rec = 10 cols_gc = (3, 6, 9) cols_ls = (4, 7, 10) start_row = 2 worksheet.write(0, 0, 'DATA', bold) worksheet.write(0, 1, 'slice', bold) worksheet.write(0, 3, 'F-MEASURE', bold) worksheet.write(0, 6, 'PRECISION', bold) worksheet.write(0, 9, 'RECALL', bold) worksheet.write(1, col_gc_fmea, 'Grow Cut', bold) worksheet.write(1, col_ls_fmea, 'Level Sets', bold) worksheet.write(1, col_gc_prec, 'Grow Cut', bold) worksheet.write(1, col_ls_prec, 'Level Sets', bold) worksheet.write(1, col_gc_rec, 'Grow Cut', bold) worksheet.write(1, col_ls_rec, 'Level Sets', bold) # loading data data_fnames = [] data_slices = [] for name, num in data_struc: for i in num: data_fnames.append(name) data_slices.append(i) n_imgs = len(data_fnames) for i, (data_fname, slice) in enumerate(zip(data_fnames, data_slices)): fname = data_fname.split('/')[-1].split('.')[0] print '#%i/%i, %s [%i]: ' % (i + 1, n_imgs, fname, slice), data, gt_mask, voxel_size = tools.load_pickle_data(data_fname) data = data[slice,...] gt_mask = gt_mask[slice,...] print 'windowing ...', data = tools.windowing(data) shape_orig = data.shape data_o = data.copy() # plt.figure() # plt.imshow(data, 'gray', vmin=0, vmax=255, interpolation='nearest') # plt.show() if scale != 1: print 'resizing ...', data = tools.resize_ND(data, scale=scale).astype(np.uint8) if smoothing: print 'smoothing ...', data = tools.smoothing(data) print 'gc ...', blob, seg_gc = coarse_segmentation(data, clear_border=False, show=False, verbose=False) print 'ls ...', seg_ls = segmentation_refinement(data, blob, show=False, verbose=False) if seg_gc.shape != gt_mask.shape: seg_gc = tools.resize_ND(seg_gc, shape=shape_orig) if seg_ls.shape != gt_mask.shape: seg_ls = tools.resize_ND(seg_ls, shape=shape_orig) # computing statistics print 'stats ...', precision_gc, recall_gc, f_measure_gc = ac.calc_statistics(blob, gt_mask) precision_ls, recall_ls, f_measure_ls = ac.calc_statistics(seg_ls, gt_mask) # writing statistics print 'writing ...', items = (f_measure_gc, precision_gc, recall_gc, f_measure_ls, precision_ls, recall_ls) worksheet.write(start_row + i, 0, fname) worksheet.write(start_row + i, 1, slice) for it, col in zip(items, cols_gc + cols_ls): worksheet.write(start_row + i, col, it) print 'done' fig = tools.visualize_seg(data_o, seg_ls, mask=seg_gc, title=fname, show_now=False, for_save=True) out_fname = '/home/tomas/Dropbox/Data/liver_segmentation/final_alg/%s_sl_%i.png' % (fname, slice) fig.savefig(out_fname) plt.close('all') print '\t\tfmea = %.3f -> %.3f, prec = %.3f -> %.3f, rec = %.3f -> %.3f' %\ (f_measure_gc, f_measure_ls, precision_gc, precision_ls, recall_gc, recall_ls)
else: mask_res = mask_sfm stats_sfm = seg_stats(mask, mask_res) if mask.shape != mask_morph.shape: mask_res = cv2.resize(mask_morph.astype(np.uint8), mask.shape[::-1]) else: mask_res = mask_morph stats_morph = seg_stats(mask, mask_res) # tp_sfm = 100 # tp_morph = 100 tools.visualize_seg(data, mask, mask, slice=None, title='ground thruth', show_now=False) tools.visualize_seg( data_sfm, mask_sfm, sfm, slice=None, title='sfm, TP=%.1f, TN=%.1f, FP=%.1f, FN=%.1f' % (stats_sfm.tp, stats_sfm.tn, stats_sfm.fp, stats_sfm.fn), show_now=False) tools.visualize_seg( data_morph, mask_morph, morph, slice=None,