def btnVesselSegmentation(self): """ Function calls segmentation.vesselSegmentation function. """ outputSegmentation = segmentation.vesselSegmentation( self.oseg.data3d, self.oseg.segmentation, threshold=-1, inputSigma=0.15, dilationIterations=2, nObj=1, biggestObjects=False, interactivity=True, binaryClosingIterations=2, binaryOpeningIterations=0) # rint outputSegmentation # rint np.unique(outputSegmentation) # rint self.oseg.slab slab = {'porta': 2} slab.update(self.oseg.slab) # rom PyQt4.QtCore import pyqtRemoveInputHook # yqtRemoveInputHook() # mport ipdb; ipdb.set_trace() # BREAKPOINT self.oseg.slab = slab self.oseg.segmentation[outputSegmentation == 1] = slab['porta']
def data_to_binar(self): # ## Median filter filteredData = scipy.ndimage.filters.median_filter(self.data3d, size=2) # ## Segmentation data3d_thr = segmentation.vesselSegmentation( filteredData, # self.data3d, segmentation=np.ones(filteredData.shape, dtype='int8'), threshold=self.threshold, inputSigma=0, # 0.15, dilationIterations=2, nObj=1, biggestObjects=False, useSeedsOfCompactObjects=False, interactivity=not self.nogui, binaryClosingIterations=self.binaryClosing, # noqa 5, binaryOpeningIterations=self.binaryOpening, # 1 # noqa qapp=self.qapp ) del(filteredData) # ## Zalepeni der scipy.ndimage.morphology.binary_fill_holes(data3d_thr, output=data3d_thr) self.data3d_thr = data3d_thr
def hepaticVeinsSegmentation(self): import segmentation outputSegmentation = segmentation.vesselSegmentation( self.data3d, self.segmentation, threshold=-1, inputSigma=0.15, dilationIterations=10, nObj=1, biggestObjects=False, useSeedsOfCompactObjects=True, interactivity=True, binaryClosingIterations=2, binaryOpeningIterations=0) slab = {'hepatic_veins': 3} slab.update(self.slab) # rom PyQt4.QtCore import pyqtRemoveInputHook # yqtRemoveInputHook() # mport ipdb; ipdb.set_trace() # BREAKPOINT self.slab = slab self.segmentation[outputSegmentation == 1] = slab['hepatic_veins'] # skeletonizace self.__vesselTree(outputSegmentation, 'hepatic_veins')
def main4(): data = misc.obj_from_file('c:\_bp_data\d5\org-liver-orig004.mhd-3mm_alpha45.pklz', filetype = 'pickle') outputTmp = sg.vesselSegmentation( data['data3d'], segmentation = data['segmentation'], threshold = -1, inputSigma = 0.15, dilationIterations = 2, interactivity = True, biggestObjects = False, binaryClosingIterations = 2, binaryOpeningIterations = 0)
def main2(): slab = {'none':0, 'liver':1, 'porta':2} voxelsize_mm = np.array([1.0, 1.0, 1.2]) segm = np.zeros([256, 256, 80], dtype = np.uint8) # liver segm[70:180, 40:190, 30:60] = slab['liver'] # port segm[120:130, 70:190, 40:45] = slab['porta'] segm[80:130, 100:110, 40:45] = slab['porta'] segm[120:170, 130:135, 40:44] = slab['porta'] data3d = np.zeros(segm.shape) data3d[segm == slab['liver']] = 156 data3d[segm == slab['porta']] = 206 #noise = (np.random.rand(segm.shape[0], segm.shape[1], segm.shape[2])*30).astype(np.int16) noise = (np.random.normal(0, 30, segm.shape))#.astype(np.int16) data3d = (data3d + noise).astype(np.uint8) # @TODO je tam bug, prohl??e? neum? korektn? pracovat s doubly # app = QApplication(sys.argv) # #pyed = QTSeedEditor(noise ) # pyed = QTSeedEditor(data3d) # pyed.exec_() # #img3d = np.zeros([256,256,80], dtype=np.int16) # pyed = sed3.sed3(data3d) # pyed.show() outputTmp = sg.vesselSegmentation( data3d, segmentation = segm == slab['liver'], voxelsize_mm = voxelsize_mm, threshold = 180, inputSigma = 0.15, dilationIterations = 2, nObj = 1, interactivity = True, biggestObjects = False, binaryClosingIterations = 5, binaryOpeningIterations = 1) if outputTmp == None: print('Final output is None')
def main2(): slab = {'none':0, 'liver':1, 'porta':2} voxelsize_mm = np.array([1.0, 1.0, 1.2]) segm = np.zeros([256, 256, 80], dtype = np.uint8) # liver segm[70:180, 40:190, 30:60] = slab['liver'] # port segm[120:130, 70:190, 40:45] = slab['porta'] segm[80:130, 100:110, 40:45] = slab['porta'] segm[120:170, 130:135, 40:44] = slab['porta'] data3d = np.zeros(segm.shape) data3d[segm == slab['liver']] = 156 data3d[segm == slab['porta']] = 206 #noise = (np.random.rand(segm.shape[0], segm.shape[1], segm.shape[2])*30).astype(np.int16) noise = (np.random.normal(0, 30, segm.shape))#.astype(np.int16) data3d = (data3d + noise).astype(np.uint8) # @TODO je tam bug, prohl??e? neum? korektn? pracovat s doubly # app = QApplication(sys.argv) # #pyed = QTSeedEditor(noise ) # pyed = QTSeedEditor(data3d) # pyed.exec_() # #img3d = np.zeros([256,256,80], dtype=np.int16) # pyed = sed3.sed3(data3d) # pyed.show() outputTmp = sg.vesselSegmentation( data3d, segmentation = segm == slab['liver'], voxelsize_mm = voxelsize_mm, threshold = 180, inputSigma = 0.15, dilationIterations = 2, nObj = 1, interactivity = True, biggestObjects = False, binaryClosingIterations = 5, binaryOpeningIterations = 1) if outputTmp == None: print 'Final output is None'
def data_to_binar(self): ### Median filter filteredData = scipy.ndimage.filters.median_filter(self.data3d, size=2) ### Segmentation data3d_thr = segmentation.vesselSegmentation( filteredData, segmentation=np.ones(self.data3d.shape, dtype='int8'), threshold=self.threshold, #-1, inputSigma=0, #0.15, dilationIterations=2, nObj=1, biggestObjects= False, interactivity= not self.nogui, binaryClosingIterations=2, #5, # TODO !!! - vytvari na stranach oblasti ktere se pak nenasegmentuji binaryOpeningIterations=0 #1 ) ### NoGUI segmentation fix # Pri pouziti nogui modu segmentation.py nepouzije funkci getPriorityObjects jelikoz nema seedy => odlisne vysledky. # Proto musim rucne zjistit vhodny seed a zavolat funkci az ted. if self.nogui: # Get seed that is inside of big object seed_data = scipy.ndimage.morphology.binary_erosion(data3d_thr, iterations=2) # hledam pouze velke cevy seed = None for i in xrange(seed_data.shape[0]/3,seed_data.shape[0]-1): # shape/3 aby se zaclo hledat kolem prostredku for n in xrange(seed_data.shape[1]/3,seed_data.shape[1]-1): for j in xrange(seed_data.shape[2]/3,seed_data.shape[2]-1): if seed_data[i][n][j]==1: seed = (np.array([i]),np.array([n]),np.array([j])) logger.debug('automatic seed -> '+str(seed)+' value -> '+str(seed_data[i][n][j])) break if seed is not None: break if seed is not None: break # Zaruci ze ve vystupu nebudou cevy ktere vedou od nikud nikam data3d_thr = thresholding_functions.getPriorityObjects(data3d_thr, nObj=1, seeds=seed) ### Zalepeni der data3d_thr = scipy.ndimage.morphology.binary_fill_holes(data3d_thr) return data3d_thr
#oseg.data3d = oseg.data3d[cri[0][0]:cri[0][1],cri[1][0]:cri[1][1],cri[2][0]:cri[2][1]] #pyed = sed3.sed3(oseg.data3d, contour = oseg.orig_scale_segmentation) print('slab', data['slab']) #import ipdb; ipdb.set_trace() # BREAKPOINT #pyed = sed3.sed3(data['data3d'], contour = data['segmentation']) #pyed.show() #import pdb; pdb.set_trace() outputTmp = segmentation.vesselSegmentation( data['data3d'], segmentation=data['segmentation'], #segmentation = oseg.orig_scale_segmentation, threshold=-1, inputSigma=0.15, dilationIterations=2, nObj=1, biggestObjects=args.biggest, # dataFiltering = True, interactivity=True, binaryClosingIterations=2, binaryOpeningIterations=0) # Uvolneni pameti garbage.collect() import inspector inspect = inspector.inspector(outputTmp) output = inspect.run() # Uvolneni pameti
def test_synthetic_data_segmentation(self): """ Function uses organ_segmentation for synthetic box object segmentation. """ #dcmdir = os.path.join(path_to_script,'./../sample_data/matlab/examples/sample_data/DICOM/digest_article/') # data slab = {'none':0, 'liver':1, 'porta':2} voxelsize_mm = np.array([1.0,1.0,1.2]) segm = np.zeros([256,256,80], dtype=np.int16) # liver segm[70:180,40:190,30:60] = slab['liver'] # port segm[120:130,70:190,40:45] = slab['porta'] segm[80:130,100:110,40:45] = slab['porta'] segm[120:170,130:135,40:44] = slab['porta'] data3d = np.zeros(segm.shape) data3d[segm== slab['liver']] = 156 data3d[segm== slab['porta']] = 206 #noise = (np.random.rand(segm.shape[0], segm.shape[1], segm.shape[2])*30).astype(np.int16) noise = (np.random.normal(0,30,segm.shape))#.astype(np.int16) data3d = (data3d + noise ).astype(np.int16) # @TODO je tam bug, prohlížeč neumí korektně pracovat s doubly # app = QApplication(sys.argv) # #pyed = QTSeedEditor(noise ) # pyed = QTSeedEditor(data3d) # pyed.exec_() # #img3d = np.zeros([256,256,80], dtype=np.int16) # pyed = py3DSeedEditor.py3DSeedEditor(data3d) # pyed.show() outputTmp = segmentation.vesselSegmentation( data3d, #.astype(np.uint8), segmentation = (segm==slab['liver']), #.astype(np.uint8), #segmentation = oseg.orig_scale_segmentation, voxelsize_mm = voxelsize_mm, threshold = 180, inputSigma = 0.15, dilationIterations = 2, nObj = 1, interactivity = False, biggestObjects=True, binaryClosingIterations = 5, binaryOpeningIterations = 1) # ověření výsledku #pyed = py3DSeedEditor.py3DSeedEditor(outputTmp, contour=segm==slab['porta']) #pyed.show() # @TODO opravit chybu v vesselSegmentation outputTmp = (outputTmp == 2) errim = np.abs(outputTmp.astype(np.int) - (segm == slab['porta']).astype(np.int)) # ověření výsledku #pyed = py3DSeedEditor.py3DSeedEditor(errim, contour=segm==slab['porta']) #pyed.show() #evaluation sum_of_wrong_voxels = np.sum(errim) sum_of_voxels = np.prod(segm.shape) #print "wrong ", sum_of_wrong_voxels #print "voxels", sum_of_voxels errorrate = sum_of_wrong_voxels/sum_of_voxels #import pdb; pdb.set_trace() self.assertLess(errorrate,0.1)
def portalVeinSegmentation(self, **inparams): """ Segmentation of vein in specified volume. It is given by label "liver". Usualy it is number 1. If there is no specified volume all image is used. If this function is used repeatedly (if there is some segmentation in this image) all segmentation labeled as 'porta' is removed and setted to 'liver' before processing. You can use additional parameters from vesselSegmentation() For example interactivity=False, biggestObjects=True, ... """ import segmentation logger.info('segmentation max label ' + str(np.max(self.segmentation))) # if there is no organ segmentation, use all image slab = {'porta': 2} slab.update(self.slab) logger.debug('self.slab') logger.debug(str(self.slab)) self.slab = slab # if there is no liver segmentation, use whole image if np.max(self.segmentation) == 0: self.segmentation = self.segmentation + 1 # remove prev segmentation self.segmentation[self.segmentation == slab['porta']] = slab['liver'] params = { 'threshold': -1, 'inputSigma': 0.15, 'dilationIterations': 10, 'nObj': 1, 'biggestObjects': False, 'useSeedsOfCompactObjects': True, 'interactivity': True, 'binaryClosingIterations': 2, 'binaryOpeningIterations': 0 } params.update(inparams) outputSegmentation = segmentation.vesselSegmentation( self.data3d, self.segmentation, **params # threshold=-1, # inputSigma=0.15, # dilationIterations=10, # nObj=1, # biggestObjects=False, # useSeedsOfCompactObjects=True, # # useSeedsOfCompactObjects=False, # interactivity=True, # binaryClosingIterations=2, # binaryOpeningIterations=0 ) # rom PyQt4.QtCore import pyqtRemoveInputHook # yqtRemoveInputHook() # mport ipdb; ipdb.set_trace() # BREAKPOINT self.segmentation[outputSegmentation == 1] = slab['porta']
def _interactivity_end(self, igc): """ This is called after processing step. All data are rescaled to original resolution. """ logger.debug('_interactivity_end()') self.__resize_to_orig(igc.seeds) self.organ_interactivity_counter = igc.interactivity_counter logger.debug("org inter counter " + str(self.organ_interactivity_counter)) logger.debug('nonzero segm ' + str(np.nonzero(self.segmentation))) # if False: if False: # TODO dodělat postprocessing PV import segmentation outputSegmentation = segmentation.vesselSegmentation( # noqa self.data3d, self.segmentation, threshold=-1, inputSigma=0.15, dilationIterations=10, nObj=1, biggestObjects=False, seeds=(self.segmentation > 0).astype(np.int8), useSeedsOfCompactObjects=True, interactivity=True, binaryClosingIterations=2, binaryOpeningIterations=0) self._segmentation_postprocessing() # rint 'autocrop', self.autocrop if self.autocrop is True: # rint # mport pdb; pdb.set_trace() tmpcrinfo = qmisc.crinfo_from_specific_data( self.segmentation, self.autocrop_margin) self.crop(tmpcrinfo) if self.texture_analysis not in (None, False): import texture_analysis # doplnit nějaký kód, parametry atd # elf.orig_scale_segmentation = # texture_analysis.segmentation(self.data3d, # self.orig_scale_segmentation, params = self.texture_analysis) self.segmentation = texture_analysis.segmentation( self.data3d, self.segmentation, self.voxelsize_mm ) # set label number # !! pomaly!!! # @TODO make faster self.segmentation[self.segmentation == 1] = self.output_label # logger.debug('self.slab') logger.debug(str(self.slab)) self.processing_time = ( datetime.datetime.now() - self.time_start).total_seconds() logger.debug('processing_time = ' + str(self.processing_time))
#oseg.data3d = oseg.data3d[cri[0][0]:cri[0][1],cri[1][0]:cri[1][1],cri[2][0]:cri[2][1]] #pyed = sed3.sed3(oseg.data3d, contour = oseg.orig_scale_segmentation) print 'slab', data['slab'] #import ipdb; ipdb.set_trace() # BREAKPOINT #pyed = sed3.sed3(data['data3d'], contour = data['segmentation']) #pyed.show() #import pdb; pdb.set_trace() outputTmp = segmentation.vesselSegmentation( data['data3d'], segmentation = data['segmentation'], #segmentation = oseg.orig_scale_segmentation, threshold = -1, inputSigma = 0.15, dilationIterations = 2, nObj = 1, biggestObjects = args.biggest, # dataFiltering = True, interactivity = True, binaryClosingIterations = 2, binaryOpeningIterations = 0) # Uvolneni pameti garbage.collect() import inspector inspect = inspector.inspector(outputTmp) output = inspect.run() # Uvolneni pameti
def test_synthetic_data_vessel_tree_evaluation(self): """ Generovani umeleho stromu do 3D a jeho evaluace. V testu dochazi ke kontrole predpokladaneho objemu a deky cev """ from gen_volume_tree import TreeVolumeGenerator from histology_analyser import HistologyAnalyser from histology_report import HistologyReport import segmentation import misc # generate 3d data from yaml for testing tvg = TreeVolumeGenerator() yaml_path = os.path.join(path_to_script, "./hist_stats_test.yaml") tvg.importFromYaml(yaml_path) tvg.voxelsize_mm = [1,1,1] tvg.shape = [100,100,100] tvg.generateTree() # init histology Analyser metadata = {'voxelsize_mm': tvg.voxelsize_mm} data3d = tvg.data3d*10 threshold = 2.5 ha = HistologyAnalyser(data3d, metadata, threshold) # modifited ha.data_to_skeleton() function data3d_thr = segmentation.vesselSegmentation( data3d, segmentation=np.ones(tvg.data3d.shape, dtype='int8'), threshold=threshold, inputSigma=0.15, dilationIterations=2, nObj=1, biggestObjects=False, interactivity=False, binaryClosingIterations=5, binaryOpeningIterations=1) data3d_skel = ha.binar_to_skeleton(data3d_thr) # get statistics ha.skeleton_to_statistics(data3d_thr, data3d_skel) yaml_new = "hist_stats_new.yaml" ha.writeStatsToYAML(filename=yaml_new) # get histology reports hr = HistologyReport() hr.importFromYaml(yaml_path) hr.generateStats() stats_orig = hr.stats hr = HistologyReport() hr.importFromYaml(os.path.join(path_to_script, yaml_new)) hr.generateStats() stats_new = hr.stats # compare self.assertGreater(stats_orig['Total length mm'],stats_new['Total length mm']*0.9) self.assertLess(stats_orig['Total length mm'],stats_new['Total length mm']*1.1) self.assertGreater(stats_orig['Avg length mm'],stats_new['Avg length mm']*0.9) self.assertLess(stats_orig['Avg length mm'],stats_new['Avg length mm']*1.1) self.assertGreater(stats_orig['Avg radius mm'],stats_new['Avg radius mm']*0.9) self.assertLess(stats_orig['Avg radius mm'],stats_new['Avg radius mm']*1.1)