def test_simple_graph_cut_overfit_with_low_noise(self): img, seg, seeds = self.make_data(64, 20, sigma=20) segparams = { # 'method':'graphcut', "method": "graphcut", "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "modelparams": { "type": "gmmsame", "params": { "n_components": 3 }, # 'fv_type': "fv_extern", # 'fv_extern': fv_function, # 'adaptation': 'original_data', }, } gc = pycut.ImageGraphCut(img, segparams=segparams, debug_images=False) gc.set_seeds(seeds) gc.run() # import sed3 # ed = sed3.sed3(img, contour=(gc.segmentation==0).astype(np.double)) # ed.show() err = np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))) self.assertLess(err, 600)
def test_simple_imcut_2d(): noise_sigma = 50 img = 80 + np.random.rand(64, 64) * noise_sigma img[12:32, 5:25] = img[12:32, 5:25] + 30 # cca 400 px # seeds seeds = np.zeros([64, 64], np.int8) seeds[13:29, 18:23] = 1 seeds[4:9, 3:32] = 2 # [mm] 10 x 10 x 10 # voxelsize_mm = [1, 4, 3] voxelsize_mm = [5, 5, 5] pycut.defaultmodelparams gc = pycut.ImageGraphCut(img, segparams=None) gc.set_seeds(seeds) gc.run() # import matplotlib.pyplot as plt # import skimage.color # im = skimage.color.label2rgb(gc.segmentation + (seeds * 2), image=img/255., alpha=0.1) # plt.imshow(img, cmap="gray") # plt.figure() # plt.imshow(im) # plt.show() labels, counts = np.unique(gc.segmentation, return_counts=True) assert counts[0] > 300 assert counts[1] > 300
def test_fast_multiscale_gc_seg(self): """ Test fast multiscale segmentation """ img, seg, seeds = self.make_data(64, 20) segparams = { # 'method':'graphcut', "method": "multiscale_graphcut", "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "block_size": 8, "tile_zoom_constant": 1, } gc = pycut.ImageGraphCut(img, segparams=segparams) gc.set_seeds(seeds) gc.run() # import sed3 # ed = sed3.sed3(gc.segmentation==0, contour=seg) # ed.show() self.assertLess( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))), 600, )
def test_custom_density_function(self): import sklearn.mixture img, seg, seeds = self.make_data(64, 20) segparams = { # 'method':'graphcut', 'method': 'graphcut', 'modelparams': { 'type': 'custom', # 'params': {}, } } gc = pycut.ImageGraphCut(img, segparams=segparams) # rewrite the default setting by you own model from sklearn.neighbors import KernelDensity # object with .fit() and .score_samples() functions # gc.mdl.mdl[1] = KernelDensity(kernel='tophat') gc.mdl.mdl[1] = KernelDensity(kernel='gaussian') gc.mdl.mdl[2] = sklearn.mixture.GaussianMixture(n_components=1) gc.set_seeds(seeds) gc.run() err = np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))) assert err < 2000, "There should be low error"
def test_msgc_lo2hi_crazy_non_block_sized_images_68(self): """ Test multiscale segmentation lo2hi crazy block 68 """ img, seg, seeds = self.make_data(68, 20) segparams = { # 'method':'graphcut', "method": "multiscale_graphcut_lo2hi", # 'method': 'multiscale_graphcut_hi2lo', "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "block_size": 8, "tile_zoom_constant": 1, } gc = pycut.ImageGraphCut(img, segparams=segparams, keep_graph_properties=True) gc.set_seeds(seeds) gc.run() edseeds = seeds # gc.interactive_inspect_node() # node_unariesalt, node_neighboor_edges_and_weights, node_neighboor_seeds = gc.inspect_node(edseeds) self.assertLess( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))), 100, )
def test_segmentation(self): data_shp = [16, 16, 16] data = self.generate_data(data_shp) seeds = np.zeros(data_shp) # setting background seeds seeds[:, 0, 0] = 1 seeds[6, 8:-5, 2] = 2 # x[4:-4, 6:-2, 1:-6] = -1 igc = pycut.ImageGraphCut(data) igc.interactivity() # instead of interacitivity just set seeeds # igc.set_seeds(seeds) # igc.make_gc() # instead of showing just test results # from PyQt4.QtGui import QApplication # app = QApplication(sys.argv) # pyed = seed_editor_qt.QTSeedEditor(igc.segmentation, # modeFun=self.interactivity_loop, # voxelVolume=self.voxel_volume, # seeds=self.seeds, minVal=min_val, maxVal=max_val) # app.exec_() # igc.show_segmentation() segmentation = igc.segmentation # Testin some pixels for result self.assertTrue(segmentation[0, 0, -1] == 0) self.assertTrue(segmentation[7, 9, 3] == 1) self.assertTrue(np.sum(segmentation) > 10)
def test_segmentation_with_boundary_penalties(self): data_shp = [16, 16, 16] # data = self.generate_data(data_shp, boundary_only=True) data = self.generate_data(data_shp, object_type="wall") seeds = np.zeros(data_shp) # setting background seeds seeds[:, 0, 0] = 1 seeds[6, 8:-5, 2] = 2 # x[4:-4, 6:-2, 1:-6] = -1 segparams = {"pairwiseAlpha": 10, "use_boundary_penalties": True} igc = pycut.ImageGraphCut(data, segparams=segparams) igc.interactivity() # instead of interacitivity just set seeeds # igc.set_seeds(seeds) # igc.make_gc() # instead of showing just test results # from PyQt4.QtGui import QApplication # app = QApplication(sys.argv) # pyed = seed_editor_qt.QTSeedEditor(igc.segmentation, # modeFun=self.interactivity_loop, # voxelVolume=self.voxel_volume, # seeds=self.seeds, minVal=min_val, maxVal=max_val) # app.exec_() # igc.show_segmentation() import pdb pdb.set_trace() segmentation = igc.segmentation # Testin some pixels for result self.assertTrue(segmentation[0, 0, -1] == 0) self.assertTrue(segmentation[7, 9, 3] == 1) self.assertTrue(np.sum(segmentation) > 10)
def test_dicomread_and_graphcut(self): """ Test dicomread module and graphcut module """ from imcut import pycut path_to_script = os.path.dirname(os.path.abspath(__file__)) dcmdir = os.path.join( path_to_script, './../sample_data/matlab/examples/sample_data/DICOM/digest_article/' ) #noqa data3d, metadata = dcmr.dcm_read_from_dir(dcmdir) # print("Data size: " + str(data3d.nbytes) + ', shape: ' + str(data3d.shape) ) #noqa igc = pycut.ImageGraphCut(data3d, zoom=0.5) seeds = igc.seeds seeds[0, :, 0] = 1 seeds[60:66, 60:66, 5:6] = 2 igc.noninteractivity(seeds) igc.make_gc() segmentation = igc.segmentation self.assertTrue(segmentation[14, 4, 1] == 0) self.assertTrue(segmentation[127, 120, 10] == 1) self.assertTrue(np.sum(segmentation == 1) > 100) self.assertTrue(np.sum(segmentation == 0) > 100)
def test_external_fv(self): """ test external feature vector """ img, seg, seeds = self.make_data(64, 20) segparams = { # 'method':'graphcut', "method": "graphcut", "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "modelparams": { "fv_type": "fv_extern", "fv_extern": fv_function }, } gc = pycut.ImageGraphCut(img, segparams=segparams) gc.set_seeds(seeds) gc.run() # import sed3 # ed = sed3.sed3(gc.segmentation==0, contour=seg) # ed.show() self.assertLess( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))), 600, )
def test_ms_seg_compared_with_different_resolution(self): """ Test multiscale segmentation compared with different resolution """ img, seg, seeds = self.make_data(64, 20) segparams = { # 'method':'graphcut', "method": "multiscale_graphcut_hi2lo", "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "block_size": 8, "tile_zoom_constant": 1, } gc = pycut.ImageGraphCut(img, segparams=segparams) gc.set_seeds(seeds) gc.run() # import sed3 # ed = sed3.sed3(gc.segmentation==0, contour=seg) # ed.show() self.assertLess( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))), 600, ) # different resolution # sz = [128,128,128] sz = [70, 70, 70] sz = [90, 90, 90] sz = [100, 100, 100] sz = [200, 200, 200] sz1 = 70 sz = [sz1, sz1, sz1] img2 = pycut.zoom_to_shape(img, sz, np.uint8) seg2 = pycut.zoom_to_shape(seg, sz, np.uint8) seeds2 = pycut.zoom_to_shape(seeds, sz, np.int8) segparams["tile_zoom_constant"] = 0.8 gc = pycut.ImageGraphCut(img2, segparams=segparams) gc.set_seeds(seeds2) gc.run()
def test_simple_graph_cut_interactive(self): img, seg, seeds = self.make_data(64, 20) gc = pycut.ImageGraphCut(img, segparams=self.segparams_ssgc) gc.set_seeds(seeds) # gc.run() gc.interactivity() err = np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))) self.assertLess(err, 600)
def test_node_inspection_on_msgc_lo2hi(self): """ Test multiscale segmentation lo2hi with node inspection """ img, seg, seeds = self.make_data(64, 20) segparams = { # 'method':'graphcut', "method": "multiscale_graphcut_lo2hi", # 'method': 'multiscale_graphcut_hi2lo', "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "block_size": 8, "tile_zoom_constant": 1, } gc = pycut.ImageGraphCut(img, segparams=segparams, keep_graph_properties=True) gc.set_seeds(seeds) gc.run() self.assertLess( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))), 100, ) # gc.interactive_inspect_node() node_msindex = gc.debug_get_node_msindex(seeds) node_unariesalt, node_neighboor_edges_and_weights, node_neighboor_seeds = gc.debug_inspect_node( node_msindex=node_msindex) ii, ij, ik = np.nonzero(node_neighboor_seeds) # self.assertLessEqual( np.max(ii) - np.min(ii), 24, msg= "Neighbor nodes position variance should be maximum 3 * block size ", ) self.assertLessEqual( np.max(ij) - np.min(ij), 24, msg= "Neighbor nodes position variance should be maximum 3 * block size ", ) self.assertLessEqual( np.max(ik) - np.min(ik), 24, msg= "Neighbor nodes position variance should be maximum 3 * block size ", )
def test_boundary_penalty_array(self): """ Test if on edge are smaller values """ data = self.generate_data([16, 16, 16]) * 100 igc = pycut.ImageGraphCut(data) # igc.interactivity() penalty_array = igc._boundary_penalties_array(axis=0) edge_area_pattern = np.mean(penalty_array[3:5, 8:10, 2]) flat_area_pattern = np.mean(penalty_array[1:3, 3:6, -4:-2]) self.assertGreater(flat_area_pattern, edge_area_pattern)
def test_apriori(self): """ Test apriori segmentation. Make segmentation twice. First is used with gamma=0.2, second is used with gamma=0.9 """ img, seg, seeds = self.make_data(64, 20) apriori = np.zeros([64, 64, 64]) apriori[:20, :20, :20] = 1 segparams1 = {"apriori_gamma": 0.1} gc = pycut.ImageGraphCut(img, segparams=segparams1) gc.set_seeds(seeds) gc.apriori = apriori gc.run() # import sed3 # ed = sed3.sed3(img, contour=(gc.segmentation==0)) # ed.show() self.assertLess( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))), 600, ) segparams2 = {"apriori_gamma": 0.9} gc = pycut.ImageGraphCut(img, segparams=segparams2) gc.set_seeds(seeds) gc.apriori = apriori gc.run() self.assertLess( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - apriori.astype(np.int8))), 600, )
def test_simple_graph_cut(self): img, seg, seeds = self.make_data(64, 20) gc = pycut.ImageGraphCut(img, segparams=self.segparams_ssgc) gc.set_seeds(seeds) gc.run() # import sed3 # ed = sed3.sed3((gc.segmentation==0).astype(np.double), contour=seg) # ed.show() err = np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))) self.assertLess(err, 600)
def test_ordered_values_by_indexes(self): """ test of pycut.__ordered_values_by_indexes """ # there must be some data img = np.zeros([32, 32, 32], dtype=np.int16) data = np.array([[0, 1, 1], [0, 2, 2], [0, 2, 2]]) inds = np.array([[0, 1, 2], [3, 4, 4], [5, 4, 4]]) gc = pycut.ImageGraphCut(img) vals = gc._ImageGraphCut__ordered_values_by_indexes(data, inds) expected = np.array([0, 1, 1, 0, 2, 0]) self.assertCountEqual(vals, expected)
def test_segmentation(self): img, seg, seeds = self.make_data() gc = pycut.ImageGraphCut(img) gc.set_seeds(seeds) gc.run() # import sed3 # ed = sed3.sed3(gc.segmentation==0, contour=seg) # ed.show() self.assertLess( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))), 30, )
def autoSeg(self): if self.dcm_3Ddata is None: self.statusBar().showMessage('No DICOM data!') return igc = pycut.ImageGraphCut(self.dcm_3Ddata, voxelsize=self.voxel_size_mm) pyed = QTSeedEditor(self.dcm_3Ddata, seeds=self.segmentation_seeds, modeFun=igc.interactivity_loop, voxelVolume=self.voxel_volume) pyed.exec_() self.segmentation_data = pyed.getContours() self.segmentation_seeds = pyed.getSeeds() self.checkSegData()
def test_simple_graph_cut_show_similarity(self): img, seg, seeds = self.make_data(64, 20) gc = pycut.ImageGraphCut(img, segparams=self.segparams_ssgc) gc.set_seeds(seeds) gc.run() gc.debug_show_reconstructed_similarity(show=False) gc.debug_show_model(start=-500, stop=500, show=False) # import sed3 # ed = sed3.sed3((gc.segmentation==0).astype(np.double), contour=seg) # ed.show() err = np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))) self.assertLess(err, 600)
def test_ordered_values_by_indexes_with_different_values(self): """ test of pycut.__ordered_values_by_indexes in input data are non-consistent data Function should take maximal value """ # there must be some data img = np.zeros([32, 32, 32], dtype=np.int16) data = np.array([[0, 1, 1], [0, 2, 2], [0, 3, 2]]) inds = np.array([[0, 1, 2], [3, 4, 4], [5, 4, 4]]) gc = pycut.ImageGraphCut(img) vals = gc._ImageGraphCut__ordered_values_by_indexes(data, inds) expected = np.array([0, 1, 1, 0, 3, 0]) self.assertCountEqual(vals, expected)
def test_ssgc_just_objects_with_seeds_round_data(self): """ Test single scale graph cut just objects with seeds on round data """ np.random.seed(3) img, seg, seeds = generate_round_data(45, 3, 10, 3, add_object_without_seeds=True) segparams = { "method": "graphcut", # 'method': 'multiscale_graphcut_hi2lo', "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "block_size": 8, "tile_zoom_constant": 1, "return_only_object_with_seeds": True, } gc = pycut.ImageGraphCut(img, segparams=segparams, keep_graph_properties=True) gc.set_seeds(seeds) gc.run() # import sed3 # ed = sed3.show_slices(img, gc.segmentation*2, seeds=seeds) self.assertEqual((gc.segmentation == 0).astype(np.int8)[-3, -3, -3], 0) self.assertLess( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))), 1500, msg="error is expected in the corner", ) self.assertGreater( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))), 1000, msg="error is expected in the corner", )
def test_gc_box_overfiting(self): data3d, seeds, voxelsize = box_data(noise_sigma=0.5) segparams = { # 'method':'graphcut', "method": "graphcut", "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "modelparams": { "type": "gmmsame", "params": { "n_components": 3 }, # 'fv_type': "fv_extern", # 'fv_extern': fv_function, # 'adaptation': 'original_data', }, } gc = pycut.ImageGraphCut(data3d, segparams=segparams, debug_images=False) gc.set_seeds(seeds) gc.run()
def grabcut(image_path, pred_path, weak_path, save_path): import imcut.pycut as pspc image = nib.load(image_path).get_data() weak = nib.load(weak_path).get_data() pred = nib.load(pred_path).get_data() seeds = weak.copy() seeds[pred == 1] = 3 # uncertain FG seeds[pred == 0] = 4 # uncertain BG seeds[weak == 1] = 1 # fg seeds[weak == 0] = 2 # background # current = datetime.datetime.now() # run igc = pspc.ImageGraphCut(image, voxelsize=[1, 1, 1]) igc.set_seeds(seeds) igc.run() # print('Cost', datetime.datetime.now() - current) # save results pred = igc.segmentation pred = (1 - pred).astype(np.uint8) labNii = nib.Nifti1Image(pred, np.eye(4)) nib.save(labNii, save_path)
def test_multiscale_indexes(self): # there must be some data img = np.zeros([32, 32, 32], dtype=np.int16) gc = pycut.ImageGraphCut(img) # mask = np.zeros([1, 4, 4], dtype=np.int16) # mask[0,1:3,2:] = 1 mask = np.zeros([1, 3, 3], dtype=np.int16) mask[0, 1:, 1] = 1 orig_shape = [2, 6, 6] # zoom = 2 inds, mask_resized = gc._ImageGraphCut__hi2lo_multiscale_indexes( mask, orig_shape) expected_result = [ [ [0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 2, 2], [3, 3, 7, 8, 4, 4], [3, 3, 9, 10, 4, 4], [5, 5, 11, 12, 6, 6], [5, 5, 13, 14, 6, 6], ], [ [0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 2, 2], [3, 3, 15, 16, 4, 4], [3, 3, 17, 18, 4, 4], [5, 5, 19, 20, 6, 6], [5, 5, 21, 22, 6, 6], ], ] self.assertCountEqual(inds.reshape(-1), np.array(expected_result).reshape(-1))
def test_simple_graph_cut_feature_vector_fv001_intensity_and_blur(self): # test feature vector with segparams = { # 'method':'graphcut', "method": "graphcut", "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "modelparams": { "type": "gmmsame", "params": { "n_components": 2 }, "fv_type": "intensity_and_blur" # 'fv_type': "fv_extern", # 'fv_extern': fv_function, # 'adaptation': 'original_data', }, } img, seg, seeds = self.make_data(64, 20) gc = pycut.ImageGraphCut(img, segparams=segparams) gc.set_seeds(seeds) gc.run() # outputs looks strange # gc.show_similarity(show=True) # gc.show_model(start=-500, stop=500, show=True) # import sed3 # ed = sed3.sed3(img, contour=gc.segmentation) # ed.show() # ed = sed3.sed3((gc.segmentation==0).astype(np.double), contour=seg) # ed.show() err = np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8)))
def do_segmentation_with_graphcut(self, image: np.ndarray, resolution: np.ndarray, time_resolution: float, qapp=None): import imcut.pycut as pspc import seededitorqt.seed_editor_qt from seededitorqt.seed_editor_qt import QTSeedEditor import imma.image_manipulation gc_pxsz_mm = float( self.parameters.param("Graph-Cut Pixelsize").value()) * 1000 gc_pairwise_alpha = int( self.parameters.param("Graph-Cut Pairwise Alpha").value()) gc_resize = bool(self.parameters.param("Graph-Cut Resize").value()) gc_msgc = bool(self.parameters.param("Graph-Cut Multiscale").value()) vxsz_mm = np.array([1.0, resolution[0] * 1000, resolution[1] * 1000]) new_vxsz_mm = np.array([1.0, gc_pxsz_mm, gc_pxsz_mm]) logger.debug(f"vxsz_mm={vxsz_mm}") logger.debug(f"new_vxsz_mm={new_vxsz_mm}") logger.debug(f"rel={vxsz_mm / new_vxsz_mm}") logger.debug(f"new sz ={image.shape * vxsz_mm / new_vxsz_mm}") if gc_resize: im_resized = imma.image_manipulation.resize_to_mm( image, voxelsize_mm=vxsz_mm, new_voxelsize_mm=new_vxsz_mm) else: im_resized = image logger.debug(f"im_resized.shape={im_resized.shape}") segparams = { # 'method':'graphcut', 'method': 'multiscale_graphcut', 'use_boundary_penalties': False, 'boundary_dilatation_distance': 1, 'boundary_penalties_weight': 1, 'block_size': 8, 'tile_zoom_constant': 1, "pairwise_alpha": gc_pairwise_alpha, } if gc_msgc: segparams["method"] = 'multiscale_graphcut' else: segparams["method"] = 'graphcut' igc = pspc.ImageGraphCut(im_resized, voxelsize=new_vxsz_mm, segparams=segparams) logger.debug(f"segparams={igc.segparams}") # seeds = igc.interactivity(qt_app=qapp) logger.debug(f"qapp[{type(qapp)}]={qapp}") pyed = QTSeedEditor( igc.img, seeds=igc.seeds, modeFun=igc.interactivity_loop, voxelSize=igc.voxelsize * 1000, volume_unit='', init_brush_index=0, ) pyed.voxel_label.setText( f"%.2f x %.2f x %.2f [µm]" % tuple(pyed.voxel_size[np.array(pyed.act_transposition)])) # seededitorqt.seed_editor_qt.VIEW_TABLE = {"time": (2, 1, 0), "X": (1, 0, 2), "Y": (2, 0, 1)} # pyed.actual_view = "time" logger.debug("exec_()") pyed.exec_() logger.debug("exec is done") logger.debug(f"stats={igc.stats}") logger.debug(f"GC time ={igc.stats['gc time']}") logger.debug( f"segmentation[{type(igc.segmentation)}]={igc.segmentation}") seg = imma.image_manipulation.resize_to_shape(igc.segmentation, shape=image.shape) import scipy.stats seg = (1 - seg).astype(np.int8) logger.debug(f"unique={np.unique(seg, return_counts=True)}") return seg
import numpy as np import imcut.pycut as pspc import matplotlib.pyplot as plt # create data data = np.random.rand(30, 30, 30) data[10:20, 5:15, 3:13] += 1 data = data * 30 data = data.astype(np.int16) # Make seeds seeds = np.zeros([30, 30, 30]) seeds[13:17, 7:10, 5:11] = 1 seeds[0:5:, 0:10, 0:11] = 2 # Run igc = pspc.ImageGraphCut(data, voxelsize=[1, 1, 1]) igc.set_seeds(seeds) igc.run() # Show results colormap = plt.cm.get_cmap('brg') colormap._init() colormap._lut[:1:, 3] = 0 plt.imshow(data[:, :, 10], cmap='gray') plt.contour(igc.segmentation[:, :, 10], levels=[0.5]) plt.imshow(igc.seeds[:, :, 10], cmap=colormap, interpolation='none') plt.savefig("gc_example.png") plt.show()
img = (100 * segm + sigma * np.random.random(img.shape)).astype(np.uint8) return img, segm, seeds img, seg, seeds = make_data(64, 20) segparams = { # 'method':'graphcut', # "method": "multiscale_graphcut", # "method": "hi2lo", "method": "lo2hi", "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "block_size": 8, "tile_zoom_constant": 1, } gc = pycut.ImageGraphCut(img, segparams=segparams) gc.set_seeds(seeds) gc.run() # cProfile.run("gc.run()") # import sed3 # ed = sed3.sed3(gc.segmentation==0, contour=seg) # ed.show() # self.assertLess( # np.sum( # np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8)) # ), # 600, # )
def test_save_load(self): """ test external feature vector with save model in the middle of processing """ img, seg, seeds = self.make_data(64, 20) segparams = { # 'method':'graphcut', "method": "graphcut", "use_boundary_penalties": False, "boundary_dilatation_distance": 2, "boundary_penalties_weight": 1, "modelparams": { "type": "gmmsame", "fv_type": "intensity", # 'fv_extern': fv_function, "adaptation": "original_data", }, } gc = pycut.ImageGraphCut(img, segparams=segparams) gc.set_seeds(seeds) gc.run() # import sed3 # ed = sed3.sed3((gc.segmentation==0).astype(np.double), contour=seg) # ed.show() err = np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))) self.assertLess(err, 600) mdl_stored_file = "test_model.p" gc.save(mdl_stored_file) # forget gc = None img, seg, seeds = self.make_data(56, 18) # there is only one change in mdl params # segparams['modelparams'] = { # 'mdl_stored_file': mdl_stored_file, # } gc = pycut.ImageGraphCut(img) # , segparams=segparams) gc.load(mdl_stored_file) gc.set_seeds(seeds) gc.run() err = np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))) self.assertLess(err, 600) # import sed3 # sed3.show_slices(img, contour=gc.segmentation==0, slice_step=6) # if we change the data there should be more error (assertMore) img = (img * 0.2).astype(np.uint8) # segparams['modelparams']['adaptation'] = 'original_data' # print(np.max(img)) # print(np.min(img)) gc = pycut.ImageGraphCut(img) # , segparams=segparams) gc.load(mdl_stored_file) gc.set_seeds(seeds) gc.run() m0 = gc.mdl.mdl[1] m1 = gc.mdl.mdl[2] logger.debug("model parameters") # import sed3 # ed = sed3.sed3((gc.segmentation==0).astype(np.double), contour=seg) # ed.show() err = np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))) self.assertGreater( err, 600, "There should be greater error when we changed the data") # self.assertGreater( # np.sum( # np.abs( # (gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8)) # ), # 600) os.remove(mdl_stored_file)
def test_msgc_lo2hi_round_data(self): """ Test multiscale segmentation lo2hi round data """ np.random.seed(3) img, seg, seeds = generate_round_data(45, 3, 10, 3) blocksize = 6 segparams = { # 'method':'graphcut', "method": "multiscale_graphcut_lo2hi", # 'method': 'multiscale_graphcut_hi2lo', "use_boundary_penalties": False, "boundary_dilatation_distance": 1, "boundary_penalties_weight": 1, "block_size": blocksize, "tile_zoom_constant": 1, } gc = pycut.ImageGraphCut( img, segparams=segparams, keep_graph_properties=True, # debug_images=True, debug_images=False, ) gc.set_seeds(seeds) gc.run() # import sed3 # ed = sed3.show_slices(img, gc.segmentation*2) # gc.debug_show_model() # gc.debug_show_reconstructed_similarity() tdata1, tdata2 = gc.debug_get_reconstructed_similarity() edseeds = seeds # node_unariesalt, node_neighboor_edges_and_weights, node_neighboor_seeds, node_msindex = gc.interactive_inspect_node() node_msindex = gc.debug_get_node_msindex(edseeds) node_unariesalt, node_neighboor_edges_and_weights, node_neighboor_seeds = gc.debug_inspect_node( node_msindex) nlinks_max = gc.debug_reconstruct_nlinks_max() from imcut import image_manipulation as imma seg_uncr = imma.uncrop(gc.segmentation, None, nlinks_max.shape) # import sed3 # ed = sed3.sed3(nlinks_max, contour=seg_uncr*2) # ed.show() self.assertLess( np.sum( np.abs((gc.segmentation == 0).astype(np.int8) - seg.astype(np.int8))), 100, ) self.assertEqual( np.max(nlinks_max), blocksize, "nlink maximal value in reconstructed nlink map. " "It should be size of block if there are at least some" " lowres blocks.", ) self.assertEqual(np.min(nlinks_max), 1, "nlink minimal value in reconstructed nlink map") self.assertGreaterEqual( np.min(tdata1), 0, "tlink minimal value in reconstructed tlink map") self.assertGreaterEqual( np.min(tdata2), 0, "tlink minimal value in reconstructed tlink map") self.assertGreaterEqual( node_neighboor_edges_and_weights.shape[0], 3, "check number of nlink connections", ) self.assertLessEqual( node_neighboor_edges_and_weights.shape[0], 6, "check number of nlink connections", ) self.assertGreaterEqual(np.min(node_unariesalt), 0, "selected node nlink minimum")