Ejemplo n.º 1
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 = sed3.sed3(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 = sed3.sed3(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 = sed3.sed3(data3d_a, contour=our_seg,
                                             seeds=diff)
        print "Sliver07 and our segmentation differences"
        pyed.show()
Ejemplo n.º 2
0
def main():

    parser = argparse.ArgumentParser(
        description=__doc__)  # 'Simple VTK Viewer')

    parser.add_argument('-i', '--inputfile', default=None, help='File as .pkl')
    parser.add_argument('-o',
                        '--outputfile',
                        default=None,
                        help='Output file. Filetype is given by extension.')

    parser.add_argument('-k',
                        '--key',
                        default='data3d',
                        help='Which key should be writen to output file. \
                        Default is "data3d". You can use "segmentation"')
    args = parser.parse_args()
    data = misc.obj_from_file(args.inputfile, filetype='pickle')
    data3d_uncrop = qmisc.uncrop(data[args.key], data['crinfo'],
                                 data['orig_shape'])
    #import ipdb; ipdb.set_trace() # BREAKPOINT
    import SimpleITK as sitk
    sitk_img = sitk.GetImageFromArray(data3d_uncrop.astype(np.uint16),
                                      isVector=True)
    sitk.WriteImage(sitk_img, args.outputfile)
    print(
        "Warning: .mhd and .raw format has corupted metadta. You can edit it manually."
    )
Ejemplo n.º 3
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 = sed3.sed3(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 = sed3.sed3(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 = sed3.sed3(data3d_a, contour=our_seg, seeds=diff)
        print("Sliver07 and our segmentation differences")
        pyed.show()
Ejemplo n.º 4
0
    def test_crop_and_uncrop(self):
        shape = [10, 10, 5]
        img_in = np.random.random(shape)

        crinfo = [[2, 8], [3, 9], [2, 5]]

        img_cropped = qmisc.crop(img_in, crinfo)

        img_uncropped = qmisc.uncrop(img_cropped, crinfo, shape)

        self.assertTrue(img_uncropped[4, 4, 3] == img_in[4, 4, 3])
Ejemplo n.º 5
0
    def sliver_compare_with_other_volume(self, segmentation_datap):
        """
        Compares actual Lisa data with other which are given by
        segmentation_datap. That means
        segmentation_datap = {
            'segmentation': 3d np.array,
            'crinfo': information about crop (optional)
            }

        """
        # if there is no segmentation, data can be stored in data3d. It is the
        # way how are data stored in sliver.
        if 'segmentation' in segmentation_datap.keys():
            segm_key = 'segmentation'
        else:
            segm_key = 'data3d'
        if 'crinfo' in segmentation_datap.keys():
            data3d_segmentation = qmisc.uncrop(
                segmentation_datap[segm_key],
                segmentation_datap['crinfo'],
                self.orig_shape)
        else:
            data3d_segmentation = segmentation_datap[segm_key]
        pass

        # now we can uncrop actual Lisa data
        data3d_segmentation_actual = qmisc.uncrop(
            self.segmentation,
            self.crinfo,
            self.orig_shape)

        evaluation = volumetry_evaluation.compare_volumes(
            data3d_segmentation_actual,
            data3d_segmentation,
            self.voxelsize_mm
            )
        score = volumetry_evaluation.sliver_score_one_couple(evaluation)
        segdiff = qmisc.crop(
            ((data3d_segmentation) - data3d_segmentation_actual),
            self.crinfo)
        return evaluation, score, segdiff
Ejemplo n.º 6
0
def saveOverlayToDicomCopy(input_dcmfilelist, output_dicom_dir, overlays,
                           crinfo, orig_shape):
    """ Save overlay to dicom. """
    import datawriter as dwriter

    if not os.path.exists(output_dicom_dir):
        os.mkdir(output_dicom_dir)

    # uncrop all overlays
    for key in overlays:
        overlays[key] = qmisc.uncrop(overlays[key], crinfo, orig_shape)

    dw = dwriter.DataWriter()
    dw.DataCopyWithOverlay(input_dcmfilelist, output_dicom_dir, overlays)
Ejemplo n.º 7
0
    def get_model(self, crinfo, image_shape):
        """
        :param image_shape: Size of output image
        :param crinfo: Array with min and max index of object for each axis.
        [[minx, maxx], [miny, maxy], [minz, maxz]]

        """
        # Průměrování
        mdl = self.model / self.data_number
        print(mdl.shape)
        print(crinfo)
        # mdl_res = io3d.misc.resize_to_shape(mdl, crinfo[0][]
        uncr = qmisc.uncrop(mdl, crinfo, image_shape, resize=True)
        return uncr
Ejemplo n.º 8
0
def saveOverlayToDicomCopy(input_dcmfilelist, output_dicom_dir, overlays,
                           crinfo, orig_shape):
    """ Save overlay to dicom. """
    import datawriter as dwriter

    if not os.path.exists(output_dicom_dir):
        os.mkdir(output_dicom_dir)

    # uncrop all overlays
    for key in overlays:
        overlays[key] = qmisc.uncrop(overlays[key], crinfo, orig_shape)

    dw = dwriter.DataWriter()
    dw.DataCopyWithOverlay(input_dcmfilelist, output_dicom_dir, overlays)
Ejemplo n.º 9
0
    def get_model(self, crinfo, image_shape):
        """
        :param image_shape: Size of output image
        :param crinfo: Array with min and max index of object for each axis.
        [[minx, maxx], [miny, maxy], [minz, maxz]]

        """
        # Průměrování
        mdl = self.model / self.data_number
        print mdl.shape
        print crinfo
        # mdl_res = qmisc.resize_to_shape(mdl, crinfo[0][]
        uncr = qmisc.uncrop(mdl, crinfo, image_shape, resize=True)
        return uncr
Ejemplo n.º 10
0
    def test_multiple_crop_and_uncrop(self):
        """
        test combination of multiple crop
        """

        shape = [10, 10, 5]
        img_in = np.random.random(shape)

        crinfo1 = [[2, 8], [3, 9], [2, 5]]
        crinfo2 = [[2, 5], [1, 4], [1, 2]]

        img_cropped = qmisc.crop(img_in, crinfo1)
        img_cropped = qmisc.crop(img_cropped, crinfo2)

        crinfo_combined = qmisc.combinecrinfo(crinfo1, crinfo2)

        img_uncropped = qmisc.uncrop(img_cropped, crinfo_combined, shape)

        self.assertTrue(img_uncropped[4, 4, 3] == img_in[4, 4, 3])
Ejemplo n.º 11
0
def main():

    parser = argparse.ArgumentParser(description=__doc__) # 'Simple VTK Viewer')

    parser.add_argument('-i','--inputfile', default=None,
                      help='File as .pkl')
    parser.add_argument('-o','--outputfile', default=None,
                      help='Output file. Filetype is given by extension.')

    parser.add_argument('-k','--key', default='data3d',
                      help='Which key should be writen to output file. \
                        Default is "data3d". You can use "segmentation"')
    args = parser.parse_args()
    data = misc.obj_from_file(args.inputfile, filetype = 'pickle')
    data3d_uncrop = qmisc.uncrop(data[args.key], data['crinfo'], data['orig_shape'])
    #import ipdb; ipdb.set_trace() # BREAKPOINT
    import SimpleITK as sitk
    sitk_img = sitk.GetImageFromArray(data3d_uncrop.astype(np.uint16), isVector=True)
    sitk.WriteImage(sitk_img, args.outputfile)
    print "Warning: .mhd and .raw format has corupted metadta. You can edit it manually."
Ejemplo n.º 12
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.º 13
0
def eval_all_from_dataset_metadata(inputdata, visualization=False,
                                   special_evaluation_function=None):
    """
    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].values()
        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)

        if 'crinfo' in obj_b.keys():
            data3d_b = qmisc.uncrop(obj_b['segmentation'],
                                    obj_b['crinfo'], data3d_a.shape)
        else:
            data3d_b = obj_b['segmentation']

        # 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 = sed3.sed3(data3d_a,  # + (4 * data3d_b)
                             contour=data3d_b)
            pyed.show()

        evaluation_one = compare_volumes(data3d_a, data3d_b,
                                         metadata_a['voxelsize_mm'])
        if special_evaluation_function is not None:
            evaluation_one.update(
                special_evaluation_function(
                    data3d_a, data3d_b, metadata_a['voxelsize_mm']
                ))
        evaluation_all['file1'].append(data3d_a_path)
        evaluation_all['file2'].append(data3d_b_path)
        for key in evaluation_one.keys():
            if key not in evaluation_all.keys():
                evaluation_all[key] = []

            evaluation_all[key].append(evaluation_one[key])
        # 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:
            try:
                processing_time = obj_b['processing_information']['organ_segmentation']['processing_time']  # noqa
                organ_interactivity_counter = obj_b['processing_information']['organ_segmentation'][
                    'organ_interactivity_counter']  # noqa
            except:
                processing_time = 0
                organ_interactivity_counter = 0
        evaluation_all['processing_time'].append(processing_time)
        evaluation_all['organ_interactivity_counter'].append(
            organ_interactivity_counter)

    return evaluation_all
Ejemplo n.º 14
0
def resection_portal_vein_new(data,
                              interactivity=False,
                              seeds=None,
                              label=10,
                              vein=6,
                              **kwargs):
    """
    New function for portal vein segmentation
    :param data:
    :param interactivity:
    :param seeds:
    :param kwargs:
    :return:
    """
    # ed = sed3.sed3(a)
    # ed.show()

    # from PyQt4 import QtGui
    # from PyQt4.QtGui import QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QFrame, \
    # QFont, QPixmap, QFileDialog
    #
    # window = QtGui.QWidget()
    # mainLayout = QVBoxLayout()
    # window.setLayout(mainLayout)
    # mainLayout.addWidget(sed3.sed3qtWidget(data['data3d'], contour=data['segmentation']))

    # zachovani puvodnich dat
    segmentation = data["segmentation"]
    data3d = data["data3d"]

    # data pouze se segmentacemi
    segm = ((data["segmentation"] == label) * label +
            (data["segmentation"] == vein) * vein)

    # ufiknutí segmentace
    crinfo = qmisc.crinfo_from_specific_data(segm, [0])
    data["segmentation"] = qmisc.crop(segm, crinfo)
    data["data3d"] = qmisc.crop(data3d, crinfo)

    # @TODO zde nahradit střeve čímkoliv smysluplnějším
    if interactivity:
        print("Select cut")
        # seeds = cut_editor_old(data)
        seeds = cut_editor_old(data)
    elif seeds is None:
        logger.error('seeds is None and interactivity is False')
        return None

    lab, cut = split_vessel(data, seeds)
    segm, dist1, dist2 = split_organ_by_two_vessels(data, lab)

    # jatra rozdeleny na 3 kusy
    a = morphology.label(segm, background=0)
    ### podmínka nefunguje
    if 3 in a:  # zda se v segmentaci objevuje 3. cast
        print "slape :) :) :P"
        a_index = velikosti(segm)
        print a_index
        i = nejnizsi(a_index[0], a_index[1], a_index[2])
        segm = ((a == i) * (segm == 1).astype('int8') + (a != i) *
                (segm == 2).astype('int8') + (segm != 0).astype('int8'))

    # TODO split this function from visualization
    data = virtual_resection_visualization(data,
                                           segm,
                                           dist1,
                                           dist2,
                                           cut,
                                           interactivity=interactivity)

    # vrácení původních dat a spojení s upravenými daty
    data["data3d"] = data3d
    data["segmentation"] = qmisc.uncrop(
        data["segmentation"], crinfo,
        (len(segmentation), len(segmentation[0]), len(segmentation[0])))

    #segmentation = segmentation == vein
    data["segmentation"] = (
        data["segmentation"] +
        (segmentation != label) * segmentation) - (segmentation == vein) * vein
    return data