Пример #1
0
    def test_training(self):
        sample_data_path = lisa.dataset.sample_data_path()
        organ_localizator.train_liver_localizator_from_sliver_data(
            "liver.ol.p",
            sliver_reference_dir=sample_data_path,
            orig_pattern="*orig*001.mhd",
            ref_pattern="*seg*001.mhd",
        )

        ol = organ_localizator.OrganLocalizator()
        ol.load("liver.ol.p")

        dr = io3d.DataReader()
        data3d, metadata = dr.Get3DData(
            op.join(sample_data_path, 'liver-orig001.mhd'))
        out = ol.predict(data3d, metadata['voxelsize_mm'])

        seg, metadata = dr.Get3DData(
            op.join(sample_data_path, 'liver-seg001.mhd'))

        err = np.sum(np.abs(seg - out))
        # import sed3
        # sed3.show_slices(out-seg, out-seg, slice_step=20)
        # self.assertEqual(True, False)
        # less then 10% error expected
        self.assertGreater(np.prod(seg.shape) * 0.1, err)
Пример #2
0
    def test_trainin_kidney_from_pklz(self):

        sample_data_path = lisa.dataset.join_sdp("kidney_training/")
        test_data = lisa.dataset.join_sdp(
            "kidney_training/liver-orig001.mhd.pklz")
        label = "left kidney"

        organ_model.train_organ_model_from_dir("left_kidney.ol.p",
                                               reference_dir=sample_data_path,
                                               orig_pattern="*orig*.pklz",
                                               ref_pattern="*orig*.pklz",
                                               label=label,
                                               segmentation_key=True)

        ol = organ_localizator.OrganLocalizator()
        ol.load("left_kidney.ol.p")

        dr = io3d.DataReader()
        data3d, metadata = dr.Get3DData(test_data)
        out = ol.predict(data3d, metadata['voxelsize_mm'])

        seg = (metadata["segmentation"] == metadata['slab'][label]).astype(
            np.int8)

        err = np.sum(np.abs(seg - out))
        import sed3
        sed3.show_slices(out - seg, out - seg, slice_step=20)
        # self.assertEqual(True, False)
        # less then 10% error expected
        self.assertGreater(np.prod(seg.shape) * 0.1, err)
Пример #3
0
def annotate2(number_of_scans):  #annotation starting from scan 1
    '''
    Annotate the data form our medical dataset, starting from scan 1, up to scan passed in param.
    
    Save the labels to an excel file 'tabulka2.xlsx'.
    '''
    df = pd.DataFrame(columns=[
        'ID', 'Mark 1 slice id', 'Mark 2 slice id', 'Mark 3 slice id',
        'Mark 4 slice id'
    ])

    for i in range(number_of_scans):
        print(f'Showing scan n. {str(i+1).zfill(2)}')
        dr = io3d.DataReader()

        datap = dr.Get3DData(
            f'data/medical/orig/sliver07/training/liver-orig0{str(i+1).zfill(2)}.mhd',
            dataplus_format=True)

        ed = sed3.sed3(datap['data3d'][::-1, :, :], windowW=400, windowC=40)
        ed.show()

        nz = np.nonzero(ed.seeds)

        ids = np.unique(nz[0])
        df = df.append(
            {
                'ID': i + 1,
                'Mark 1 slice id': ids[0],
                'Mark 2 slice id': ids[1],
                'Mark 3 slice id': ids[2],
                'Mark 4 slice id': ids[3]
            },
            ignore_index=True)
    df.to_excel('tabulka2.xlsx', sheet_name='List1', index=False)
Пример #4
0
def annotate(number_of_scans):  #annotation starting from scan 1
    '''
    Annotate the data form 3DIrcad1 dataset, starting from scan 1, up to scan passed in param.
    
    Save the labels to an excel file 'tabulka.xlsx'.
    '''
    df = pd.DataFrame(columns=[
        'Ircad ID', 'Mark 1 slice id', 'Mark 2 slice id', 'Mark 3 slice id',
        'Mark 4 slice id'
    ])

    for i in range(number_of_scans):
        dr = io3d.DataReader()
        pth = io3d.datasets.join_path('medical/orig/3Dircadb1.{}/'.format(i +
                                                                          1),
                                      get_root=True)
        datap = dr.Get3DData(pth + "PATIENT_DICOM/", dataplus_format=True)
        datap_labelled = dr.Get3DData(pth + 'MASKS_DICOM/liver',
                                      dataplus_format=True)

        ed = sed3.sed3(datap['data3d'],
                       contour=datap_labelled['data3d'],
                       windowW=400,
                       windowC=40)
        ed.show()

        nz = np.nonzero(ed.seeds)
        ids = np.unique(nz[0])
        order = input("Did liver end before kidney started? (y/n)")
        if order == "y":
            df = df.append(
                {
                    'Ircad ID': i + 1,
                    'Mark 1 slice id': ids[0],
                    'Mark 2 slice id': ids[1],
                    'Mark 3 slice id': ids[2],
                    'Mark 4 slice id': ids[3]
                },
                ignore_index=True)
        elif order == "n":
            df = df.append(
                {
                    'Ircad ID': i + 1,
                    'Mark 1 slice id': ids[0],
                    'Mark 2 slice id': ids[2],
                    'Mark 3 slice id': ids[1],
                    'Mark 4 slice id': ids[3]
                },
                ignore_index=True)
        else:
            print("ERROR")
            break
    df.to_excel('tabulka.xlsx', sheet_name='List1', index=False)
Пример #5
0
def differencing(path, res, axis):
    sez = list()
    teacher = list()
    dr = io3d.DataReader()
    datap = dr.Get3DData(path, dataplus_format=True)
    ed = sed3.sed3(datap['data3d'])
    datap['data3d'] = misc.resize_to_shape(datap['data3d'], [datap['data3d'].shape[0],100,100])
    ed.show()

    try:
        under = np.where(ed.seeds == 1)[0][0]
    except:
        under = None
    try:
        over = np.where(ed.seeds == 3)[0][0]
    except:
        over = None
    number_of_slice = np.shape(ed.seeds)[0]
    c = list()
    if under is None and over is None:
        return [],[]
    elif under is None or over is None:
        print u'byla zadana jenom jedna mez zadejte obe nebo zadnou'
        w, y = differencing(path, res)
        return w, y
    if over > under:
        c = [1 for i in range(under)]
        b = [2 for i in range(over-under)]
        c.extend(b)
        b = [3 for i in range(number_of_slice-over)]
        c.extend(b)
    else:
        c = [3 for i in range(over)]
        b = [2 for i in range(under - over)]
        c.extend(b)
        b = [1 for i in range(number_of_slice - under)]
        c.extend(b)
        over, under = under, over
    for i in range(number_of_slice):
        a = datap['data3d'][i,:,:]
        x = c[i]
        teacher.append(x)
        sez.append(a)

    return sez, teacher, under, over
Пример #6
0
    def test_automatickyTest(self):
        ''' nacte prvni dva soubory koncici .mhd z adresare sample_data
        prvni povazuje za originalni a provede na nem segmentaci defaultni
        metodou z liver_segmentation. Pote nacte druhy a povazuje jej za
        rucni segmentaci, na vysledku a rucni provede srovnani a podle
        vysledku vypise verdikt na konzoli'''

        import io3d

        logger.setLevel(
            logging.DEBUG)  #ZDE UPRAVIT POKUD NECHCETE VSECHNY VYPISY

        # path_to_script = os.path.dirname(os.path.abspath(__file__))
        # # print path_to_script
        # b = path_to_script[0:-5]
        # b = b + 'sample_data'
        cesta = lisa.dataset.sample_data_path()

        logger.info('probiha nacitani souboru z adresare sample_data')
        seznamSouboru = liver_segmentation.vyhledejSoubory(cesta)
        reader = io3d.DataReader()
        vektorOriginal = liver_segmentation.nactiSoubor(
            cesta, seznamSouboru, 0, reader)
        originalPole = vektorOriginal[0]
        originalVelikost = vektorOriginal[1]
        logger.info('***zahajeni segmentace***')
        vytvoreny = liver_segmentation.LiverSegmentation(
            originalPole, originalVelikost)
        #vytvoreny.setCisloMetody(2)
        vytvoreny.run()
        segmentovany = vytvoreny.segmentation
        segmentovanyVelikost = vytvoreny.voxelSize
        logger.info(
            'segmentace dokoncena, nacitani rucni segmentace z adresare sample_data'
        )
        vektorOriginal = liver_segmentation.nactiSoubor(
            cesta, seznamSouboru, 1, reader)
        rucniPole = vektorOriginal[0]
        rucniVelikost = vektorOriginal[1]
        logger.info('zahajeni vyhodnoceni segmentace')
        vysledky = liver_segmentation.vyhodnoceniSnimku(
            rucniPole, rucniVelikost, segmentovany, segmentovanyVelikost)
        logger.info(str(vysledky))
        skore = vysledky[1]
        pravda = True
        import sed3
        ed = sed3.sed3(vytvoreny.data3d, contour=vytvoreny.segmentation)
        ed.show()

        if (skore > 75):
            logger.info('metoda funguje uspokojive')
            pravda = False
        if (pravda and (skore > 50)):
            logger.info('metoda funguje relativne dobre')
            pravda = False
        if (pravda):
            logger.info('metoda funguje spatne')
            pravda = False
        # self.assertGreater(skore, 5)

        self.assertLess(vysledky[0]['voe'], 50)

        return
Пример #7
0
        default='mesh_geom.vtk',
        help='temp file used in processing')
    parser.add_argument(
        '-d', '--degrad', type=int,
        default=4,
        help='data degradation, default 4')
    parser.add_argument(
        '-l', '--labels', type=int, metavar='N', nargs='+',
        default=[1],
        help='segmentation labels, default 1')
    parser.add_argument(
        '-s', '--show', action='store_true',
        help='Show mode')
    args = parser.parse_args()

    dr = io3d.DataReader()
    data = dr.Get3DData(args.inputfile, dataplus_format=True)
    # args.label = np.array(eval(args.label))
    # print args.label
    # import pdb; pdb.set_trace()
    ds = data['segmentation']

    if args.show:
        dsel = select_labels(ds, args.labels)
        import sed3


        ed = sed3.sed3(dsel.astype(np.double))
        ed.show()