Ejemplo n.º 1
0
    def buttonClicked(self):
        print("button")
        import sed3
        import sed3.sed3
        import numpy as np

        img = np.zeros([10, 10, 15])
        img[6:9, 2:7, 1:5] = 1
        img[7:9, 3:9, 8:14] = 2

        ed = sed3.sed3qt(img)
        # ed.set_params(img)

        if ed.exec_():
            print("konec edu")
            vals = ed.o
            print(vals.seeds)


        print(np.nonzero(ed.seeds))
        # ed = sed3.sed3(img)
        # ed.sed3_on_close = self.callback_close
        # ed.show()

        print("konec sed3")
Ejemplo n.º 2
0
def show(data3dw):
    data3d = data3dw.datap["data3d"]
    import sed3
    ed = sed3.sed3qt(data3d)
    # ed = sed3.se
    # ed.show()
    ed.exec_()
Ejemplo n.º 3
0
    def compareSegmentationWithFile(self):
        """
        Function make GUI for reading segmentaion file to compare it with
        actual segmentation using Sliver methodics. It calls
        organ_segmentation function to do the work.
        """
        self.statusBar().showMessage('Reading segmentation from file ...')
        QApplication.processEvents()
        logger.debug("import segmentation from file to compare by sliver")
        logger.debug(str(self.oseg.crinfo))
        logger.debug(str(self.oseg.data3d.shape))
        logger.debug(str(self.oseg.segmentation.shape))
        if 'loadcomparedir' in self.oseg.cache.data.keys():
            directory = self.oseg.cache.get('loadcomparedir')
        else:
            directory = self.oseg.input_datapath_start
        #
        seg_path = self.__get_datafile(
            app=True,
            directory=directory
        )
        if seg_path is None:
            self.statusBar().showMessage('No data path specified!')
            return
        evaluation, segdiff = \
            self.oseg.sliver_compare_with_other_volume_from_file(seg_path)
        print 'Evaluation: ', evaluation
        # print 'Score: ', score

        text = self.__evaluation_to_text(evaluation)

        segdiff[segdiff == -1] = 2
        logger.debug('segdif unique ' + str(np.unique(segdiff)))

        QApplication.processEvents()
        try:

            ed = sed3.sed3qt(
                self.oseg.data3d,
                seeds=segdiff,
                # contour=(self.oseg.segmentation == self.oseg.slab['liver'])
                contour=self.oseg.segmentation
            )
            ed.exec_()
        except:
            ed = sed3.sed3(
                self.oseg.data3d,
                seeds=segdiff,
                contour=(self.oseg.segmentation == self.oseg.slab['liver'])
            )
            ed.show()

        head, teil = os.path.split(seg_path)
        self.oseg.cache.update('loadcompatext_seg_dataredir', head)
        self.setLabelText(self.segBody.lblSegData, text)
        self.statusBar().showMessage('Ready')
Ejemplo n.º 4
0
    def compareSegmentationWithFile(self):
        """
        Function make GUI for reading segmentaion file to compare it with
        actual segmentation using Sliver methodics. It calls
        organ_segmentation function to do the work.
        """
        self.statusBar().showMessage('Reading segmentation from file ...')
        QApplication.processEvents()
        logger.debug("import segmentation from file to compare by sliver")
        logger.debug(str(self.oseg.crinfo))
        logger.debug(str(self.oseg.data3d.shape))
        logger.debug(str(self.oseg.segmentation.shape))
        if 'loadcomparedir' in self.oseg.cache.data.keys():
            directory = self.oseg.cache.get('loadcomparedir')
        else:
            directory = self.oseg.input_datapath_start
        #
        seg_path = self.__get_datafile(
            app=True,
            directory=directory
        )
        if seg_path is None:
            self.statusBar().showMessage('No data path specified!')
            return
        evaluation, segdiff = \
            self.oseg.sliver_compare_with_other_volume_from_file(seg_path)
        print 'Evaluation: ', evaluation
        # print 'Score: ', score

        text = self.__evaluation_to_text(evaluation)

        segdiff[segdiff == -1] = 2
        logger.debug('segdif unique ' + str(np.unique(segdiff)))

        QApplication.processEvents()
        try:

            ed = sed3.sed3qt(
                self.oseg.data3d,
                seeds=segdiff,
                # contour=(self.oseg.segmentation == self.oseg.slab['liver'])
                contour=self.oseg.segmentation
            )
            ed.exec_()
        except:
            ed = sed3.sed3(
                self.oseg.data3d,
                seeds=segdiff,
                contour=(self.oseg.segmentation == self.oseg.slab['liver'])
            )
            ed.show()

        head, teil = os.path.split(seg_path)
        self.oseg.cache.update('loadcomparedir', head)
        # self.setLabelText(self.text_seg_data, text)
        self.statusBar().showMessage('Ready')
Ejemplo n.º 5
0
def virtual_resection_visualization(data, segm, dist1, dist2, cut,
                                    interactivity=True):
    v1, v2 = liver_spit_volume_mm3(segm, data['voxelsize_mm'])

    if interactivity:
        print("Liver volume: %.4g l" % ((v1 + v2) * 1e-6))
        print("volume1: %.4g l  (%.3g %%)" % (
            (v1) * 1e-6, 100 * v1 / (v1 + v2)))
        print("volume2: %.4g l  (%.3g %%)" % (
            (v2) * 1e-6, 100 * v2 / (v1 + v2)))

    # pyed = sed3.sed3(segm)
    # pyed.show()
    # import pdb; pdb.set_trace()
    linie = (((data['segmentation'] != 0) *
              (np.abs(dist1 - dist2) < 1))).astype(np.int8)
    linie_vis = 2 * linie
    linie_vis[cut == 1] = 1
    linie_vis = linie_vis.astype(np.int8)
    if interactivity:
        pyed = sed3.sed3qt(
            data['data3d'],
            seeds=linie_vis,
            contour=(data['segmentation'] != 0))
        # pyed.show()
        pyed.exec_()

    # import pdb; pdb.set_trace()

    # show3.show3(data['segmentation'])

    slab = {
        'liver': 1,
        'porta': 2,
        'resected_liver': 3,
        'resected_porta': 4}

    slab.update(data['slab'])

    data['slab'] = slab

    data['slab']['resected_liver'] = 3
    data['slab']['resected_porta'] = 4

    mask_resected_liver = (
        (segm == 1) & (data['segmentation'] == data['slab']['liver']))
    mask_resected_porta = (
        (segm == 1) & (data['segmentation'] == data['slab']['porta']))

    data['segmentation'][mask_resected_liver] = \
        data['slab']['resected_liver']
    data['segmentation'][mask_resected_porta] = \
        data['slab']['resected_porta']

    logger.debug('resection_old() end')
    return data
Ejemplo n.º 6
0
def virtual_resection_visualization(data, segm, dist1, dist2, cut,
                                    interactivity=True):
    v1, v2 = liver_spit_volume_mm3(segm, data['voxelsize_mm'])

    if interactivity:
        print("Liver volume: %.4g l" % ((v1 + v2) * 1e-6))
        print("volume1: %.4g l  (%.3g %%)" % (
            (v1) * 1e-6, 100 * v1 / (v1 + v2)))
        print("volume2: %.4g l  (%.3g %%)" % (
            (v2) * 1e-6, 100 * v2 / (v1 + v2)))

    # pyed = sed3.sed3(segm)
    # pyed.show()
    # import pdb; pdb.set_trace()
    linie = (((data['segmentation'] != 0) *
              (np.abs(dist1 - dist2) < 1))).astype(np.int8)
    linie_vis = 2 * linie
    linie_vis[cut == 1] = 1
    linie_vis = linie_vis.astype(np.int8)
    if interactivity:
        pyed = sed3.sed3qt(
            data['data3d'],
            seeds=linie_vis,
            contour=(data['segmentation'] != 0))
        # pyed.show()
        pyed.exec_()

    # import pdb; pdb.set_trace()

    # show3.show3(data['segmentation'])

    slab = {
        'liver': 1,
        'porta': 2,
        'resected_liver': 3,
        'resected_porta': 4}

    slab.update(data['slab'])

    data['slab'] = slab

    data['slab']['resected_liver'] = 3
    data['slab']['resected_porta'] = 4

    mask_resected_liver = (
        (segm == 1) & (data['segmentation'] == data['slab']['liver']))
    mask_resected_porta = (
        (segm == 1) & (data['segmentation'] == data['slab']['porta']))

    data['segmentation'][mask_resected_liver] = \
        data['slab']['resected_liver']
    data['segmentation'][mask_resected_porta] = \
        data['slab']['resected_porta']

    logger.debug('resection_old() end')
    return data
Ejemplo n.º 7
0
def cut_editor_old(data, label=None):
    logger.debug("editor input label: " + str(label))

    if label is None:
        contour=data['segmentation']
    else:
        if type(label) == str:
            label = data['slab'][label]
        contour=(data['segmentation'] == label).astype(np.int8)
    pyed = sed3.sed3qt(data['data3d'], contour=contour)
    pyed.exec_()

    return pyed.seeds
Ejemplo n.º 8
0
def cut_editor_old(data, label=None):
    logger.debug("editor input label: " + str(label))

    if label is None:
        contour = data['segmentation']
    else:
        if type(label) == str:
            label = data['slab'][label]
        contour = (data['segmentation'] == label).astype(np.int8)
    pyed = sed3.sed3qt(data['data3d'], contour=contour)
    pyed.exec_()

    return pyed.seeds
def vesselSegmentation(data,
                       segmentation=-1,
                       threshold=None,
                       voxelsize_mm=[1, 1, 1],
                       inputSigma=-1,
                       aoi_dilation_iterations=0,
                       aoi_dilation_structure=None,
                       nObj=10,
                       biggestObjects=False,
                       useSeedsOfCompactObjects=False,
                       seeds=None,
                       interactivity=True,
                       binaryClosingIterations=2,
                       binaryOpeningIterations=0,
                       smartInitBinaryOperations=False,
                       returnThreshold=False,
                       binaryOutput=True,
                       returnUsedData=False,
                       qapp=None,
                       auto_method='',
                       aoi_label=1,
                       forbidden_label=None,
                       slab=None,
                       old_gui=False,
                       debug=False):
    """

    Vessel segmentation z jater.

    Input:
        :param data: - CT (nebo MRI) 3D data
        :param segmentation: - zakladni oblast pro segmentaci, oznacena struktura se
        :param stejnymi: rozmery jako "data",
            kde je oznaceni (label) jako:
                1 jatra,
                -1 zajimava tkan (kosti, ...)
                0 jinde
        :param threshold: - prah
        :param voxelsize_mm: - (vektor o hodnote 3) rozmery jednoho voxelu
        :param inputSigma: - pocatecni hodnota pro prahovani
        :param aoi_dilation_iterations: - pocet operaci dilation nad zakladni oblasti pro
            segmentaci ("segmantation")
        :param aoi_dilation_structure: - struktura pro operaci dilation
        :param nObj: - oznacuje, kolik nejvetsich objektu se ma vyhledat - pokud je
            rovno 0 (nule), vraci cela data
        :param biggestObjects: - moznost, zda se maji vracet nejvetsi objekty nebo ne
        :param seeds: - moznost zadat pocatecni body segmentace na vstupu. Je to matice
            o rozmerech jako data. Vsude nuly, tam kde je oznaceni jsou jednicky
               It can be same shape like data, or it can be
               indexes e.g. from np.nonzero(seeds)
        :param interactivity: - nastavi, zda ma nebo nema byt pouzit interaktivni mod
            upravy dat
        :param binaryClosingIterations: - vstupni binary closing operations
        :param binaryOpeningIterations: - vstupni binary opening operations
        :param smartInitBinaryOperations: - logicka hodnota pro smart volbu pocatecnich
            hodnot binarnich operaci (bin. uzavreni a bin. otevreni)
        :param returnThreshold: - jako druhy parametr funkce vrati posledni hodnotu
            prahu
        :param binaryOutput: - zda ma byt vystup vracen binarne nebo ne (binarnim
            vystupem se rozumi: cokoliv jineho nez hodnota 0 je hodnota 1)
        :param returnUsedData: - vrati pouzita data
        :param aoi_label: label of organ where is the target vessel
        :param forbidden_label: int or list of ints. Labels of areas which are not used for segmentation.

    Output:
        filtrovana data

    """
    # self.qapp = qapp

    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 is 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))

    if aoi_label is None:
        target_organ_segmentation = np.ones(segmentation.shape)
    else:
        target_organ_segmentation = image_manipulation.select_labels(
            segmentation, aoi_label, slab)
    # Operace dilatace (dilation) nad samotnymi jatry ("segmentation").
    if (aoi_dilation_iterations > 0.0):
        target_organ_segmentation = scipy.ndimage.binary_dilation(
            input=target_organ_segmentation,
            structure=aoi_dilation_structure,
            iterations=aoi_dilation_iterations)

    # remove forbidden areas from segmentation
    if forbidden_label is not None:
        forbidden_organ_segmentation = image_manipulation.select_labels(
            segmentation, forbidden_label, slab)
        target_organ_segmentation[forbidden_organ_segmentation] = 0
        del (forbidden_organ_segmentation)

    # Ziskani datove oblasti jater (bud pouze jater nebo i jejich okoli -
    # zalezi, jakym zpusobem bylo nalozeno s operaci dilatace dat).

    preparedData = (data * (target_organ_segmentation))  # .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!')
        raise ValueError("Cannot cast input data to numpy.float")
        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!')
        raise ValueError(
            "Wrong input data. All is true == data is all false == bad segmentation matrix (if data matrix is ok)"
        )
        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 is None and interactivity == True and threshold is None:
        if old_gui:

            logger.debug((
                'Nyni si levym nebo pravym tlacitkem mysi (klepnutim nebo tazenim)\
     oznacte specificke oblasti k vraceni.'))

            import sed3
            pyed = sed3.sed3qt(preparedData,
                               contour=segmentation,
                               windowW=400,
                               windowC=50)
            # pyed.show()
            pyed.exec_()

            # from PyQt4.QtCore import pyqtRemoveInputHook
            # pyqtRemoveInputHook()
            # import ipdb; ipdb.set_trace() #  noqa BREAKPOINT

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

    closing = binaryClosingIterations
    opening = binaryOpeningIterations

    if (smartInitBinaryOperations and interactivity):

        if (seeds == None):  # noqa

            closing = 5
            opening = 1

        else:

            closing = 2
            opening = 0

    # Samotne filtrovani
    if interactivity:
        if old_gui:
            uiT = uiThreshold.uiThresholdQt(
                preparedData,
                voxel=voxel,
                threshold=threshold,
                interactivity=interactivity,
                number=number,
                inputSigma=inputSigma,
                nObj=nObj,
                biggestObjects=biggestObjects,
                useSeedsOfCompactObjects=useSeedsOfCompactObjects,
                binaryClosingIterations=closing,
                binaryOpeningIterations=opening,
                seeds=seeds,
                threshold_auto_method=auto_method,
            )

            output = uiT.run()
        else:
            # TODO use all parameters
            import seededitorqt

            se = seededitorqt.QTSeedEditor(preparedData, voxelSize=voxel)
            import imtools.threshold_qsed_plugin
            wg0 = imtools.threshold_qsed_plugin.QtSEdThresholdPlugin(
                nObj=nObj, debug=debug)
            se.addPlugin(wg0)
            se.exec_()
            output = se.getContours()

    else:
        uiT = uiThreshold.uiThreshold(
            preparedData,
            voxel=voxel,
            threshold=threshold,
            interactivity=interactivity,
            number=number,
            inputSigma=inputSigma,
            nObj=nObj,
            biggestObjects=biggestObjects,
            useSeedsOfCompactObjects=useSeedsOfCompactObjects,
            binaryClosingIterations=closing,
            binaryOpeningIterations=opening,
            seeds=seeds,
            threshold_auto_method=auto_method,
        )
        output = uiT.run()

    # Vypocet binarni matice.
    if output is None:  # noqa

        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.º 10
0
def cut_editor_old(data):

    pyed = sed3.sed3qt(data['data3d'], contour=data['segmentation'])
    pyed.exec_()

    return pyed.seeds
Ejemplo n.º 11
0
def cut_editor_old(data):

    pyed = sed3.sed3qt(data['data3d'], contour=data['segmentation'])
    pyed.exec_()

    return pyed.seeds