コード例 #1
0
def get_extractor(img, mask, settings, name=None):
    if name:
        features = {
            "first_order":
            firstorder.RadiomicsFirstOrder(img, mask, **settings),
            "glcm": glcm.RadiomicsGLCM(img, mask, **settings),
            "glrm": glrlm.RadiomicsGLRLM(img, mask, **settings),
            "glszm": glszm.RadiomicsGLSZM(img, mask, **settings),
            "gldm": gldm.RadiomicsGLDM(img, mask, **settings)
        }
        return features[name]
コード例 #2
0
    def gldm_features(self):

        gldm_dict = {}
        GLDMFeatures = gldm.RadiomicsGLDM(img,GT)
        GLDMFeatures.enableAllFeatures()  # On the feature class level, all features are disabled by default.
        GLDMFeatures.execute()
        for (key,val) in six.iteritems(GLDMFeatures.featureValues):

            if self.all_: 
                self.feat_dict[self.seq + "_" + self.class_ + '_' + key] = val
            else: 
                gldm_dict[self.seq + "_" + self.class_ + "_" + key] = val

        df = pd.DataFrame(gldm_dict)
        if self.save_path:
            df.to_csv(os.path.join(self.save_path, 'gldm_features.csv'), index=False)

        return df
コード例 #3
0
ファイル: radfeatures.py プロジェクト: xgxofdream/BioExp
    def gldm_features(self):

        gldm_dict = {}
        GLDMFeatures = gldm.RadiomicsGLDM(self.img, self.GT)
        GLDMFeatures.enableAllFeatures(
        )  # On the feature class level, all features are disabled by default.
        GLDMFeatures.execute()
        for (key, val) in six.iteritems(GLDMFeatures.featureValues):

            self.feat_dict[key] = [val]
            gldm_dict[key] = [val]

        print(gldm_dict)
        df = pd.DataFrame(gldm_dict)
        if self.save_path:
            df.to_csv(os.path.join(self.save_path, 'gldm_features.csv'),
                      index=False)

        return df
コード例 #4
0
    def gldm_features(self):

        gldm_dict = {}
        GLDMFeatures = gldm.RadiomicsGLDM(self.img, self.GT)
        GLDMFeatures.enableAllFeatures(
        )  # On the feature class level, all features are disabled by default.
        GLDMFeatures.execute()
        for (key, val) in six.iteritems(GLDMFeatures.featureValues):

            if self.all_:
                self.feat_dict[self.seq + "_" + self.class_ + '_' + key] = val
            else:
                gldm_dict[self.seq + "_" + self.class_ + "_" + key] = val

        if self.save_path and (not self.all_):
            self.write(gldm_dict,
                       os.path.join(self.save_path, 'gldm_features.pickle'))

        return gldm_dict
コード例 #5
0
def extract_features(folder_path, folder_id):
    # Load in preprocessed mri volumes
    scans = np.load(r"{}/{}_scans.npy".format(folder_path, folder_id))

    # Get t1ce and flair image from which to extract features
    t1ce_img = sitk.GetImageFromArray(scans[1])
    flair_img = sitk.GetImageFromArray(scans[3])

    # Convert scans from numpy to torch tensor and obtain segmentations with the model. Must Unsqueeze to be in format (B,C,H,W,D)
    scans = torch.unsqueeze(torch.from_numpy(scans), 0).to(device)
    _, mask = model(scans)
    mask = torch.squeeze(mask, 0)
    _, mask = mask.max(0)
    enhancing = (mask == 1).cpu().detach().numpy().astype('long')
    edema = (mask == 1).cpu().detach().numpy().astype('long')
    ncr_nenhancing = (mask == 3).cpu().detach().numpy().astype('long')

    regions = {
        'edema': {
            'mask': edema,
            'modality': flair_img
        },
        'enhancing': {
            'mask': enhancing,
            'modality': t1ce_img
        },
        'ncr_nenhancing': {
            'mask': ncr_nenhancing,
            'modality': t1ce_img
        }
    }

    # Convert the region arrays into SITK image objects so they can be inputted to the PyRadiomics featureextractor functions.
    all_features = {}
    printed = 0
    for (region_name, images) in regions.items():

        lbl_img = sitk.GetImageFromArray(images['mask'])
        if len(np.unique(images['mask'])) > 1:

            # Get First order features
            firstorderfeatures = firstorder.RadiomicsFirstOrder(
                images['modality'], lbl_img)
            firstorderfeatures.enableAllFeatures(
            )  # On the feature class level, all features are disabled by default
            firstorderfeatures.execute()
            for (key, val) in firstorderfeatures.featureValues.items():
                all_features[region_name + '_' + key] = val

            # Get Shape features
            shapefeatures = shape.RadiomicsShape(images['modality'], lbl_img)
            shapefeatures.enableAllFeatures()
            shapefeatures.execute()
            for (key, val) in shapefeatures.featureValues.items():
                all_features[region_name + '_' + key] = val

            # Get Gray Level Co-occurrence Matrix (GLCM) Features
            glcmfeatures = glcm.RadiomicsGLCM(images['modality'], lbl_img)
            glcmfeatures.enableAllFeatures()
            glcmfeatures.execute()
            for (key, val) in glcmfeatures.featureValues.items():
                all_features[region_name + '_' + key] = val

            # Get Gray Level Size Zone Matrix (GLSZM) Features
            glszmfeatures = glszm.RadiomicsGLSZM(images['modality'], lbl_img)
            glszmfeatures.enableAllFeatures()
            glszmfeatures.execute()
            for (key, val) in glszmfeatures.featureValues.items():
                all_features[region_name + '_' + key] = val

            # Get Gray Level Run Length Matrix (GLRLM) Features
            glrlmfeatures = glrlm.RadiomicsGLRLM(images['modality'], lbl_img)
            glrlmfeatures.enableAllFeatures()
            glrlmfeatures.execute()
            for (key, val) in glrlmfeatures.featureValues.items():
                all_features[region_name + '_' + key] = val

            # Get Neighbouring Gray Tone Difference Matrix (NGTDM) Features
            ngtdmfeatures = ngtdm.RadiomicsNGTDM(images['modality'], lbl_img)
            ngtdmfeatures.enableAllFeatures()
            ngtdmfeatures.execute()
            for (key, val) in ngtdmfeatures.featureValues.items():
                all_features[region_name + '_' + key] = val

            # Get Gray Level Dependence Matrix (GLDM) Features
            gldmfeatures = gldm.RadiomicsGLDM(images['modality'], lbl_img)
            gldmfeatures.enableAllFeatures()
            gldmfeatures.execute()
            for (key, val) in gldmfeatures.featureValues.items():
                all_features[region_name + '_' + key] = val
        else:
            if (not printed):
                print(folder_id)
                printed = 1
    return all_features
コード例 #6
0
def calculateRadiomicsFromJson(niiFile, jsonFile,wavelet,LoG,Square,SquareRoot,Logarithm,\
                Exponential,Gradient,LocalBinaryPattern2D,LocalBinaryPattern3D):
    sitkImageParent = sitk.ReadImage(niiFile)
    direction = sitkImageParent.GetDirection()
    origin = sitkImageParent.GetOrigin()
    spacing = sitkImageParent.GetSpacing()
    # processing json
    nodules = {}   
    parameterList = ["xBegin","yBegin","zBegin","DimInPixelX","DimInPixelY","DimInPixelZ",\
                     "sliceMask"]
    with open(jsonFile,mode='r') as f: 
        json_Data = json.load(f)
        nodule_List = json_Data.get("Nodules",None)
        if not nodule_List:
            print("Error!NO DATA IN json")
            return
        for subNodule,subVal in nodule_List.items():
            if str(subNodule) == 'count' or str(subNodule) == 'version' :
                continue
            # print("subNodule=",subNodule)
            # print("subVal=",subVal)
            label = subVal.get("Label",None)
            if not label:
                print("ERROR:Nodule No Label Info")
                return 
            nodules[label]={}
            nodules[label]['label'] = label
            nodules[label]['sliceMask'] = ''
            for arg in parameterList:
                if arg in ["DimInPixelX","DimInPixelY","DimInPixelZ"]:
                    nodules[label][arg] = int(subVal.get(arg,None))
                elif arg in ["xBegin","yBegin","zBegin"]:
                    if subVal.get("VerifiedNodule",None).get("mask",None):
                        nodules[label][arg] = float(subVal.get("VerifiedNodule",None).get("mask",None).get(arg,None))#subVal.get("VerifiedNodule",None).get("mask",None).get(arg,None))
                    else:
                        nodules[label][arg] = float(subVal.get("mask",None).get(arg,None))#subVal.get("VerifiedNodule",None).get("mask",None).get(arg,None))
                else:
                    if subVal.get("VerifiedNodule",None).get("mask",None):
                        subSliceMask = subVal.get("VerifiedNodule",None).get("mask",None).get("sliceMask",None)#.get("VerifiedNodule",None).get("mask",None).get("sliceMask",None)#['item']
                    else:
                        subSliceMask = subVal.get("mask",None).get("sliceMask",None)
                    subSliceMask.pop("count")
                    for key,val in subSliceMask.items():#current 
                        for i in val:
                            nodules[label][arg] += i
                    # nodules[label][arg] =subVal.get("VerifiedNodule",None).get("mask",None).get("sliceMask",None)['item']
    # print("nodules=",nodules)
    features = {}
    kwargs = {'binWidth': 64,
              'interpolator': sitk.sitkBSpline,
              'resampledPixelSpacing': None}
    for noduleLabel in nodules:
        if 'DimInPixelX' not in nodules[noduleLabel]:
            continue
        print("noduleLabel=",noduleLabel)
        bbox_dim = (nodules[noduleLabel]['DimInPixelX'], nodules[noduleLabel]['DimInPixelY'], \
                   nodules[noduleLabel]['DimInPixelZ'])
        bbox_ori = (nodules[noduleLabel]['xBegin'], nodules[noduleLabel]['yBegin'], \
                   nodules[noduleLabel]['zBegin'])

        sitkMask = sitk.Image(bbox_dim[0], bbox_dim[1], bbox_dim[2], sitk.sitkUInt8)
        sitkMask.SetSpacing(spacing)
        sitkMask.SetOrigin(bbox_ori)
        sitkMask.SetDirection(direction)

        for z in range(bbox_dim[2]):
            for y in range(bbox_dim[1]):
                for x in range(bbox_dim[0]):
                    idx = z * bbox_dim[1] * bbox_dim[0]  + y * bbox_dim[0] + x
                    v = int(nodules[noduleLabel]['sliceMask'][idx])
                    sitkMask.SetPixel(x, y, z, v)
        ori_matrix = (int(direction[0] * (bbox_ori[0] - origin[0]) / spacing[0]), \
                      int(direction[4] * (bbox_ori[1] - origin[1]) / spacing[1]), \
                      int(direction[8] * (bbox_ori[2] - origin[2]) / spacing[2]))

        sitkMask = resample_sitkImage(sitkMask, (spacing[0]/4, spacing[1]/4, spacing[2]/4))
        sitkImage = sitk.RegionOfInterest(sitkImageParent, sitkMask.GetSize(), ori_matrix)
        sitkImage.SetSpacing(spacing)
        sitkImage.SetOrigin(bbox_ori)
        sitkImage.SetDirection(direction)

        features[noduleLabel] = {}
        
        firstOrderFeatures = firstorder.RadiomicsFirstOrder(sitkImage, sitkMask, **kwargs)
        firstOrderFeatures.enableAllFeatures()
        firstOrderFeatures.calculateFeatures()
        firstOrderResult = features[noduleLabel].setdefault('firstorder', {})
        for (key, val) in six.iteritems(firstOrderFeatures.featureValues):
            firstOrderResult[key] = val

        shapeFeatures = shape.RadiomicsShape(sitkImage, sitkMask, **kwargs)
        shapeFeatures.enableAllFeatures()
        shapeFeatures.calculateFeatures()
        shapeResult = features[noduleLabel].setdefault('shape', {})
        for (key, val) in six.iteritems(shapeFeatures.featureValues):
            shapeResult[key] = val

        glcmFeatures = glcm.RadiomicsGLCM(sitkImage, sitkMask, **kwargs)
        glcmFeatures.enableAllFeatures()
        glcmFeatures.calculateFeatures()
        glcmResult = features[noduleLabel].setdefault('glcm', {})
        for (key, val) in six.iteritems(glcmFeatures.featureValues):
            glcmResult[key] = val

        glrlmFeatures = glrlm.RadiomicsGLRLM(sitkImage, sitkMask, **kwargs)
        glrlmFeatures.enableAllFeatures()
        glrlmFeatures.calculateFeatures()
        glrlmResult = features[noduleLabel].setdefault('glrlm', {})
        for (key, val) in six.iteritems(glrlmFeatures.featureValues):
            glrlmResult[key] = val

        glszmFeatures = glszm.RadiomicsGLSZM(sitkImage, sitkMask, **kwargs)
        glszmFeatures.enableAllFeatures()
        glszmFeatures.calculateFeatures()
        glszmResult = features[noduleLabel].setdefault('glszm', {})
        for (key, val) in six.iteritems(glszmFeatures.featureValues):
            glszmResult[key] = val
        #added new feature of gldm
        gldmFeatures = gldm.RadiomicsGLDM(sitkImage, sitkMask, **kwargs)
        gldmFeatures.enableAllFeatures()
        gldmFeatures.calculateFeatures()
        gldmFeatures = features[noduleLabel].setdefault('gldm', {})
        for (key, val) in six.iteritems(glszmFeatures.featureValues):
            gldmFeatures[key] = val
        #added new feature of ngtdm
        ngtdmFeatures = ngtdm.RadiomicsNGTDM(sitkImage, sitkMask, **kwargs)
        ngtdmFeatures.enableAllFeatures()
        ngtdmFeatures.calculateFeatures()
        ngtdmFeatures = features[noduleLabel].setdefault('ngtdm', {})
        for (key, val) in six.iteritems(glszmFeatures.featureValues):
            ngtdmFeatures[key] = val

        print("features=",features)

        featuresList = ["FirstOrder","Shape","GLCM","GLRLM","GLSZM","NGTDM","GLDM"]
        if LoG:
            sigmaValues = numpy.arange(5., 0., -.5)[::1]
            for logImage, imageTypeName, inputKwargs in imageoperations.getLoGImage(sitkImage, sitkMask,sigma=sigmaValues):
                for filterName  in featuresList: 
                    exec("LoG"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(logImage, sitkMask, **inputKwargs)")
                for feature in featuresList:
                    exec("LoG"+feature+"Features.enableAllFeatures()")
                    exec("LoG"+feature+"Features.calculateFeatures()")
                LoGFirstOrderResult = features[noduleLabel].setdefault('LoGFirstOrder', {})
                LoGShapeResult = features[noduleLabel].setdefault('LoGShape', {})
                LoGGLCMResult = features[noduleLabel].setdefault('LoGGlcm', {})
                LoGGLRLMResult = features[noduleLabel].setdefault('LoGGlrlm', {})
                LoGGLSZMResult = features[noduleLabel].setdefault('LoGGlszm', {})
                LoGGLDMResult = features[noduleLabel].setdefault('LoGGldm', {})
                LoGNGTDMResult = features[noduleLabel].setdefault('LoGNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("LoG" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                       exec("LoG"+filterName+"Result[key]=val") 
        
        if wavelet:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getWaveletImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("wavelet"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("wavelet"+filterName+"Features.enableAllFeatures()")
                    exec("wavelet"+filterName+"Features.calculateFeatures()")
                waveletFirstOrderResult = features[noduleLabel].setdefault('waveletFirstOrder', {})
                waveletShapeResult = features[noduleLabel].setdefault('waveletShape', {})
                waveletGLCMResult = features[noduleLabel].setdefault('waveletGlcm', {})
                waveletGLRLMResult = features[noduleLabel].setdefault('waveletGlrlm', {})
                waveletGLSZMResult = features[noduleLabel].setdefault('waveletGlszm', {})
                waveletGLDMResult = features[noduleLabel].setdefault('waveletGldm', {})
                waveletNGTDMResult = features[noduleLabel].setdefault('waveletNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("wavelet" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                       exec("wavelet"+filterName+"Result[key]=val") 
        if Square:
            # calculateSubFilterValues(imageType =="Square",features,noduleLabel,sitkImage,sitkMask)
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getSquareImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("square"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("square"+filterName+"Features.enableAllFeatures()")
                    exec("square"+filterName+"Features.calculateFeatures()")
                squareFirstOrderResult = features[noduleLabel].setdefault('squareFirstOrder', {})
                squareShapeResult = features[noduleLabel].setdefault('squareShape', {})
                squareGLCMResult = features[noduleLabel].setdefault('squareGlcm', {})
                squareGLRLMResult = features[noduleLabel].setdefault('squareGlrlm', {})
                squareGLSZMResult = features[noduleLabel].setdefault('squareGlszm', {})
                squareGLDMResult = features[noduleLabel].setdefault('squareGldm', {})
                squareNGTDMResult = features[noduleLabel].setdefault('squareNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("square" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("square"+filterName+"Result[key]=val") 
        if SquareRoot:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getSquareRootImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("squareRoot"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("squareRoot"+filterName+"Features.enableAllFeatures()")
                    exec("squareRoot"+filterName+"Features.calculateFeatures()")
                squareRootFirstOrderResult = features[noduleLabel].setdefault('squareRootFirstOrder', {})
                squareRootShapeResult = features[noduleLabel].setdefault('squareRootShape', {})
                squareRootGLCMResult = features[noduleLabel].setdefault('squareRootGlcm', {})
                squareRootGLRLMResult = features[noduleLabel].setdefault('squareRootGlrlm', {})
                squareRootGLSZMResult = features[noduleLabel].setdefault('squareRootGlszm', {})
                squareRootGLDMResult = features[noduleLabel].setdefault('squareRootGldm', {})
                squareRootNGTDMResult = features[noduleLabel].setdefault('squareRootNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("squareRoot" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("squareRoot"+filterName+"Result[key]=val") 
        if Logarithm:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getLogarithmImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("logarithm"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("logarithm"+filterName+"Features.enableAllFeatures()")
                    exec("logarithm"+filterName+"Features.calculateFeatures()")
                logarithmFirstOrderResult = features[noduleLabel].setdefault('logarithmFirstOrder', {})
                logarithmShapeResult = features[noduleLabel].setdefault('logarithmShape', {})
                logarithmGLCMResult = features[noduleLabel].setdefault('logarithmGlcm', {})
                logarithmGLRLMResult = features[noduleLabel].setdefault('logarithmGlrlm', {})
                logarithmGLSZMResult = features[noduleLabel].setdefault('logarithmGlszm', {})
                logarithmGLDMResult = features[noduleLabel].setdefault('logarithmGldm', {})
                logarithmNGTDMResult = features[noduleLabel].setdefault('logarithmNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("logarithm" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("logarithm"+filterName+"Result[key]=val")
    
        if Exponential:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getExponentialImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("Exponential"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("Exponential"+filterName+"Features.enableAllFeatures()")
                    exec("Exponential"+filterName+"Features.calculateFeatures()")
                ExponentialFirstOrderResult = features[noduleLabel].setdefault('ExponentialFirstOrder', {})
                ExponentialShapeResult = features[noduleLabel].setdefault('ExponentialShape', {})
                ExponentialGLCMResult = features[noduleLabel].setdefault('ExponentialGlcm', {})
                ExponentialGLRLMResult = features[noduleLabel].setdefault('ExponentialGlrlm', {})
                ExponentialGLSZMResult = features[noduleLabel].setdefault('ExponentialGlszm', {})
                ExponentialGLDMResult = features[noduleLabel].setdefault('ExponentialGldm', {})
                ExponentialNGTDMResult = features[noduleLabel].setdefault('ExponentialNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("Exponential" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("Exponential"+filterName+"Result[key]=val") 
        if Gradient:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getGradientImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("Gradient"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("Gradient"+filterName+"Features.enableAllFeatures()")
                    exec("Gradient"+filterName+"Features.calculateFeatures()")
                GradientFirstOrderResult = features[noduleLabel].setdefault('GradientFirstOrder', {})
                GradientShapeResult = features[noduleLabel].setdefault('GradientShape', {})
                GradientGLCMResult = features[noduleLabel].setdefault('GradientGlcm', {})
                GradientGLRLMResult = features[noduleLabel].setdefault('GradientGlrlm', {})
                GradientGLSZMResult = features[noduleLabel].setdefault('GradientGlszm', {})
                GradientGLDMResult = features[noduleLabel].setdefault('GradientGldm', {})
                GradientNGTDMResult = features[noduleLabel].setdefault('GradientNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("Gradient" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("Gradient"+filterName+"Result[key]=val") 
                        
        #LocalBinaryPattern2D,LocalBinaryPattern3D
        if LocalBinaryPattern2D:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getLBP2DImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("LBP2D"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("LBP2D"+filterName+"Features.enableAllFeatures()")
                    exec("LBP2D"+filterName+"Features.calculateFeatures()")
                LBP2DFirstOrderResult = features[noduleLabel].setdefault('LBP2DFirstOrder', {})
                LBP2DShapeResult = features[noduleLabel].setdefault('LBP2DShape', {})
                LBP2DGLCMResult = features[noduleLabel].setdefault('LBP2DGlcm', {})
                LBP2DGLRLMResult = features[noduleLabel].setdefault('LBP2DGlrlm', {})
                LBP2DGLSZMResult = features[noduleLabel].setdefault('LBP2DGlszm', {})
                LBP2DGLDMResult = features[noduleLabel].setdefault('LBP2DGldm', {})
                LBP2DNGTDMResult = features[noduleLabel].setdefault('LBP2DNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("LBP2D" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("LBP2D"+filterName+"Result[key]=val") 
        
        if LocalBinaryPattern3D:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getLBP3DImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("LBP3D"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("LBP3D"+filterName+"Features.enableAllFeatures()")
                    exec("LBP3D"+filterName+"Features.calculateFeatures()")
                LBP3DFirstOrderResult = features[noduleLabel].setdefault('LBP3DFirstOrder', {})
                LBP3DShapeResult = features[noduleLabel].setdefault('LBP3DShape', {})
                LBP3DGLCMResult = features[noduleLabel].setdefault('LBP3DGlcm', {})
                LBP3DGLRLMResult = features[noduleLabel].setdefault('LBP3DGlrlm', {})
                LBP3DGLSZMResult = features[noduleLabel].setdefault('LBP3DGlszm', {})
                LBP3DGLDMResult = features[noduleLabel].setdefault('LBP3DGldm', {})
                LBP3DNGTDMResult = features[noduleLabel].setdefault('LBP3DNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("LBP3D" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("LBP3D"+filterName+"Result[key]=val")
    return features
コード例 #7
0
ファイル: jsonRadiomics.py プロジェクト: zhuyun86/PyWork
def calculateRadiomicsFromJson(niiFile, jsonFile,wavelet,LoG,Square,SquareRoot,Logarithm,\
                Exponential,Gradient,LocalBinaryPattern2D,LocalBinaryPattern3D):
    # moduleConfig = get_current_config()
    # processing nii
    sitkImageParent = sitk.ReadImage(niiFile)
    direction = sitkImageParent.GetDirection()
    origin = sitkImageParent.GetOrigin()
    spacing = sitkImageParent.GetSpacing()
    # processing json
    f = open(jsonFile)
    p = ijson.parse(f)
    # print("p={}".format(p))
    nodules = {}
    label = ''
    for prefix, _, value in p:
        # print()
        if re.match('Nodules.item\d+.Label', prefix) or prefix == 'Nodules.item.Label':
            label = value
            nodules[label] = {}
            nodules[label]['label'] = value
            nodules[label]['sliceMask'] = ''
        if re.match('Nodules.item\d+.mask.xBegin', prefix) or prefix == 'Nodules.item.mask.xBegin':
            nodules[label]['xBegin'] = float(value)
        if re.match('Nodules.item\d+.mask.yBegin', prefix) or prefix == 'Nodules.item.mask.yBegin':
            nodules[label]['yBegin'] = float(value)
        if re.match('Nodules.item\d+.mask.zBegin', prefix) or prefix == 'Nodules.item.mask.zBegin':
            nodules[label]['zBegin'] = float(value)
        if re.match('Nodules.item\d+.DimInPixelX', prefix) or prefix == 'Nodules.item.DimInPixelX':
            nodules[label]['DimInPixelX'] =int(float(value))
        if re.match('Nodules.item\d+.DimInPixelY', prefix) or prefix == 'Nodules.item.DimInPixelY':
            nodules[label]['DimInPixelY'] = int(float(value))
        if re.match('Nodules.item\d+.DimInPixelZ', prefix) or prefix == 'Nodules.item.DimInPixelZ':
            nodules[label]['DimInPixelZ'] = int(float(value))
        if re.match('Nodules.item\d+.mask.sliceMask.item\d+', prefix) or prefix == 'Nodules.item.mask.sliceMask.item':
            nodules[label]['sliceMask'] += value
    # working on radiomics calculation
    features = {}
    kwargs = {'binWidth': 64,
              'interpolator': sitk.sitkBSpline,
              'resampledPixelSpacing': None}
    # print("nodules=",nodules)
    for noduleLabel in nodules:
        if 'DimInPixelX' not in nodules[noduleLabel]:
            continue
        bbox_dim = (nodules[noduleLabel]['DimInPixelX'], nodules[noduleLabel]['DimInPixelY'], \
                   nodules[noduleLabel]['DimInPixelZ'])
        bbox_ori = (nodules[noduleLabel]['xBegin'], nodules[noduleLabel]['yBegin'], \
                   nodules[noduleLabel]['zBegin'])
        print("bbox_dim={}".format(bbox_dim))
        sitkMask = sitk.Image(bbox_dim[0], bbox_dim[1], bbox_dim[2], sitk.sitkUInt8)
        sitkMask.SetSpacing(spacing)
        sitkMask.SetOrigin(bbox_ori)
        sitkMask.SetDirection(direction)

        for z in range(bbox_dim[2]):#9
            for y in range(bbox_dim[1]):  #16
                for x in range(bbox_dim[0]): #17
                    # print("x,y,z={}{}{}".format(x,y,z))
                    # print("{},{},{}".format(x,y,z))
                    idx = z * bbox_dim[1] * bbox_dim[0]  + y * bbox_dim[0] + x
                    # print("idx={}".format(idx))
                    v = int(nodules[noduleLabel]['sliceMask'][idx])
                    sitkMask.SetPixel(x, y, z, v)
        ori_matrix = (int(direction[0] * (bbox_ori[0] - origin[0]) / spacing[0]), \
                      int(direction[4] * (bbox_ori[1] - origin[1]) / spacing[1]), \
                      int(direction[8] * (bbox_ori[2] - origin[2]) / spacing[2]))

        # sitkMask = resample_sitkImage(sitkMask, (spacing[0]/2, spacing[1]/2, spacing[2]/2))
        sitkImage = sitk.RegionOfInterest(sitkImageParent, sitkMask.GetSize(), ori_matrix)
        sitkImage.SetSpacing(spacing)
        sitkImage.SetOrigin(bbox_ori)
        sitkImage.SetDirection(direction)

        features[noduleLabel] = {}

        firstOrderFeatures = firstorder.RadiomicsFirstOrder(sitkImage, sitkMask, **kwargs)
        firstOrderFeatures.enableAllFeatures()
        firstOrderFeatures.calculateFeatures()
        firstOrderResult = features[noduleLabel].setdefault('firstorder', {})
        for (key, val) in six.iteritems(firstOrderFeatures.featureValues):
            firstOrderResult[key] = val

        shapeFeatures = shape.RadiomicsShape(sitkImage, sitkMask, **kwargs)
        shapeFeatures.enableAllFeatures()
        shapeFeatures.calculateFeatures()
        shapeResult = features[noduleLabel].setdefault('shape', {})
        for (key, val) in six.iteritems(shapeFeatures.featureValues):
            shapeResult[key] = val

        glcmFeatures = glcm.RadiomicsGLCM(sitkImage, sitkMask, **kwargs)
        glcmFeatures.enableAllFeatures()
        glcmFeatures.calculateFeatures()
        glcmResult = features[noduleLabel].setdefault('glcm', {})
        for (key, val) in six.iteritems(glcmFeatures.featureValues):
            glcmResult[key] = val

        glrlmFeatures = glrlm.RadiomicsGLRLM(sitkImage, sitkMask, **kwargs)
        glrlmFeatures.enableAllFeatures()
        glrlmFeatures.calculateFeatures()
        glrlmResult = features[noduleLabel].setdefault('glrlm', {})
        for (key, val) in six.iteritems(glrlmFeatures.featureValues):
            glrlmResult[key] = val

        glszmFeatures = glszm.RadiomicsGLSZM(sitkImage, sitkMask, **kwargs)
        glszmFeatures.enableAllFeatures()
        glszmFeatures.calculateFeatures()
        glszmResult = features[noduleLabel].setdefault('glszm', {})
        for (key, val) in six.iteritems(glszmFeatures.featureValues):
            glszmResult[key] = val
        #added new feature of gldm
        gldmFeatures = gldm.RadiomicsGLDM(sitkImage, sitkMask, **kwargs)
        gldmFeatures.enableAllFeatures()
        gldmFeatures.calculateFeatures()
        gldmFeatures = features[noduleLabel].setdefault('gldm', {})
        for (key, val) in six.iteritems(glszmFeatures.featureValues):
            gldmFeatures[key] = val
        #added new feature of ngtdm
        ngtdmFeatures = ngtdm.RadiomicsNGTDM(sitkImage, sitkMask, **kwargs)
        ngtdmFeatures.enableAllFeatures()
        ngtdmFeatures.calculateFeatures()
        ngtdmFeatures = features[noduleLabel].setdefault('ngtdm', {})
        for (key, val) in six.iteritems(glszmFeatures.featureValues):
            ngtdmFeatures[key] = val

        featuresList = ["FirstOrder","Shape","GLCM","GLRLM","GLSZM","NGTDM","GLDM"]
        if LoG:
            sigmaValues = numpy.arange(5., 0., -.5)[::1]
            for logImage, imageTypeName, inputKwargs in imageoperations.getLoGImage(sitkImage, sitkMask,sigma=sigmaValues):
                for filterName  in featuresList: 
                    exec("LoG"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(logImage, sitkMask, **inputKwargs)")
                for feature in featuresList:
                    exec("LoG"+feature+"Features.enableAllFeatures()")
                    exec("LoG"+feature+"Features.calculateFeatures()")
                LoGFirstOrderResult = features[noduleLabel].setdefault('logFirstOrder', {})
                LoGShapeResult = features[noduleLabel].setdefault('logShape', {})
                LoGGLCMResult = features[noduleLabel].setdefault('logGlcm', {})
                LoGGLRLMResult = features[noduleLabel].setdefault('logGlrlm', {})
                LoGGLSZMResult = features[noduleLabel].setdefault('logGlszm', {})
                LoGGLDMResult = features[noduleLabel].setdefault('logGldm', {})
                LoGNGTDMResult = features[noduleLabel].setdefault('logNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("LoG" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                       exec("LoG"+filterName+"Result[key]=val") 
        
        if wavelet:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getWaveletImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("wavelet"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("wavelet"+filterName+"Features.enableAllFeatures()")
                    exec("wavelet"+filterName+"Features.calculateFeatures()")
                waveletFirstOrderResult = features[noduleLabel].setdefault('waveletFirstOrder', {})
                waveletShapeResult = features[noduleLabel].setdefault('waveletShape', {})
                waveletGLCMResult = features[noduleLabel].setdefault('waveletGlcm', {})
                waveletGLRLMResult = features[noduleLabel].setdefault('waveletGlrlm', {})
                waveletGLSZMResult = features[noduleLabel].setdefault('waveletGlszm', {})
                waveletGLDMResult = features[noduleLabel].setdefault('waveletGldm', {})
                waveletNGTDMResult = features[noduleLabel].setdefault('waveletNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("wavelet" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                       exec("wavelet"+filterName+"Result[key]=val") 
        if Square:
            # calculateSubFilterValues(imageType =="Square",features,noduleLabel,sitkImage,sitkMask)
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getSquareImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("square"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("square"+filterName+"Features.enableAllFeatures()")
                    exec("square"+filterName+"Features.calculateFeatures()")
                squareFirstOrderResult = features[noduleLabel].setdefault('squareFirstOrder', {})
                squareShapeResult = features[noduleLabel].setdefault('squareShape', {})
                squareGLCMResult = features[noduleLabel].setdefault('squareGlcm', {})
                squareGLRLMResult = features[noduleLabel].setdefault('squareGlrlm', {})
                squareGLSZMResult = features[noduleLabel].setdefault('squareGlszm', {})
                squareGLDMResult = features[noduleLabel].setdefault('squareGldm', {})
                squareNGTDMResult = features[noduleLabel].setdefault('squareNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("square" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("square"+filterName+"Result[key]=val") 
        if SquareRoot:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getSquareRootImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("squareRoot"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("squareRoot"+filterName+"Features.enableAllFeatures()")
                    exec("squareRoot"+filterName+"Features.calculateFeatures()")
                squareRootFirstOrderResult = features[noduleLabel].setdefault('squareRootFirstOrder', {})
                squareRootShapeResult = features[noduleLabel].setdefault('squareRootShape', {})
                squareRootGLCMResult = features[noduleLabel].setdefault('squareRootGlcm', {})
                squareRootGLRLMResult = features[noduleLabel].setdefault('squareRootGlrlm', {})
                squareRootGLSZMResult = features[noduleLabel].setdefault('squareRootGlszm', {})
                squareRootGLDMResult = features[noduleLabel].setdefault('squareRootGldm', {})
                squareRootNGTDMResult = features[noduleLabel].setdefault('squareRootNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("squareRoot" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("squareRoot"+filterName+"Result[key]=val") 
        if Logarithm:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getLogarithmImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("logarithm"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("logarithm"+filterName+"Features.enableAllFeatures()")
                    exec("logarithm"+filterName+"Features.calculateFeatures()")
                logarithmFirstOrderResult = features[noduleLabel].setdefault('logarithmFirstOrder', {})
                logarithmShapeResult = features[noduleLabel].setdefault('logarithmShape', {})
                logarithmGLCMResult = features[noduleLabel].setdefault('logarithmGlcm', {})
                logarithmGLRLMResult = features[noduleLabel].setdefault('logarithmGlrlm', {})
                logarithmGLSZMResult = features[noduleLabel].setdefault('logarithmGlszm', {})
                logarithmGLDMResult = features[noduleLabel].setdefault('logarithmGldm', {})
                logarithmNGTDMResult = features[noduleLabel].setdefault('logarithmNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("logarithm" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("logarithm"+filterName+"Result[key]=val")
    
        if Exponential:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getExponentialImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("Exponential"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("Exponential"+filterName+"Features.enableAllFeatures()")
                    exec("Exponential"+filterName+"Features.calculateFeatures()")
                ExponentialFirstOrderResult = features[noduleLabel].setdefault('ExponentialFirstOrder', {})
                ExponentialShapeResult = features[noduleLabel].setdefault('ExponentialShape', {})
                ExponentialGLCMResult = features[noduleLabel].setdefault('ExponentialGlcm', {})
                ExponentialGLRLMResult = features[noduleLabel].setdefault('ExponentialGlrlm', {})
                ExponentialGLSZMResult = features[noduleLabel].setdefault('ExponentialGlszm', {})
                ExponentialGLDMResult = features[noduleLabel].setdefault('ExponentialGldm', {})
                ExponentialNGTDMResult = features[noduleLabel].setdefault('ExponentialNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("Exponential" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("Exponential"+filterName+"Result[key]=val") 
        if Gradient:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getGradientImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("Gradient"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("Gradient"+filterName+"Features.enableAllFeatures()")
                    exec("Gradient"+filterName+"Features.calculateFeatures()")
                GradientFirstOrderResult = features[noduleLabel].setdefault('GradientFirstOrder', {})
                GradientShapeResult = features[noduleLabel].setdefault('GradientShape', {})
                GradientGLCMResult = features[noduleLabel].setdefault('GradientGlcm', {})
                GradientGLRLMResult = features[noduleLabel].setdefault('GradientGlrlm', {})
                GradientGLSZMResult = features[noduleLabel].setdefault('GradientGlszm', {})
                GradientGLDMResult = features[noduleLabel].setdefault('GradientGldm', {})
                GradientNGTDMResult = features[noduleLabel].setdefault('GradientNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("Gradient" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("Gradient"+filterName+"Result[key]=val") 
                        
        #LocalBinaryPattern2D,LocalBinaryPattern3D
        if LocalBinaryPattern2D:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getLBP2DImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("LBP2D"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("LBP2D"+filterName+"Features.enableAllFeatures()")
                    exec("LBP2D"+filterName+"Features.calculateFeatures()")
                LBP2DFirstOrderResult = features[noduleLabel].setdefault('LBP2DFirstOrder', {})
                LBP2DShapeResult = features[noduleLabel].setdefault('LBP2DShape', {})
                LBP2DGLCMResult = features[noduleLabel].setdefault('LBP2DGlcm', {})
                LBP2DGLRLMResult = features[noduleLabel].setdefault('LBP2DGlrlm', {})
                LBP2DGLSZMResult = features[noduleLabel].setdefault('LBP2DGlszm', {})
                LBP2DGLDMResult = features[noduleLabel].setdefault('LBP2DGldm', {})
                LBP2DNGTDMResult = features[noduleLabel].setdefault('LBP2DNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("LBP2D" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("LBP2D"+filterName+"Result[key]=val") 
        
        if LocalBinaryPattern3D:
            for decompositionImage, decompositionName, inputKwargs in imageoperations.getLBP3DImage(sitkImage,sitkMask):
                for filterName  in featuresList: 
                    exec("LBP3D"+filterName+"Features = "+filterName.lower()+".Radiomics"+filterName+"(decompositionImage, sitkMask, **inputKwargs)")
                    exec("LBP3D"+filterName+"Features.enableAllFeatures()")
                    exec("LBP3D"+filterName+"Features.calculateFeatures()")
                LBP3DFirstOrderResult = features[noduleLabel].setdefault('LBP3DFirstOrder', {})
                LBP3DShapeResult = features[noduleLabel].setdefault('LBP3DShape', {})
                LBP3DGLCMResult = features[noduleLabel].setdefault('LBP3DGlcm', {})
                LBP3DGLRLMResult = features[noduleLabel].setdefault('LBP3DGlrlm', {})
                LBP3DGLSZMResult = features[noduleLabel].setdefault('LBP3DGlszm', {})
                LBP3DGLDMResult = features[noduleLabel].setdefault('LBP3DGldm', {})
                LBP3DNGTDMResult = features[noduleLabel].setdefault('LBP3DNGTDM', {})
                for filterName in featuresList:
                    subFeatureValue =eval("LBP3D" + filterName + "Features.featureValues")
                    for (key, val) in six.iteritems(subFeatureValue):
                        exec("LBP3D"+filterName+"Result[key]=val") 
    return features
コード例 #8
0
def calc_radio_fea(img: np.ndarray, mask: np.ndarray) -> List[np.ndarray]:
    assert type(
        img
    ) == np.ndarray, f"TypeError, expected np.ndarray but Got {type(img)}"
    assert img.shape == mask.shape, f"SizeError, expected to be same, but Got {img.shape} and {mask.shape}"

    image = sitk.GetImageFromArray(img)
    mask = sitk.GetImageFromArray(mask)

    # Setting for the feature calculation.
    # Currently, resampling is disabled.
    # Can be enabled by setting 'resampledPixelSpacing' to a list of 3 floats (new voxel size in mm for x, y and z)
    settings = {
        'binWidth': 25,
        'interpolator': sitk.sitkBSpline,
        'resampledPixelSpacing': None
    }
    #
    # If enabled, resample image (resampled image is automatically cropped.
    #
    interpolator = settings.get('interpolator')
    resampledPixelSpacing = settings.get('resampledPixelSpacing')
    if interpolator is not None and resampledPixelSpacing is not None:
        image, mask = imageoperations.resampleImage(image, mask, **settings)

    bb, correctedMask = imageoperations.checkMask(image, mask)
    if correctedMask is not None:
        mask = correctedMask
    image, mask = imageoperations.cropToTumorMask(image, mask, bb)
    results_collect = dict()
    results_np = list()
    # Fisrt order
    firstOrderFeatures = firstorder.RadiomicsFirstOrder(
        image, mask, **settings)
    # firstOrderFeatures.enableFeatureByName('Mean', True)
    firstOrderFeatures.enableAllFeatures()
    results: dict = firstOrderFeatures.execute()  # dict()
    # results_collect['FirstOrder'] = results
    results_np.append(np.array([value for key, value in results.items()]))
    #
    shapeFeatures = shape.RadiomicsShape(image, mask, **settings)
    shapeFeatures.enableAllFeatures()
    results = shapeFeatures.execute()
    # results_collect['ShapeFeature'] = results
    results_np.append(np.array([value for key, value in results.items()]))
    ###
    glcmFeatures = glcm.RadiomicsGLCM(image, mask, **settings)
    glcmFeatures.enableAllFeatures()
    results = glcmFeatures.execute()
    # results_collect['GLCM'] = results
    results_np.append(np.array([value for key, value in results.items()]))
    ###
    glrlmFeatures = glrlm.RadiomicsGLRLM(image, mask, **settings)
    glrlmFeatures.enableAllFeatures()
    results = glrlmFeatures.execute()
    # results_collect['GLRLM'] = results
    results_np.append(np.array([value for key, value in results.items()]))
    ###
    glszmFeatures = glszm.RadiomicsGLSZM(image, mask, **settings)
    glszmFeatures.enableAllFeatures()
    results = glszmFeatures.execute()
    # results_collect['GLSZM'] = results
    results_np.append(np.array([value for key, value in results.items()]))

    gldmFeatures = gldm.RadiomicsGLDM(image, mask, **settings)
    gldmFeatures.enableAllFeatures()
    results = gldmFeatures.execute()
    results_np.append(np.array([value for key, value in results.items()]))

    return results_np
コード例 #9
0
from xlwt import *

tumor_path = '../tumor'
mask_path = '../mask'
Tumor = os.listdir(tumor_path)
Mask = os.listdir(mask_path)
file = Workbook(encoding='ascii')
table = file.add_sheet('data')
for idx in xrange(len(Tumor)):
    image = sitk.ReadImage(os.path.join(tumor_path, Tumor[idx]))
    mask = sitk.ReadImage(os.path.join(mask_path, Mask[idx]))

    shapeFeatures = shape.RadiomicsShape(image, mask)
    firstorderFeatures = firstorder.RadiomicsFirstOrder(image, mask)
    glcmFeatures = glcm.RadiomicsGLCM(image, mask)
    gldmFeatures = gldm.RadiomicsGLDM(image, mask)
    glrlmFeatures = glrlm.RadiomicsGLRLM(image, mask)
    glszmFeatures = glszm.RadiomicsGLSZM(image, mask)
    ngtdmFeatures = ngtdm.RadiomicsNGTDM(image, mask)

    shapeFeatures.enableAllFeatures()
    glcmFeatures.enableAllFeatures()
    firstorderFeatures.enableAllFeatures()
    gldmFeatures.enableAllFeatures()
    glrlmFeatures.enableAllFeatures()
    glszmFeatures.enableAllFeatures()
    ngtdmFeatures.enableAllFeatures()

    shapeFeatures.execute()
    glszmFeatures.execute()
    glcmFeatures.execute()
コード例 #10
0
glszmFeatures.enableAllFeatures()

# print('Will calculate the following GLSZM features: ')
# for f in glszmFeatures.enabledFeatures.keys():
#   print('  ', f)
#   print(getattr(glszmFeatures, 'get%sFeatureValue' % f).__doc__)

print('Calculating GLSZM features...')
results = glszmFeatures.execute()
print('done')

print('Calculated GLSZM features: ')
for i, (key, val) in enumerate(six.iteritems(results)):
    print('  ', f"{i}:", key, ':', val)

gldmFeatures = gldm.RadiomicsGLDM(image, mask, **settings)
gldmFeatures.enableAllFeatures()
print('Calculating GLDM features...')
results = gldmFeatures.execute()
print('done')
print('Calculated GLDM features: ')
for i, (key, val) in enumerate(six.iteritems(results)):
    print('  ', f"{i}:", key, ':', val)
#
# Show FirstOrder features, calculated on a LoG filtered image
#
if applyLog:
    sigmaValues = np.arange(5., 0., -.5)[::1]
    for logImage, imageTypeName, inputKwargs in imageoperations.getLoGImage(
            image, mask, sigma=sigmaValues):
        logFirstorderFeatures = firstorder.RadiomicsFirstOrder(
コード例 #11
0
def extractor(image_array, mask_array, applyLog = False,applyWavelet = False ):
    feature_vectors = {}
    cache_file = os.path.join(DATA_CACHE_PATH_OUT,'cache_%s.nrrd'%random.random())
    nrrd.write(cache_file, image_array)
    image = sitk.ReadImage(cache_file)
    nrrd.write(cache_file, mask_array)
    mask = sitk.ReadImage(cache_file)


    settings = {'binWidth': 25,
            'interpolator': None, #sitk.sitkBSpline,
            'resampledPixelSpacing': None}
    # interpolator = settings.get('interpolator')
    # resampledPixelSpacing = settings.get('resampledPixelSpacing')
    # if interpolator is not None and resampledPixelSpacing is not None:
    #     image, mask = imageoperations.resampleImage(image, mask, **settings)
    # bb, correctedMask = imageoperations.checkMask(image, mask)
    # if correctedMask is not None:
    #   mask = correctedMask
    # image, mask = imageoperations.cropToTumorMask(image, mask, bb)
    
    features = firstorder.RadiomicsFirstOrder(image, mask, **settings)
    # features.enableFeatureByName('Mean', True)
    features.enableAllFeatures()

    # print('Will calculate the following first order features: ')
    # for f in features.enabledFeatures.keys():
    #   print('  ', f)
    #   print(getattr(features, 'get%sFeatureValue' % f).__doc__)

    # print('Calculating first order features...')
    results = features.execute()
    # print('done')

    # print('Calculated first order features: ')
    for (key, val) in six.iteritems(results):
        firstOrderFeatureName = '%s_%s' % ('firstOrder', key)
        if firstOrderFeatureName not in feature_vectors:
            feature_vectors[firstOrderFeatureName] = val
        else:
            print('Error: firstOrder key existing! %s'%firstOrderFeatureName)
            # break
        # print('  ', key, ':', val)
    print('ADDED %s first Order Features'%len(results))
    #
    # Show Shape features
    #

    features = shape.RadiomicsShape(image, mask, **settings)
    features.enableAllFeatures()

    # print('Will calculate the following Shape features: ')
    # for f in features.enabledFeatures.keys():
    #   print('  ', f)
    #   print(getattr(features, 'get%sFeatureValue' % f).__doc__)

    # print('Calculating Shape features...')
    results = features.execute()
    # print('done')

    # print('Calculated Shape features: ')
    for (key, val) in six.iteritems(results):
        ShapeFeatureName = '%s_%s' % ('Shape', key)
        if ShapeFeatureName not in feature_vectors:
            feature_vectors[ShapeFeatureName] = val
        else:
            print('Error: shape key existing! %s'%ShapeFeatureName)
            # break
        # print('  ', key, ':', val)
    print('ADDED %s shape Features'%len(results))
    #
    # Show GLCM features: Gray Level Co-occurrence Matrix (GLCM) Features
    #
    features = glcm.RadiomicsGLCM(image, mask, **settings)
    features.enableAllFeatures()

    # print('Will calculate the following GLCM features: ')
    # for f in features.enabledFeatures.keys():
    #   print('  ', f)
    #   print(getattr(features, 'get%sFeatureValue' % f).__doc__)

    # print('Calculating GLCM features...')
    results = features.execute()
    # print('done')

    # print('Calculated GLCM features: ')
    for (key, val) in six.iteritems(results):
        GLCMFeatureName = '%s_%s' % ('GLCM', key)
        if GLCMFeatureName not in feature_vectors:
            feature_vectors[GLCMFeatureName] = val
        else:
            print('Error: GLCM key existing! %s'%GLCMFeatureName)
            # break
        # print('  ', key, ':', val)


    print('ADDED %s GLCM Features'%len(results))
    #
    # Show GLSZM features; Gray Level Size Zone Matrix (GLSZM) Features
    #
    features = glszm.RadiomicsGLSZM(image, mask, **settings)
    features.enableAllFeatures()

    # print('Will calculate the following GLSZM features: ')
    # for f in features.enabledFeatures.keys():
    #   print('  ', f)
    #   print(getattr(features, 'get%sFeatureValue' % f).__doc__)

    # print('Calculating GLSZM features...')
    results = features.execute()

    # print('Calculated GLSZM features: ')
    for (key, val) in six.iteritems(results):
        GLSZMFeatureName = '%s_%s' % ('GLSZM', key)
        if GLSZMFeatureName not in feature_vectors:
            feature_vectors[GLSZMFeatureName] = val
        else:
            print('Error: GLSZM key existing! %s'%GLSZMFeatureName)
            # break
        # print('  ', key, ':', val)
    print('ADDED %s GLSZ Features'%len(results))

    #
    # Show GLRLM features; Gray Level Run Length Matrix (GLRLM) Features
    #
    features = glrlm.RadiomicsGLRLM(image, mask, **settings)
    features.enableAllFeatures()

    # print('Will calculate the following GLRLM features: ')
    # for f in features.enabledFeatures.keys():
    #   print('  ', f)
    #   print(getattr(features, 'get%sFeatureValue' % f).__doc__)

    # print('Calculating GLRLM features...')
    results = features.execute()
    # print('done')

    # print('Calculated GLRLM features: ')
    for (key, val) in six.iteritems(results):
        GLRLMFeatureName = '%s_%s' % ('GLRLM', key)
        if GLRLMFeatureName not in feature_vectors:
            feature_vectors[GLRLMFeatureName] = val
        else:
            print('Error: GLRLM key existing! %s'%GLRLMFeatureName)
            # break
        # print('  ', key, ':', val)
    print('ADDED %s GLRM Features'%len(results))
    #
    # Show NGTDM features; Neighbouring Gray Tone Difference Matrix (NGTDM) Features
    #
    features = ngtdm.RadiomicsNGTDM(image, mask, **settings)
    features.enableAllFeatures()

    # print('Will calculate the following NGTDM features: ')
    # for f in features.enabledFeatures.keys():
    #   print('  ', f)
    #   print(getattr(features, 'get%sFeatureValue' % f).__doc__)

    # print('Calculating NGTDM features...')
    results = features.execute()
    # print('done')

    # print('Calculated NGTDM features: ')
    for (key, val) in six.iteritems(results):
        NGTDMFeatureName = '%s_%s' % ('NGTDM', key)
        if NGTDMFeatureName not in feature_vectors:
            feature_vectors[NGTDMFeatureName] = val
        else:
            print('Error: NGTDM key existing! %s'%NGTDMFeatureName)
            # break
        # print('  ', key, ':', val)
    print('ADDED %s NGTDM Features'%len(results))
    #
    # Show GLDM features; Gray Level Dependence Matrix (GLDM) Features
    #
    features = gldm.RadiomicsGLDM(image, mask, **settings)
    features.enableAllFeatures()

    # print('Will calculate the following GLDM features: ')
    # for f in features.enabledFeatures.keys():
    #   print('  ', f)
    #   print(getattr(features, 'get%sFeatureValue' % f).__doc__)

    # print('Calculating GLDM features...')
    results = features.execute()
    # print('done')

    # print('Calculated GLDM features: ')
    for (key, val) in six.iteritems(results):
        GLDMFeatureName = '%s_%s' % ('GLDM', key)
        if GLDMFeatureName not in feature_vectors:
            feature_vectors[GLDMFeatureName] = val
        else:
            print('Error: GLDM key existing! %s'%GLDMFeatureName)
            # break
        # print('  ', key, ':', val)

    print('ADDED %s GLDM Features'%len(results))

    #
    # Show FirstOrder features, calculated on a LoG filtered image
    #
    if applyLog:
      sigmaValues = np.arange(5., 0., -.5)[::1]
      cnt = 0
      for logImage, imageTypeName, inputKwargs in imageoperations.getLoGImage(image, mask, sigma=sigmaValues):
        cnt += 1
        features = firstorder.RadiomicsFirstOrder(logImage, mask, **inputKwargs)
        features.enableAllFeatures()
        results = features.execute()
        print('ADDEDING %s/%s Features...'%(cnt, len(logImage)))
        for (key, val) in six.iteritems(results):
            laplacianFeatureName = '%s_%s' % (imageTypeName, key)
            if laplacianFeatureName not in feature_vectors:
                feature_vectors[laplacianFeatureName] = val
            else:
                print('Error: LoG key existing! %s'%laplacianFeatureName)
                # break
            # print('  ', laplacianFeatureName, ':', val)
    #
    # Show FirstOrder features, calculated on a wavelet filtered image
    #
    if applyWavelet:
        cnt = 0
        for decompositionImage, decompositionName, inputKwargs in imageoperations.getWaveletImage(image, mask):
            cnt+=1
            features = firstorder.RadiomicsFirstOrder(decompositionImage, mask, **inputKwargs)
            features.enableAllFeatures()
            results = features.execute()
            print('ADDEDING %s/%s WAVELET Features...'%(cnt, str(decompositionName)))
            print('Calculated firstorder features with wavelet ', decompositionName)
            for (key, val) in six.iteritems(results):
                waveletFeatureName = '%s_%s' % (str(decompositionName), key)
                if waveletFeatureName not in feature_vectors:
                    feature_vectors[waveletFeatureName] = val
                else:
                    print('Error: wavelet key existing! %s'%waveletFeatureName)
                    # break
                # print('  ', waveletFeatureName, ':', val)

    mask = None
    image = None
    features = None
    os.remove(cache_file)
    print('DONE!')
    return feature_vectors
コード例 #12
0
def features_extractor(patients_nrrd_path, valid_IDs, applyLog = False, applyWavelet = False):
    feature_vectors = {}
    cnt = 0
    for case_id in valid_IDs:
        feature_vectors[case_id] = {}
        cnt += 1
        # try:
        ct_nrrd_path = os.path.join(patients_nrrd_path,case_id, "image.nrrd")
        ss_nrrd_path = os.path.join(patients_nrrd_path,case_id, "mask.nrrd")
        print("Reading ct image")
        image = sitk.ReadImage(ct_nrrd_path)
        # image, header = nrrd.read(ct_nrrd_path)
        print("Reading roi mask")
        mask = sitk.ReadImage(ss_nrrd_path)
        # mask, header = nrrd.read(ss_nrrd_path)
        print("Getting ct image array")
        image_array = sitk.GetArrayFromImage(image)
        print("Getting roi mask array")
        mask_array = sitk.GetArrayFromImage(mask)
        print(image_array.shape, mask_array.shape)
        # simple_plot_nrrd(image_array, mask_array, sliceNumber=75, plotSrc='sitk')
        print (cnt, "_ Calculating features: ",case_id)   

        settings = {'binWidth': 25,
                'interpolator': sitk.sitkBSpline,
                'resampledPixelSpacing': None}
        interpolator = settings.get('interpolator')
        resampledPixelSpacing = settings.get('resampledPixelSpacing')
        if interpolator is not None and resampledPixelSpacing is not None:
            image, mask = imageoperations.resampleImage(image, mask, **settings)
        bb, correctedMask = imageoperations.checkMask(image, mask)
        if correctedMask is not None:
          mask = correctedMask
        image, mask = imageoperations.cropToTumorMask(image, mask, bb)
        
        firstOrderFeatures = firstorder.RadiomicsFirstOrder(image, mask, **settings)
        # firstOrderFeatures.enableFeatureByName('Mean', True)
        firstOrderFeatures.enableAllFeatures()

        # print('Will calculate the following first order features: ')
        # for f in firstOrderFeatures.enabledFeatures.keys():
        #   print('  ', f)
        #   print(getattr(firstOrderFeatures, 'get%sFeatureValue' % f).__doc__)

        # print('Calculating first order features...')
        results = firstOrderFeatures.execute()
        # print('done')

        print('Calculated first order features: ')
        for (key, val) in six.iteritems(results):
            firstOrderFeatureName = '%s_%s' % ('firstOrder', key)
            if firstOrderFeatureName not in feature_vectors[case_id]:
                feature_vectors[case_id][firstOrderFeatureName] = val
            else:
                print('Error: firstOrder key existing! %s'%firstOrderFeatureName)
                # break
            # print('  ', key, ':', val)

        #
        # Show Shape features
        #

        shapeFeatures = shape.RadiomicsShape(image, mask, **settings)
        shapeFeatures.enableAllFeatures()

        # print('Will calculate the following Shape features: ')
        # for f in shapeFeatures.enabledFeatures.keys():
        #   print('  ', f)
        #   print(getattr(shapeFeatures, 'get%sFeatureValue' % f).__doc__)

        # print('Calculating Shape features...')
        results = shapeFeatures.execute()
        # print('done')

        print('Calculated Shape features: ')
        for (key, val) in six.iteritems(results):
            ShapeFeatureName = '%s_%s' % ('Shape', key)
            if ShapeFeatureName not in feature_vectors[case_id]:
                feature_vectors[case_id][ShapeFeatureName] = val
            else:
                print('Error: shape key existing! %s'%ShapeFeatureName)
                # break
            # print('  ', key, ':', val)

        #
        # Show GLCM features: Gray Level Co-occurrence Matrix (GLCM) Features
        #
        glcmFeatures = glcm.RadiomicsGLCM(image, mask, **settings)
        glcmFeatures.enableAllFeatures()

        # print('Will calculate the following GLCM features: ')
        # for f in glcmFeatures.enabledFeatures.keys():
        #   print('  ', f)
        #   print(getattr(glcmFeatures, 'get%sFeatureValue' % f).__doc__)

        # print('Calculating GLCM features...')
        results = glcmFeatures.execute()
        # print('done')

        print('Calculated GLCM features: ')
        for (key, val) in six.iteritems(results):
            GLCMFeatureName = '%s_%s' % ('GLCM', key)
            if GLCMFeatureName not in feature_vectors[case_id]:
                feature_vectors[case_id][GLCMFeatureName] = val
            else:
                print('Error: GLCM key existing! %s'%GLCMFeatureName)
                # break
            # print('  ', key, ':', val)



        #
        # Show GLSZM features; Gray Level Size Zone Matrix (GLSZM) Features
        #
        glszmFeatures = glszm.RadiomicsGLSZM(image, mask, **settings)
        glszmFeatures.enableAllFeatures()

        # print('Will calculate the following GLSZM features: ')
        # for f in glszmFeatures.enabledFeatures.keys():
        #   print('  ', f)
        #   print(getattr(glszmFeatures, 'get%sFeatureValue' % f).__doc__)

        # print('Calculating GLSZM features...')
        results = glszmFeatures.execute()
        print('done')

        print('Calculated GLSZM features: ')
        for (key, val) in six.iteritems(results):
            GLSZMFeatureName = '%s_%s' % ('GLSZM', key)
            if GLSZMFeatureName not in feature_vectors[case_id]:
                feature_vectors[case_id][GLSZMFeatureName] = val
            else:
                print('Error: GLSZM key existing! %s'%GLSZMFeatureName)
                # break
            # print('  ', key, ':', val)


        #
        # Show GLRLM features; Gray Level Run Length Matrix (GLRLM) Features
        #
        glrlmFeatures = glrlm.RadiomicsGLRLM(image, mask, **settings)
        glrlmFeatures.enableAllFeatures()

        # print('Will calculate the following GLRLM features: ')
        # for f in glrlmFeatures.enabledFeatures.keys():
        #   print('  ', f)
        #   print(getattr(glrlmFeatures, 'get%sFeatureValue' % f).__doc__)

        # print('Calculating GLRLM features...')
        results = glrlmFeatures.execute()
        # print('done')

        print('Calculated GLRLM features: ')
        for (key, val) in six.iteritems(results):
            GLRLMFeatureName = '%s_%s' % ('GLRLM', key)
            if GLRLMFeatureName not in feature_vectors[case_id]:
                feature_vectors[case_id][GLRLMFeatureName] = val
            else:
                print('Error: GLRLM key existing! %s'%GLRLMFeatureName)
                # break
            # print('  ', key, ':', val)

        #
        # Show NGTDM features; Neighbouring Gray Tone Difference Matrix (NGTDM) Features
        #
        ngtdmFeatures = ngtdm.RadiomicsNGTDM(image, mask, **settings)
        ngtdmFeatures.enableAllFeatures()

        # print('Will calculate the following NGTDM features: ')
        # for f in ngtdmFeatures.enabledFeatures.keys():
        #   print('  ', f)
        #   print(getattr(ngtdmFeatures, 'get%sFeatureValue' % f).__doc__)

        # print('Calculating NGTDM features...')
        results = ngtdmFeatures.execute()
        # print('done')

        print('Calculated NGTDM features: ')
        for (key, val) in six.iteritems(results):
            NGTDMFeatureName = '%s_%s' % ('NGTDM', key)
            if NGTDMFeatureName not in feature_vectors[case_id]:
                feature_vectors[case_id][NGTDMFeatureName] = val
            else:
                print('Error: NGTDM key existing! %s'%NGTDMFeatureName)
                # break
            # print('  ', key, ':', val)

        #
        # Show GLDM features; Gray Level Dependence Matrix (GLDM) Features
        #
        gldmFeatures = gldm.RadiomicsGLDM(image, mask, **settings)
        gldmFeatures.enableAllFeatures()

        # print('Will calculate the following GLDM features: ')
        # for f in gldmFeatures.enabledFeatures.keys():
        #   print('  ', f)
        #   print(getattr(gldmFeatures, 'get%sFeatureValue' % f).__doc__)

        # print('Calculating GLDM features...')
        results = gldmFeatures.execute()
        # print('done')

        print('Calculated GLDM features: ')
        for (key, val) in six.iteritems(results):
            GLDMFeatureName = '%s_%s' % ('GLDM', key)
            if GLDMFeatureName not in feature_vectors[case_id]:
                feature_vectors[case_id][GLDMFeatureName] = val
            else:
                print('Error: GLDM key existing! %s'%GLDMFeatureName)
                # break
            # print('  ', key, ':', val)


        #
        # Show FirstOrder features, calculated on a LoG filtered image
        #
        if applyLog:
          sigmaValues = np.arange(5., 0., -.5)[::1]
          for logImage, imageTypeName, inputKwargs in imageoperations.getLoGImage(image, mask, sigma=sigmaValues):
            logFirstorderFeatures = firstorder.RadiomicsFirstOrder(logImage, mask, **inputKwargs)
            logFirstorderFeatures.enableAllFeatures()
            results = logFirstorderFeatures.execute()
            for (key, val) in np.iteritems(results):
                laplacianFeatureName = '%s_%s' % (imageTypeName, key)
                if laplacianFeatureName not in feature_vectors[case_id]:
                    feature_vectors[case_id][laplacianFeatureName] = val
                else:
                    print('Error: LoG key existing! %s'%laplacianFeatureName)
                    # break
                # print('  ', laplacianFeatureName, ':', val)
        #
        # Show FirstOrder features, calculated on a wavelet filtered image
        #
        if applyWavelet:
          for decompositionImage, decompositionName, inputKwargs in imageoperations.getWaveletImage(image, mask):
            waveletFirstOrderFeaturs = firstorder.RadiomicsFirstOrder(decompositionImage, mask, **inputKwargs)
            waveletFirstOrderFeaturs.enableAllFeatures()
            results = waveletFirstOrderFeaturs.execute()
            print('Calculated firstorder features with wavelet ', decompositionName)
            for (key, val) in six.iteritems(results):
                waveletFeatureName = '%s_%s' % (str(decompositionName), key)
                if waveletFeatureName not in feature_vectors[case_id]:
                    feature_vectors[case_id][waveletFeatureName] = val
                else:
                    print('Error: wavelet key existing! %s'%waveletFeatureName)
                    # break
                # print('  ', waveletFeatureName, ':', val)

        mask = None
        image = None
    return feature_vectors