Ejemplo n.º 1
0
    def _automatic_localization(self):
        """
        Automatic localization made by Tomas Ryba.
        """

        # seeds = self.get_seeds_using_class_1(class1)
        liver = self.data3d * (self.segmentation != 0)
        print 'analyzing histogram...'
        class1 = tools.analyse_histogram(self.data3d,
                                         roi=self.segmentation != 0)
        # py3DSeedEditor.py3DSeedEditor(self.data3d, seeds=class1).show()
        print 'getting seeds...'
        seeds = self.get_seeds_using_prob_class1(
            liver,
            class1,
            thresholdType='percOfMaxDist',
            percT=0.3)

        # py3DSeedEditor.py3DSeedEditor(self.data3d, seeds=seeds).show()

        print('Starting random walker...')
        rw = random_walker(liver, seeds, mode='cg_mg')
        print('...finished.')

        label_l = self.data['slab']['lesions']

        lessions = rw == 2
        py3DSeedEditor.py3DSeedEditor(self.data3d, contour=lessions).show()
        lessions = self.filter_objects(lessions)

        self.segmentation = np.where(lessions, label_l, self.segmentation)
Ejemplo n.º 2
0
def main():

    logger = logging.getLogger()

    logger.setLevel(logging.WARNING)
    ch = logging.StreamHandler()
    logger.addHandler(ch)

    #logger.debug('input params')

    data3d_a_path = None # os.path.join(path_to_script, '../../../data/medical/data_orig/sliver07/training-part1/liver-orig001.mhd')
    data3d_b_path = None #os.path.join(path_to_script, '../../../data/medical/data_orig/sliver07/training-part1/liver-seg001.mhd')
    parser = argparse.ArgumentParser(
            description='Information about pkl/pklz file')
    parser.add_argument('pklzFile',
            help='path to data' )
    args = parser.parse_args()

    data = misc.obj_from_file(args.pklzFile, 'pickle')
    print data

    try:
        pyed = py3DSeedEditor.py3DSeedEditor(data['data3d'], contour=data['segmentation'])
        pyed.show()
    except:
        try:

            pyed = py3DSeedEditor.py3DSeedEditor(data['data3d'])
            pyed.show()
        except:
            print "Problem with visualization"
Ejemplo n.º 3
0
def main():

    logger = logging.getLogger()

    logger.setLevel(logging.WARNING)
    ch = logging.StreamHandler()
    logger.addHandler(ch)

    # logger.debug('input params')

    # input parser
    parser = argparse.ArgumentParser(
        description='Module for segmentation of simple anatomical structures')
    parser.add_argument('-i', '--inputfile', default='vessels.pkl',
                        help='path to data dir')

    # args = parser.parse_args()
    # horsi kvalita segmentace
    # datapath = os.path.join(path_to_script, "../vessels1.pkl")
    # hypodenzni meta
    # datapath = os.path.join(path_to_script, args.inputfile)
    # horsi kvalita segmentace
    # datapath = os.path.join(path_to_script, "../organ.pkl")

    # data = misc.obj_from_file(args.inputfile, filetype = 'pickle')

    dcmdir = '/home/tomas/Dropbox/Work/Data/medical/org-38289898-export1.pklz'
    data = misc.obj_from_file(dcmdir, filetype='pickle')

    # windowing
    data['data3d'] = tools.windowing(data['data3d'], level=50, width=350)
    # data['data3d'] = smoothing(data['data3d'], sliceId=0)

    # smoothing ----------------
    # bilateral
    # data['data3d'] = tools.smoothing_bilateral(data['data3d'],
    # sigma_space=15, sigma_color=0.05, sliceId=0)
    # more bilateral
    # data['data3d'] = tools.smoothing_bilateral(data['data3d'],
    # sigma_space=15, sigma_color=0.1, sliceId=0)
    # total-variation
    data['data3d'] = tools.smoothing_tv(data['data3d'], weight=0.05, sliceId=0)
    # more total-variation
    # data['data3d'] = tools.smoothing_tv(data['data3d'], weight=0.2,
    # multichannel=False, sliceId=0)
    # py3DSeedEditor.py3DSeedEditor(data['data3d']).show()
    # ---------------------------gym

    tumory = Lesions()
    # tumory.overlay_test()
    tumory.import_data(data)
    tumory.automatic_localization()

    tumors = tumory.segmentation == tumory.data['slab']['lesions']
    py3DSeedEditor.py3DSeedEditor(tumory.data3d, contour=tumors).show()
Ejemplo n.º 4
0
def one_experiment_setting_for_whole_dataset(inputdata, tile_shape,
                                             feature_fcn, classif_fcn, train,
                                             visualization=False):
    fvall = []
    fv_tiles = []
    indata_len = len(inputdata['data'])
    #indata_len = 3

    for i in range(0, indata_len):
        data3d_orig, data3d_seg, voxelsize_mm = read_data_orig_and_seg(
            inputdata, i)

        if visualization:
            pyed = py3DSeedEditor.py3DSeedEditor(data3d_orig,
                                                 contour=data3d_seg)
            pyed.show()
            #import pdb; pdb.set_trace()
        #fvall.insert(i, get_features(
        #    data3d_orig,
        #    data3d_seg,
        #    visualization=args.visualization
        #    ))
        #feature_fcn = feat_hist
        fv_t = get_features_in_tiles(data3d_orig, data3d_seg, tile_shape,
                                     feature_fcn)
        cidxs, features_t, seg_cover_t = fv_t

        if train is True:
            labels_train_lin_float = np.array(seg_cover_t)
            labels_train_lin = labels_train_lin_float > 0.5

        #from sklearn import svm
        #clf = svm.SVC()

        clf = classif_fcn()
        clf.fit(features_t, labels_train_lin)
        labels_lin = clf.predict(features_t)

        d_shp = data3d_orig.shape

        labels = arrange_to_tiled_data(cidxs, tile_shape, d_shp,
                                       labels_lin)
            #ltl = (labels_train_lin_float * 10).astype(np.int8)
            #labels_train = arrange_to_tiled_data(cidxs, tile_shape,
            #                                     d_shp, ltl)

            #pyed = py3DSeedEditor.py3DSeedEditor(labels_train, contour=labels)
        if visualization:
            pyed = py3DSeedEditor.py3DSeedEditor(data3d_seg, contour=labels)
            pyed.show()
        fv_tiles.insert(i, fv_t)

# @TODO vracet něco inteligentního, fvall je prázdný
    return fvall
Ejemplo n.º 5
0
def show(data3d_a_path, sliver_seg_path, ourSegmentation):
    reader = datareader.DataReader()
    #data3d_a_path = os.path.join(path_to_script, data3d_a_path)
    datap_a = reader.Get3DData(data3d_a_path,
                               dataplus_format=True)

    if 'orig_shape' in datap_a.keys():
# pklz
        data3d_a = qmisc.uncrop(datap_a['data3d'], datap_a['crinfo'],
                                datap_a['orig_shape'])
    else:
#dicom
        data3d_a = datap_a['data3d']

    if sliver_seg_path is not None:
        sliver_seg_path = os.path.join(path_to_script, sliver_seg_path)
        sliver_datap = reader.Get3DData(sliver_seg_path,
                                        dataplus_format=True)
        if 'segmentation' in sliver_datap.keys():
            sliver_seg = sliver_datap['segmentation']
            sliver_seg = qmisc.uncrop(sliver_datap['segmentation'],
                                      sliver_datap['crinfo'],
                                      data3d_a.shape)
        else:
            sliver_seg = sliver_datap['data3d']

        pyed = py3DSeedEditor.py3DSeedEditor(data3d_a, contour=sliver_seg)
        print "Sliver07 segmentation"
        pyed.show()

    if ourSegmentation != None:
        ourSegmentation = os.path.join(path_to_script, ourSegmentation)
        datap_our = reader.Get3DData(ourSegmentation, dataplus_format=True)
        #data_our = misc.obj_from_file(ourSegmentation, 'pickle')
        #data3d_our = data_our['segmentation']
        our_seg = qmisc.uncrop(datap_our['segmentation'], datap_our['crinfo'],
                               data3d_a.shape)

    if ourSegmentation != None:
        pyed = py3DSeedEditor.py3DSeedEditor(data3d_a, contour=our_seg)
        print "Our segmentation"
        pyed.show()

    if (ourSegmentation is not None) and (sliver_seg_path is not None):
        diff = (our_seg.astype(np.int8) - sliver_seg)
        diff[diff==-1] = 2
        #import ipdb; ipdb.set_trace() # BREAKPOINT
        pyed = py3DSeedEditor.py3DSeedEditor(data3d_a, contour=our_seg,
                                             seeds=diff)
        print "Sliver07 and our segmentation differences"
        pyed.show()
Ejemplo n.º 6
0
    def show_segmentation(self, img = None):

        if img == None:
            img = self.segmentation

        pyed = py3DSeedEditor.py3DSeedEditor(img)
        pyed.show()
Ejemplo n.º 7
0
def one_experiment_setting_for_whole_dataset(inputdata, tile_shape,
                                             feature_fcn, classif_fcn, train,
                                             visualization=False):
    fvall = []
    fv_tiles = []
    indata_len = len(inputdata['data'])
    indata_len = 3

    for i in range(0, indata_len):
        data3d_orig, data3d_seg = read_data_orig_and_seg(inputdata, i)

        feat_hist_by_segmentation(data3d_orig, data3d_seg, visualization)

        if visualization:
            pyed = py3DSeedEditor.py3DSeedEditor(data3d_orig,
                                                 contour=data3d_seg)
            pyed.show()

            #import pdb; pdb.set_trace()
        #fvall.insert(i, get_features(
        #    data3d_orig,
            #ltl = (labels_train_lin_float * 10).astype(np.int8)
            #labels_train = arrange_to_tiled_data(cidxs, tile_shape,
            #                                     d_shp, ltl)

            #pyed = py3DSeedEditor.py3DSeedEditor(labels_train, contour=labels)

# @TODO vracet něco inteligentního, fvall je prázdný
    return fvall
Ejemplo n.º 8
0
def main():

    logger = logging.getLogger()

    logger.setLevel(logging.WARNING)
    ch = logging.StreamHandler()
    logger.addHandler(ch)

    #logger.debug('input params')

    # input parser
    parser = argparse.ArgumentParser(
            description='Module for segmentation of simple anatomical structures')
    parser.add_argument('-i', '--inputfile',
            default='organ.pkl',
            help='path to data dir')

    args = parser.parse_args()

    data = misc.obj_from_file(args.inputfile, filetype = 'pickle')
    data3d = data['data3d']
    voxelsize_mm = data['voxelsize_mm']

    ss = SimpleSegmentation()
    simple_seg = ss.simple_segmentation(data3d, voxelsize_mm)

    #visualization
    pyed = py3DSeedEditor.py3DSeedEditor(data['data3d'], seeds=simple_seg)
    pyed.show()

    # save
    savestring = raw_input('Save output data? (y/n): ')
    if savestring in ['Y', 'y']:
        misc.obj_to_file(data, "resection.pkl", filetype='pickle')
Ejemplo n.º 9
0
def resection(data):
    #pyed = py3DSeedEditor.py3DSeedEditor(data['segmentation'])
    #pyed.show()
    # vessels = get_biggest_object(data['segmentation'] == data['slab']['porta'])
    vessels = data['segmentation'] == data['slab']['porta']
# ostranění porty z více kusů, nastaví se jim hodnota liver
    #data['segmentation'][data['segmentation'] == data['slab']['porta']] = data['slab']['liver']
    #show3.show3(data['segmentation'])
    import pdb; pdb.set_trace()

    #data['segmentation'][vessels == 1] = data['slab']['porta']
    #segm = data['segmentation']
    #pyed = py3DSeedEditor.py3DSeedEditor(vessels)
    #pyed.show()
    print ("Select cut")
    lab = vessel_cut.cut_editor_old(data)
    pyed = py3DSeedEditor.py3DSeedEditor(lab )#, contour=segm)
    pyed.show()
    l1 = 1
    l2 = 2
    #import pdb; pdb.set_trace()

    # dist se tady počítá od nul jenom v jedničkách
    dist1 = scipy.ndimage.distance_transform_edt(lab != l1)
    dist2 = scipy.ndimage.distance_transform_edt(lab != l2)




    #segm = (dist1 < dist2) * (data['segmentation'] != data['slab']['none'])
    segm = (((data['segmentation'] != 0) * (dist1 < dist2)).astype('int8') + (data['segmentation'] != 0).astype('int8'))

# vizualizace 1
#    pyed = py3DSeedEditor.py3DSeedEditor(segm)
#    pyed.show()
#    import pdb; pdb.set_trace()
#    pyed = py3DSeedEditor.py3DSeedEditor(data['data3d'], contour=segm)
#    pyed.show()
#    import pdb; pdb.set_trace()

# vizualizace 2
    linie = np.abs(dist1 - dist2) < 1
    pyed = py3DSeedEditor.py3DSeedEditor(data['data3d'], contour = data['segmentation']==data['slab']['liver'] ,seeds = linie)
    pyed.show()
Ejemplo n.º 10
0
    def interactivity(self):
        """
        Interactive seed setting with 3d seed editor
        """

        pyed = py3DSeedEditor.py3DSeedEditor(self.img, 
                mouse_button_map = self.editor_mouse_button_map )
        pyed.show()

        #scipy.io.savemat(args.outputfile,{'data':output})
        #pyed.get_seed_val(1)


        # control list of non zero values in seeds
        #nzero_seeds_prev = ([],[])
        nzero_seeds = pyed.seeds.nonzero()

        pocitadlo = 0
        opakovat = True

        while opakovat:#(nzero_seeds_prev != nzero_seeds).all():
            pocitadlo = pocitadlo + 1

            self.voxels1 = pyed.get_seed_val(1)
            self.voxels2 = pyed.get_seed_val(2)
            self.seeds = pyed.seeds
            self.make_gc()

# new pyeditor is created, seeds must be setted
            pyed = py3DSeedEditor.py3DSeedEditor(self.img, seeds = self.seeds, 
                    contour = self.segmentation,
                    mouse_button_map = self.editor_mouse_button_map 
                    )

            #pyed.seeds = self.seeds

            pyed.show()

            opakovat = not np.array_equal(pyed.seeds.nonzero() , nzero_seeds)


            #opakovat =True #not all(opakovat)
            nzero_seeds = pyed.seeds.nonzero()
Ejemplo n.º 11
0
def main():

    #logger = logging.getLogger(__name__)
    logger = logging.getLogger()

    logger.setLevel(logging.WARNING)
    ch = logging.StreamHandler()
    logger.addHandler(ch)

    #logger.debug('input params')

## read confguraton from file, use default values from OrganSegmentation

    # input parser
    parser = argparse.ArgumentParser(
        description=' Show dicom data with overlay')
    parser.add_argument('-i', '--inputdatapath',
                        default='',
                        help='path to data dir')
    args_obj = parser.parse_args()
    args = vars(args_obj)
    #print args["arg"]

    reader = datareader.DataReader()
    data3d, metadata = reader.Get3DData(args['inputdatapath'], qt_app=None)
    overlays = reader.GetOverlay()
    overlay = np.zeros(data3d.shape, dtype=np.int8)
    print "overlays ", overlays.keys()
    for key in overlays:
        overlay += overlays[key]

    #import ipdb; ipdb.set_trace() # BREAKPOINT
    pyed = py3DSeedEditor.py3DSeedEditor(data3d, contour=overlay)
    pyed.show()

    #print savestring
#    import pdb; pdb.set_trace()
    return
Ejemplo n.º 12
0
    def showSegmentedData(self, data3d_thr, data3d_skel):
        skan = SkeletonAnalyser(
            data3d_skel,
            volume_data=data3d_thr,
            voxelsize_mm=self.metadata['voxelsize_mm'])
        data3d_nodes_vis = skan.sklabel.copy()
# edges
        data3d_nodes_vis[data3d_nodes_vis > 0] = 1
# nodes and terminals
        data3d_nodes_vis[data3d_nodes_vis < 0] = 2

        #pyed = seqt.QTSeedEditor(
        #    data3d,
        #    seeds=(data3d_nodes_vis).astype(np.int8),
        #    contours=data3d_thr.astype(np.int8)
        #)
        #app.exec_()
        if not self.nogui:
            pyed = se.py3DSeedEditor(
                self.data3d,
                seeds=(data3d_nodes_vis).astype(np.int8),
                contour=data3d_thr.astype(np.int8)
            )
            pyed.show()
Ejemplo n.º 13
0
    def simple_segmentation(self, data3d, voxelsize_mm):
        simple_seg = np.zeros(data3d.shape )
	#definice konvoluční masky
	KONV_MASK = np.ones([10,10,10], float)
	KONV_MASK = KONV_MASK/9.0;	
	

	#definice konvoluční funkce - param a - matice m*n kterou budeme přenásobovat konvoluční maticí, b - Konvoluční maska m*n
     
	
	# nalezení kostí
	simple_seg = data3d > BONES 
	#simple_seg[(simple_seg.shape[0]/5)*4:simple_seg.shape[0]] = 0
	
	#nalzení páteře
	spine_finder = scipy.ndimage.filters.convolve((simple_seg).astype(np.int), KONV_MASK)
	#pyed = py3DSeedEditor.py3DSeedEditor(simple_seg)
	#
				
	simple_seg += ((spine_finder>25)*SPINE_ID)
	pyed = py3DSeedEditor.py3DSeedEditor(simple_seg)
	pyed.show()	

	return simple_seg
Ejemplo n.º 14
0
    def get_seeds_using_prob_class1(self, data, class1, roi=None, dens_min=20,
                                    dens_max=255,
                                    thresholdType='percOfMaxDist', percT=0.5):
        # calculates probability based on similarity of intensities
        probs = tools.intensity_probability(data, std=10)
        # py3DSeedEditor.py3DSeedEditor(data).show()
        # py3DSeedEditor.py3DSeedEditor(probs).show()
        # normalizing and calculating reciprocal values
        # weights_ints = skexp.rescale_intensity(probs,
        # in_range=(0,probs.max()), out_range=(1,0))
        weights_ints = np.exp(-probs)
        # py3DSeedEditor.py3DSeedEditor(weights_ints).show()

        if roi is None:
            roi = np.logical_and(data >= dens_min, data <= dens_max)
        dist_data = np.where(class1 == 1, False, True)
        dist_data *= roi > 0
        # dists = distance_transform_edt(dist_data)
        # py3DSeedEditor.py3DSeedEditor(dists).show()

        # print 'dists max = %i' % dists.max()
        # print 'dists min = %i' % dists.min()
        # print 'weights_ints max = %.4f' % weights_ints.max()
        # print 'weights_ints min = %.4f' % weights_ints.min()
        # print 'probs max = %.4f' % probs.max()
        # print 'probs min = %.4f' % probs.min()

        # energy = dists * weights_ints
        energy = weights_ints
        # py3DSeedEditor.py3DSeedEditor(energy).show()

        seeds = np.zeros(data.shape, dtype=np.bool)
        if thresholdType == 'percOfMaxDist':
            seeds = energy > (percT * energy.max())
        elif thresholdType == 'mean':
            seeds = energy > 2 * (energy[np.nonzero(energy)]).mean()

        # TODO: tady je problem, ze energy je v intervalu <0.961, 1> - hrozne
        # maly rozsah
        print 'energy max = %.4f' % energy.max()
        print 'energy min = %.4f' % energy.min()
        print 'thresh = %.4f' % (percT * energy.max())
        print seeds.min()
        print seeds.max()
        print 'seed perc = %.2f' % (
            (energy > percT * energy.max()).sum()/np.float(energy.nbytes))
        py3DSeedEditor.py3DSeedEditor(seeds).show()

        # removing to small objects
        min_size_of_seed_area = 60
        print 'before removing: %i' % seeds.sum()
        seeds = skimor.remove_small_objects(
            seeds, min_size=min_size_of_seed_area, connectivity=1,
            in_place=False)
        print 'after removing: %i' % seeds.sum()

        all_seeds = np.zeros(data.shape, dtype=np.int)
        # allSeeds[np.nonzero(self.segmentation)] = 80
        all_seeds[np.nonzero(class1)] = 1  # zdrava tkan
        all_seeds[np.nonzero(seeds)] = 2  # outliers
        # kvuli segmentaci pomoci random walkera se omezi obraz pouze na
        # segmentovana jatra a cevy
        all_seeds = np.where(roi == 0, -1, all_seeds)

        py3DSeedEditor.py3DSeedEditor(all_seeds).show()

        return all_seeds
Ejemplo n.º 15
0
def eval_all_from_dataset_metadata(inputdata, visualization=False):
    """
    set metadata
    """
    evaluation_all = {
        'file1': [],
        'file2': [],
        'volume1_mm3': [],
        'volume2_mm3': [],
        'err1_mm3': [],
        'err2_mm3': [],
        'err1_percent': [],
        'err2_percent': [],
        'voe': [],
        'vd': [],
        'avgd': [],
        'rmsd': [],
        'processing_time': [],
        'organ_interactivity_counter': [],
        'maxd': []

    }
    for i in range(0, len(inputdata['data'])):

        reader = datareader.DataReader()
        data3d_a_path = os.path.join(inputdata['basedir'],
                                     inputdata['data'][i]['sliverseg'])
        data3d_a, metadata_a = reader.Get3DData(data3d_a_path)
        print "inputdata ", inputdata['data'][i].keys()
        try:
# if there is defined overlay
            data3d_a = reader.GetOverlay()[inputdata['data'][i][
                'overlay_number']]
            logger.info('overlay loaded')
            print 'overlay loaded'
        except:
            logger.debug("overlay not loaded")
            pass

        logger.debug('data A shape ' + str(data3d_a.shape))

        data3d_b_path = os.path.join(inputdata['basedir'],
                                     inputdata['data'][i]['ourseg'])
        obj_b = misc.obj_from_file(data3d_b_path, filetype='pickle')
        #data_b, metadata_b = reader.Get3DData(data3d_b_path)

        data3d_b = qmisc.uncrop(obj_b['segmentation'],
                                obj_b['crinfo'], data3d_a.shape)

        #import pdb; pdb.set_trace()
        #data3d_a = (data3d_a > 1024).astype(np.int8)
        data3d_a = (data3d_a > 0).astype(np.int8)
        data3d_b = (data3d_b > 0).astype(np.int8)

        if visualization:
            pyed = py3DSeedEditor.py3DSeedEditor(data3d_a,  # + (4 * data3d_b)
                                                 contour=data3d_b)
            pyed.show()

        evaluation_one = compare_volumes(data3d_a, data3d_b,
                                         metadata_a['voxelsize_mm'])
        evaluation_all['file1'].append(data3d_a_path)
        evaluation_all['file2'].append(data3d_b_path)
        evaluation_all['volume1_mm3'].append(evaluation_one['volume1_mm3'])
        evaluation_all['volume2_mm3'].append(evaluation_one['volume2_mm3'])
        evaluation_all['err1_mm3'].append(evaluation_one['err1_mm3'])
        evaluation_all['err2_mm3'].append(evaluation_one['err2_mm3'])
        evaluation_all['err1_percent'].append(evaluation_one['err1_percent'])
        evaluation_all['err2_percent'].append(evaluation_one['err2_percent'])
        evaluation_all['voe'].append(evaluation_one['voe'])
        evaluation_all['vd'].append(evaluation_one['vd'])
        evaluation_all['avgd'].append(evaluation_one['avgd'])
        evaluation_all['rmsd'].append(evaluation_one['rmsd'])
        evaluation_all['maxd'].append(evaluation_one['maxd'])
        if 'processing_time' in obj_b.keys():
            #this is only for compatibility with march2014 data
            processing_time = obj_b['processing_time']
            organ_interactivity_counter = obj_b['organ_interactivity_counter']
        else:
            processing_time = obj_b['processing_information']['organ_segmentation']['processing_time']  # noqa
            organ_interactivity_counter = obj_b['processing_information']['organ_segmentation']['organ_interactivity_counter']  # noqa
        evaluation_all['processing_time'].append(processing_time)
        evaluation_all['organ_interactivity_counter'].append(
            organ_interactivity_counter)

    return evaluation_all
Ejemplo n.º 16
0
    data['slab']['none'] = 0
    data['slab']['liver'] = 1
    data['slab']['porta'] = 2


    #print np.max(output)
    #import pdb; pdb.set_trace()
    #data = {}
    #data['data3d'] = oseg.data3d
    #data['crinfo'] = oseg.crinfo
    #data['segmentation'] = oseg.segmentation
    data['segmentation'][output] = data['slab']['porta']
    #data['slab'] = slab


    pyed = py3DSeedEditor.py3DSeedEditor(data['data3d'],  contour=data['segmentation']==data['slab']['porta'])
    pyed.show()

    #pyed = py3DSeedEditor.py3DSeedEditor(data['segmentation'])
    #pyed.show()
    # Uvolneni pameti
    garbage.collect()


    if args.outputfile == None:

        savestring = raw_input ('Save output data? (y/n): ')
        #sn = int(snstring)
        if savestring in ['Y','y']:
            pth, filename = os.path.split(os.path.normpath(args.inputfile))
Ejemplo n.º 17
0
    startTime = datetime.now()
    
    hr = TreeVolumeGenerator()
    hr.importFromYaml(args.inputfile)
    hr.voxelsize_mm = args.voxelsize
    hr.shape = args.datashape
    hr.generateTree()
    
    logger.info("TimeUsed:"+str(datetime.now()-startTime))
    volume_px = sum(sum(sum(hr.data3d)))
    volume_mm3 = volume_px*(hr.voxelsize_mm[0]*hr.voxelsize_mm[1]*hr.voxelsize_mm[2])
    logger.info("Volume px:"+str(volume_px))
    logger.info("Volume mm3:"+str(volume_mm3))
    
#vizualizace
    pyed = se.py3DSeedEditor(hr.data3d)
    pyed.show()
# 3d vizualizace (debug)
    if args.debug:
        try:
            from vtk_point_cloud import VtkPointCloud
            pointCloud = VtkPointCloud(None,0,51,True)
            for z in xrange(0,len(hr.data3d)):
                for y in xrange(0,len(hr.data3d[z])):
                    for x in xrange(0,len(hr.data3d[z][y])):
                        if hr.data3d[z][y][x] == 1:
                            pointCloud.addPoint([x,y,z])
            pointCloud.rander()
        except:
            logger.error("pointCloud 3d debug error: cant find vtk_point_cloud.py")
#ukládání do souboru
Ejemplo n.º 18
0
def vesselSegmentation(data, segmentation = -1, threshold = -1, voxelsize_mm = [1,1,1], inputSigma = -1, 
                       dilationIterations = 0, dilationStructure = None, nObj = 10, biggestObjects = False, 
                       seeds = None, interactivity = True, binaryClosingIterations = 2, 
                       binaryOpeningIterations = 0, smartInitBinaryOperations = True,
                       returnThreshold = False, binaryOutput = True, returnUsedData = False):

    """

    Vessel segmentation z jater.

    Input:
        data - CT (nebo MRI) 3D data
        segmentation - zakladni oblast pro segmentaci, oznacena struktura se stejnymi rozmery jako "data",
            kde je oznaceni (label) jako:
                1 jatra,
                -1 zajimava tkan (kosti, ...)
                0 jinde
        threshold - prah
        voxelsize_mm - (vektor o hodnote 3) rozmery jednoho voxelu
        inputSigma - pocatecni hodnota pro prahovani
        dilationIterations - pocet operaci dilation nad zakladni oblasti pro segmentaci ("segmantation")
        dilationStructure - struktura pro operaci dilation
        nObj - oznacuje, kolik nejvetsich objektu se ma vyhledat - pokud je rovno 0 (nule), vraci cela data
        biggestObjects - moznost, zda se maji vracet nejvetsi objekty nebo ne
        seeds - moznost zadat pocatecni body segmentace na vstupu. Je to matice o rozmerech jako data. Vsude nuly, tam kde je oznaceni jsou jednicky.
        interactivity - nastavi, zda ma nebo nema byt pouzit interaktivni mod upravy dat
        binaryClosingIterations - vstupni binary closing operations
        binaryOpeningIterations - vstupni binary opening operations
        smartInitBinaryOperations - logicka hodnota pro smart volbu pocatecnich hodnot binarnich operaci (bin. uzavreni a bin. otevreni)
        returnThreshold - jako druhy parametr funkce vrati posledni hodnotu prahu
        binaryOutput - zda ma byt vystup vracen binarne nebo ne (binarnim vystupem se rozumi: cokoliv jineho nez hodnota 0 je hodnota 1)
        returnUsedData - vrati pouzita data

    Output:
        filtrovana data

    """

    dim = numpy.ndim(data)
    logger.debug( 'Dimenze vstupnich dat: ' + str(dim))
    if (dim < 2) or (dim > 3):
        logger.debug( 'Nepodporovana dimenze dat!')
        logger.debug( 'Ukonceni funkce!')
        return None

    if seeds == None:
        logger.debug( 'Funkce spustena bez prioritnich objektu!')

    if biggestObjects:
        logger.debug( 'Funkce spustena s vracenim nejvetsich objektu => nebude mozne vybrat prioritni objekty!')

    if ( nObj < 1 ) :
        nObj = 1

    if biggestObjects:
        logger.debug( 'Vybrano objektu k vraceni: ' + str(nObj))

    logger.debug('Pripravuji data...')

    voxel = numpy.array(voxelsize_mm)

    ## Kalkulace objemove jednotky (voxel) (V = a*b*c).
    voxel1 = voxel[0]#[0]
    voxel2 = voxel[1]#[0]
    voxel3 = voxel[2]#[0]
    voxelV = voxel1 * voxel2 * voxel3

    ## number je zaokrohleny 2x nasobek objemove jednotky na 2 desetinna mista.
    ## number stanovi doporucenou horni hranici parametru gauss. filtru.
    number = (numpy.round((2 * voxelV**(1.0/3.0)), 2))

    ## Operace dilatace (dilation) nad samotnymi jatry ("segmentation").
    if(dilationIterations > 0.0):
        segmentation = scipy.ndimage.binary_dilation(input = segmentation,
            structure = dilationStructure, iterations = dilationIterations)

    ## Ziskani datove oblasti jater (bud pouze jater nebo i jejich okoli - zalezi,
    ## jakym zpusobem bylo nalozeno s operaci dilatace dat).
    preparedData = (data * (segmentation == 1))#.astype(numpy.float)
    logger.debug( 'Typ vstupnich dat: ' + str(preparedData.dtype))

#    if preparedData.dtype != numpy.uint8:
#        print 'Data nejsou typu numpy.uint8 => muze dojit k errorum'

    if not numpy.can_cast(preparedData.dtype, numpy.float):
       logger.debug( 'ERROR: (debug message) Data nejsou takoveho typu, aby se daly prevest na typ "numpy.float" => muze dojit k errorum')
       logger.debug( 'Ukoncuji funkci!')
       return None

    if (preparedData == False).all():
       logger.debug( 'ERROR: (debug message) Jsou spatna data nebo segmentacni matice: all is true == data is all false == bad segmentation matrix (if data matrix is ok)')
       logger.debug( 'Ukoncuji funkci!')
       return None

    del(data)
    del(segmentation)

    ## Nastaveni rozmazani a prahovani dat.
    if(inputSigma == -1):
        inputSigma = number
    if(inputSigma > number):
        inputSigma = number

    seeds = None
    if biggestObjects == False and seeds == None and interactivity == True and threshold==-1:

        logger.debug(('Nyni si levym nebo pravym tlacitkem mysi (klepnutim nebo tazenim) oznacte specificke oblasti k vraceni.'))
        import py3DSeedEditor
        pyed = py3DSeedEditor.py3DSeedEditor(preparedData)
        pyed.show()
        seeds = pyed.seeds

        ## Zkontrolovat, jestli uzivatel neco vybral - nejaky item musi byt ruzny od nuly.
        if (seeds != 0).any() == False:

            seeds = None
            logger.debug( 'Zadne seedy nezvoleny => nejsou prioritni objekty.')

        else:

            seeds = seeds.nonzero()#seeds * (seeds != 0) ## seeds je n-tice poli indexu nenulovych prvku => item krychle je == krychle[ seeds[0][x], seeds[1][x], seeds[2][x] ]
            logger.debug( 'Seedu bez nul: ' + str(len(seeds[0])))

    closing = binaryClosingIterations
    opening = binaryOpeningIterations

    if (smartInitBinaryOperations and interactivity):

        if (seeds == None):

            closing = 5
            opening = 1

        else:

            closing = 2
            opening = 0

    ## Samotne filtrovani.
    uiT = uiThreshold.uiThreshold(preparedData, voxel, threshold,
        interactivity, number, inputSigma, nObj, biggestObjects, closing,
        opening, seeds)
    output = uiT.run()

    ## Vypocet binarni matice.
    if output == None:

        logger.debug( 'Zadna data k vraceni! (output == None)')

    elif binaryOutput:

        output[output != 0] = 1
    
    ## Vraceni matice.
    if returnThreshold:

        if returnUsedData:

            return preparedData, output, uiT.returnLastThreshold()

        else:

            return output, uiT.returnLastThreshold()

    else:

        if returnUsedData:

            return preparedData, output

        else:

            return output
Ejemplo n.º 19
0
 def visualization(self):
     pyed = py3DSeedEditor.py3DSeedEditor(
         self.segmentation == self.data['slab']['lesions'])
     pyed.show()
Ejemplo n.º 20
0
def segmentation(data3d, segmentation, params):
    """ Texture analysis by LBP algorithm.
    data: CT (or MRI) 3D data
    segmentation: labeled image with same size as data where label:
    1 mean liver pixels,
    -1 interesting tissuse (bones)
    0 otherwise
    """
    
    MAXPATTERNS = 10

    slices = data3d.shape[2]
    data3d = data3d.astype(np.int16)
    
    params[2] = 0
    data3d = data3d * segmentation;
    data3d = sp.ndimage.filters.gaussian_filter(data3d,params*2.5)  
    pyed = py3DSeedEditor.py3DSeedEditor(data3d)
    pyed.show()
    
    lbp = lbpLib.loadLbpLibrary()    

    lbpReftmp = (ctypes.c_long * 256)()
    lbpRef = np.zeros([MAXPATTERNS,256])

    actualpatterns = 0

    # vytvoreni referencnich LBP obrazu
    for j in range(15,data3d.shape[0]-16):
        if (actualpatterns == MAXPATTERNS) :
            break
        for k in range(15,data3d.shape[1]-16): 
            if (actualpatterns == MAXPATTERNS) :
                break
            if ((pyed.seeds[j,k,pyed.actual_slice] == 1)):                
                lbpReftmp = lbpLib.realTimeLbpImNp(lbp, data3d[j-15:j+16,k-15:k+16,pyed.actual_slice])
                for z in range(256):
                    lbpRef[actualpatterns, z] = lbpReftmp[z]
                print lbpRef[actualpatterns,]
                actualpatterns += 1                   

    # uprava velikosti dat
    for i in range(20):
        h2 = data3d.shape[0] - i*16
        if (h2 <= 0):
            h2 = i*16
            break
    for i in range(20):
        w2 = data3d.shape[1] - i*16
        if (w2 <= 0):
            w2 = i*16
            break    
    # obdelnikova data prevedeme na ctverec 
    if (w2 >=  h2 ):     
        h2 = w2
    else :
        w2 = h2
    numOfPartsX = (w2) / 16
    numOfPartsY = (h2) / 16   
    minMaxData = np.zeros([h2,w2,data3d.shape[2]],dtype = np.float)
    lbpSlice = np.zeros([h2,w2])
      
    # hlavni cyklus vypocitavajici odezvy
    for i in range(slices):
        tempData = np.zeros([h2,w2],dtype = np.float)
        tempData[0:data3d.shape[0],0:data3d.shape[1]] = data3d[:,:,i].astype(np.float)   
        lbpSlice = lbpLib.realTimeLbpIm2ImNp(lbp, tempData.astype(np.int16))
        lbpRes = lbpLib.lbp2HistsNp(lbp, lbpSlice)
        for j in range(lbpRes.shape[0]):
            minmaxBestVal = 0
            for k in range(MAXPATTERNS):
                minmaxVal = minmax(lbpRes[j,:],lbpRef[k,:])
                if minmaxVal > minmaxBestVal : 
                    minmaxBestVal = minmaxVal
            minMaxData[16*(j/numOfPartsX):16*(j/numOfPartsX)+16,16*(j % numOfPartsX):16*(j % numOfPartsX)+16,i] = minmaxBestVal        

    # zobrazeni vysledku
    pyed2 = py3DSeedEditor.py3DSeedEditor(minMaxData)
    pyed2.show()

    return segmentation