This example shows how to use the radiomics package and the feature extractor.
The feature extractor handles preprocessing, and then calls the needed featureclasses to calculate the features.
It is also possible to directly instantiate the feature classes. However, this is not recommended for use outside debugging or development. For more information, see helloFeatureClass
.
In [12]:
from __future__ import print_function
import sys
import os
import logging
import six
from radiomics import featureextractor, getFeatureClasses
import radiomics
Regulate verbosity of PyRadiomics (outputs to stderr)
In [13]:
# Regulate verbosity with radiomics.setVerbosity
# radiomics.setVerbosity(logging.INFO) # Use logging.DEBUG for maximum output, default verbosity level = WARNING
Set up logging to a log file
In [14]:
# Get the PyRadiomics logger (default log-level = INFO)
logger = radiomics.logger
logger.setLevel(logging.DEBUG) # set level to DEBUG to include debug log messages in log file
# Write out all log entries to a file
handler = logging.FileHandler(filename='testLog.txt', mode='w')
formatter = logging.Formatter('%(levelname)s:%(name)s: %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
Test cases can be downloaded to temporary files. This is handled by the radiomics.getTestCase()
function, which checks if the requested test case is available and if not, downloads it. It returns a tuple with the location of the image and mask of the requested test case, or (None, None) if it fails.
Alternatively, if the data is available somewhere locally, this directory can be passed as a second argument to radiomics.getTestCase()
. If that directory does not exist or does not contain the testcase, functionality reverts to default and tries to download the test data.
If getting the test case fails, PyRadiomics will log an error explaining the cause.
In [15]:
featureClasses = getFeatureClasses()
imageName, maskName = radiomics.getTestCase('brain1')
if imageName is None or maskName is None: # Something went wrong, in this case PyRadiomics will also log an error
raise Exception('Error getting testcase!') # Raise exception to prevent cells below from running in case of "run all"
In [16]:
# Use a parameter file, this customizes the extraction settings and also specifies the input image types to use and which features should be extracted
params = os.path.join('..', 'examples', 'exampleSettings', 'Params.yaml')
extractor = featureextractor.RadiomicsFeatureExtractor(params)
In [17]:
# Alternative: use hardcoded settings (separate for settings, input image types and enabled features)
settings = {}
settings['binWidth'] = 25
settings['resampledPixelSpacing'] = None
# settings['resampledPixelSpacing'] = [3, 3, 3] # This is an example for defining resampling (voxels with size 3x3x3mm)
settings['interpolator'] = 'sitkBSpline'
settings['verbose'] = True
extractor = featureextractor.RadiomicsFeatureExtractor(**settings)
In [18]:
# By default, only 'Original' (no filter applied) is enabled. Optionally enable some image types:
# extractor.enableImageTypeByName('Wavelet')
# extractor.enableImageTypeByName('LoG', customArgs={'sigma':[3.0]})
# extractor.enableImageTypeByName('Square')
# extractor.enableImageTypeByName('SquareRoot')
# extractor.enableImageTypeByName('Exponential')
# extractor.enableImageTypeByName('Logarithm')
# Alternative; set filters in one operation
# This updates current enabled image types, i.e. overwrites custom settings specified per filter.
# However, image types already enabled, but not passed in this call, are not disabled or altered.
# extractor.enableImageTypes(Wavelet={}, LoG={'sigma':[3.0]})
print('Enabled input images:')
for imageType in extractor.enabledImagetypes.keys():
print('\t' + imageType)
In [19]:
# Disable all classes
extractor.disableAllFeatures()
# Enable all features in firstorder
extractor.enableFeatureClassByName('firstorder')
# Alternative; only enable 'Mean' and 'Skewness' features in firstorder
# extractor.enableFeaturesByName(firstorder=['Mean', 'Skewness'])
In [20]:
print('Active features:')
for cls, features in six.iteritems(extractor.enabledFeatures):
if len(features) == 0:
features = [f for f, deprecated in six.iteritems(featureClasses[cls].getFeatureNames()) if not deprecated]
for f in features:
print(f)
print(getattr(featureClasses[cls], 'get%sFeatureValue' % f).__doc__)
In [21]:
print('Calculating features')
featureVector = extractor.execute(imageName, maskName)
In [22]:
# Show output
for featureName in featureVector.keys():
print('Computed %s: %s' % (featureName, featureVector[featureName]))