idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
232,000
def get_value_from_set ( self , key ) : key = key . lower ( ) if self . _remotelib : while True : value = self . _remotelib . run_keyword ( 'get_value_from_set' , [ key , self . _my_id ] , { } ) if value : return value time . sleep ( 0.1 ) logger . debug ( 'waiting for a value' ) else : return _PabotLib . get_value_fro...
Get a value from previously reserved value set .
232,001
def release_value_set ( self ) : if self . _remotelib : self . _remotelib . run_keyword ( 'release_value_set' , [ self . _my_id ] , { } ) else : _PabotLib . release_value_set ( self , self . _my_id )
Release a reserved value set so that other executions can use it also .
232,002
def install_all_patches ( ) : from . import mysqldb from . import psycopg2 from . import strict_redis from . import sqlalchemy from . import tornado_http from . import urllib from . import urllib2 from . import requests mysqldb . install_patches ( ) psycopg2 . install_patches ( ) strict_redis . install_patches ( ) sqla...
A convenience method that installs all available hooks .
232,003
def install_patches ( patchers = 'all' ) : if patchers is None or patchers == 'all' : install_all_patches ( ) return if not _valid_args ( patchers ) : raise ValueError ( 'patchers argument must be None, "all", or a list' ) for patch_func_name in patchers : logging . info ( 'Loading client hook %s' , patch_func_name ) p...
Usually called from middleware to install client hooks specified in the client_hooks section of the configuration .
232,004
def install_client_interceptors ( client_interceptors = ( ) ) : if not _valid_args ( client_interceptors ) : raise ValueError ( 'client_interceptors argument must be a list' ) from . . http_client import ClientInterceptors for client_interceptor in client_interceptors : logging . info ( 'Loading client interceptor %s' ...
Install client interceptors for the patchers .
232,005
def _load_symbol ( name ) : module_name , key = name . rsplit ( '.' , 1 ) try : module = importlib . import_module ( module_name ) except ImportError as err : module_name , class_name = module_name . rsplit ( '.' , 1 ) module = importlib . import_module ( module_name ) cls = getattr ( module , class_name , None ) if cl...
Load a symbol by name .
232,006
def span_in_stack_context ( span ) : if not isinstance ( opentracing . tracer . scope_manager , TornadoScopeManager ) : raise RuntimeError ( 'scope_manager is not TornadoScopeManager' ) context = tracer_stack_context ( ) entered_context = _TracerEnteredStackContext ( context ) if span is None : return entered_context o...
Create Tornado s StackContext that stores the given span in the thread - local request context . This function is intended for use in Tornado applications based on IOLoop although will work fine in single - threaded apps like Flask albeit with more overhead .
232,007
def traced_function ( func = None , name = None , on_start = None , require_active_trace = False ) : if func is None : return functools . partial ( traced_function , name = name , on_start = on_start , require_active_trace = require_active_trace ) if name : operation_name = name else : operation_name = func . __name__ ...
A decorator that enables tracing of the wrapped function or Tornado co - routine provided there is a parent span already established .
232,008
def start_child_span ( operation_name , tracer = None , parent = None , tags = None ) : tracer = tracer or opentracing . tracer return tracer . start_span ( operation_name = operation_name , child_of = parent . context if parent else None , tags = tags )
Start a new span as a child of parent_span . If parent_span is None start a new root span .
232,009
def before_request ( request , tracer = None ) : if tracer is None : tracer = opentracing . tracer tags_dict = { tags . SPAN_KIND : tags . SPAN_KIND_RPC_SERVER , tags . HTTP_URL : request . full_url , } remote_ip = request . remote_ip if remote_ip : tags_dict [ tags . PEER_HOST_IPV4 ] = remote_ip caller_name = request ...
Attempts to extract a tracing span from incoming request . If no tracing context is passed in the headers or the data cannot be parsed a new root span is started .
232,010
def _parse_wsgi_headers ( wsgi_environ ) : prefix = 'HTTP_' p_len = len ( prefix ) headers = { key [ p_len : ] . replace ( '_' , '-' ) . lower ( ) : val for ( key , val ) in wsgi_environ . items ( ) if key . startswith ( prefix ) } return headers
HTTP headers are presented in WSGI environment with HTTP_ prefix . This method finds those headers removes the prefix converts underscores to dashes and converts to lower case .
232,011
def append ( cls , interceptor ) : cls . _check ( interceptor ) cls . _interceptors . append ( interceptor )
Add interceptor to the end of the internal list .
232,012
def insert ( cls , index , interceptor ) : cls . _check ( interceptor ) cls . _interceptors . insert ( index , interceptor )
Add interceptor to the given index in the internal list .
232,013
def singleton ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : if wrapper . __call_state__ == CALLED : return ret = func ( * args , ** kwargs ) wrapper . __call_state__ = CALLED return ret def reset ( ) : wrapper . __call_state__ = NOT_CALLED wrapper . reset = reset reset ( ) wrapper . __ori...
This decorator allows you to make sure that a function is called once and only once . Note that recursive functions will still work .
232,014
def smooth_image ( image , sigma , sigma_in_physical_coordinates = True , FWHM = False , max_kernel_width = 32 ) : if image . components == 1 : return _smooth_image_helper ( image , sigma , sigma_in_physical_coordinates , FWHM , max_kernel_width ) else : imagelist = utils . split_channels ( image ) newimages = [ ] for ...
Smooth an image
232,015
def build_template ( initial_template = None , image_list = None , iterations = 3 , gradient_step = 0.2 , ** kwargs ) : wt = 1.0 / len ( image_list ) if initial_template is None : initial_template = image_list [ 0 ] * 0 for i in range ( len ( image_list ) ) : initial_template = initial_template + image_list [ i ] * wt ...
Estimate an optimal template from an input image_list
232,016
def resample_image ( image , resample_params , use_voxels = False , interp_type = 1 ) : if image . components == 1 : inimage = image . clone ( 'float' ) outimage = image . clone ( 'float' ) rsampar = 'x' . join ( [ str ( rp ) for rp in resample_params ] ) args = [ image . dimension , inimage , outimage , rsampar , int ...
Resample image by spacing or number of voxels with various interpolators . Works with multi - channel images .
232,017
def apply_ants_transform ( transform , data , data_type = "point" , reference = None , ** kwargs ) : return transform . apply ( data , data_type , reference , ** kwargs )
Apply ANTsTransform to data
232,018
def compose_ants_transforms ( transform_list ) : precision = transform_list [ 0 ] . precision dimension = transform_list [ 0 ] . dimension for tx in transform_list : if precision != tx . precision : raise ValueError ( 'All transforms must have the same precision' ) if dimension != tx . dimension : raise ValueError ( 'A...
Compose multiple ANTsTransform s together
232,019
def transform_index_to_physical_point ( image , index ) : if not isinstance ( image , iio . ANTsImage ) : raise ValueError ( 'image must be ANTsImage type' ) if isinstance ( index , np . ndarray ) : index = index . tolist ( ) if not isinstance ( index , ( tuple , list ) ) : raise ValueError ( 'index must be tuple or li...
Get spatial point from index of an image .
232,020
def invert ( self ) : libfn = utils . get_lib_fn ( 'inverseTransform%s' % ( self . _libsuffix ) ) inv_tx_ptr = libfn ( self . pointer ) new_tx = ANTsTransform ( precision = self . precision , dimension = self . dimension , transform_type = self . transform_type , pointer = inv_tx_ptr ) return new_tx
Invert the transform
232,021
def apply ( self , data , data_type = 'point' , reference = None , ** kwargs ) : if data_type == 'point' : return self . apply_to_point ( data ) elif data_type == 'vector' : return self . apply_to_vector ( data ) elif data_type == 'image' : return self . apply_to_image ( data , reference , ** kwargs )
Apply transform to data
232,022
def apply_to_point ( self , point ) : libfn = utils . get_lib_fn ( 'transformPoint%s' % ( self . _libsuffix ) ) return tuple ( libfn ( self . pointer , point ) )
Apply transform to a point
232,023
def apply_to_vector ( self , vector ) : if isinstance ( vector , np . ndarray ) : vector = vector . tolist ( ) libfn = utils . get_lib_fn ( 'transformVector%s' % ( self . _libsuffix ) ) return np . asarray ( libfn ( self . pointer , vector ) )
Apply transform to a vector
232,024
def plot_hist ( image , threshold = 0. , fit_line = False , normfreq = True , title = None , grid = True , xlabel = None , ylabel = None , facecolor = 'green' , alpha = 0.75 ) : img_arr = image . numpy ( ) . flatten ( ) img_arr = img_arr [ np . abs ( img_arr ) > threshold ] if normfreq != False : normfreq = 1. if normf...
Plot a histogram from an ANTsImage
232,025
def morphology ( image , operation , radius , mtype = 'binary' , value = 1 , shape = 'ball' , radius_is_parametric = False , thickness = 1 , lines = 3 , include_center = False ) : if image . components > 1 : raise ValueError ( 'multichannel images not yet supported' ) _sflag_dict = { 'ball' : 1 , 'box' : 2 , 'cross' : ...
Apply morphological operations to an image
232,026
def rgb_to_vector ( image ) : if image . pixeltype != 'unsigned char' : image = image . clone ( 'unsigned char' ) idim = image . dimension libfn = utils . get_lib_fn ( 'RgbToVector%i' % idim ) new_ptr = libfn ( image . pointer ) new_img = iio . ANTsImage ( pixeltype = image . pixeltype , dimension = image . dimension ,...
Convert an RGB ANTsImage to a Vector ANTsImage
232,027
def vector_to_rgb ( image ) : if image . pixeltype != 'unsigned char' : image = image . clone ( 'unsigned char' ) idim = image . dimension libfn = utils . get_lib_fn ( 'VectorToRgb%i' % idim ) new_ptr = libfn ( image . pointer ) new_img = iio . ANTsImage ( pixeltype = image . pixeltype , dimension = image . dimension ,...
Convert an Vector ANTsImage to a RGB ANTsImage
232,028
def quantile ( image , q , nonzero = True ) : img_arr = image . numpy ( ) if isinstance ( q , ( list , tuple ) ) : q = [ qq * 100. if qq <= 1. else qq for qq in q ] if nonzero : img_arr = img_arr [ img_arr > 0 ] vals = [ np . percentile ( img_arr , qq ) for qq in q ] return tuple ( vals ) elif isinstance ( q , ( float ...
Get the quantile values from an ANTsImage
232,029
def bandpass_filter_matrix ( matrix , tr = 1 , lowf = 0.01 , highf = 0.1 , order = 3 ) : from scipy . signal import butter , filtfilt def butter_bandpass ( lowcut , highcut , fs , order ) : nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b , a = butter ( order , [ low , high ] , btype = 'band' ) return b , a def...
Bandpass filter the input time series image
232,030
def compcor ( boldImage , ncompcor = 4 , quantile = 0.975 , mask = None , filter_type = False , degree = 2 ) : def compute_tSTD ( M , quantile , x = 0 , axis = 0 ) : stdM = np . std ( M , axis = axis ) stdM [ stdM == 0 ] = x stdM [ np . isnan ( stdM ) ] = x tt = round ( quantile * 100 ) threshold_std = np . percentile ...
Compute noise components from the input image
232,031
def n3_bias_field_correction ( image , downsample_factor = 3 ) : outimage = image . clone ( ) args = [ image . dimension , image , outimage , downsample_factor ] processed_args = pargs . _int_antsProcessArguments ( args ) libfn = utils . get_lib_fn ( 'N3BiasFieldCorrection' ) libfn ( processed_args ) return outimage
N3 Bias Field Correction
232,032
def n4_bias_field_correction ( image , mask = None , shrink_factor = 4 , convergence = { 'iters' : [ 50 , 50 , 50 , 50 ] , 'tol' : 1e-07 } , spline_param = 200 , verbose = False , weight_mask = None ) : if image . pixeltype != 'float' : image = image . clone ( 'float' ) iters = convergence [ 'iters' ] tol = convergence...
N4 Bias Field Correction
232,033
def abp_n4 ( image , intensity_truncation = ( 0.025 , 0.975 , 256 ) , mask = None , usen3 = False ) : if ( not isinstance ( intensity_truncation , ( list , tuple ) ) ) or ( len ( intensity_truncation ) != 3 ) : raise ValueError ( 'intensity_truncation must be list/tuple with 3 values' ) outimage = iMath ( image , 'Trun...
Truncate outlier intensities and bias correct with the N4 algorithm .
232,034
def image_mutual_information ( image1 , image2 ) : if ( image1 . pixeltype != 'float' ) or ( image2 . pixeltype != 'float' ) : raise ValueError ( 'Both images must have float pixeltype' ) if image1 . dimension != image2 . dimension : raise ValueError ( 'Both images must have same dimension' ) libfn = utils . get_lib_fn...
Compute mutual information between two ANTsImage types
232,035
def get_mask ( image , low_thresh = None , high_thresh = None , cleanup = 2 ) : cleanup = int ( cleanup ) if isinstance ( image , iio . ANTsImage ) : if image . pixeltype != 'float' : image = image . clone ( 'float' ) if low_thresh is None : low_thresh = image . mean ( ) if high_thresh is None : high_thresh = image . m...
Get a binary mask image from the given image after thresholding
232,036
def label_image_centroids ( image , physical = False , convex = True , verbose = False ) : d = image . shape if len ( d ) != 3 : raise ValueError ( 'image must be 3 dimensions' ) xcoords = np . asarray ( np . arange ( d [ 0 ] ) . tolist ( ) * ( d [ 1 ] * d [ 2 ] ) ) ycoords = np . asarray ( np . repeat ( np . arange ( ...
Converts a label image to coordinates summarizing their positions
232,037
def transform ( self , X , y = None ) : insuffix = X . _libsuffix multires_fn = utils . get_lib_fn ( 'multiResolutionAntsImage%s' % ( insuffix ) ) casted_ptrs = multires_fn ( X . pointer , self . levels ) imgs = [ ] for casted_ptr in casted_ptrs : img = iio . ANTsImage ( pixeltype = X . pixeltype , dimension = X . dime...
Generate a set of multi - resolution ANTsImage types
232,038
def transform ( self , X , y = None ) : insuffix = X . _libsuffix cast_fn = utils . get_lib_fn ( 'locallyBlurAntsImage%s' % ( insuffix ) ) casted_ptr = cast_fn ( X . pointer , self . iters , self . conductance ) return iio . ANTsImage ( pixeltype = X . pixeltype , dimension = X . dimension , components = X . components...
Locally blur an image by applying a gradient anisotropic diffusion filter .
232,039
def get_data ( name = None ) : if name is None : files = [ ] for fname in os . listdir ( data_path ) : if ( fname . endswith ( '.nii.gz' ) ) or ( fname . endswith ( '.jpg' ) or ( fname . endswith ( '.csv' ) ) ) : fname = os . path . join ( data_path , fname ) files . append ( fname ) return files else : datapath = None...
Get ANTsPy test data filename
232,040
def convolve_image ( image , kernel_image , crop = True ) : if not isinstance ( image , iio . ANTsImage ) : raise ValueError ( 'image must be ANTsImage type' ) if not isinstance ( kernel_image , iio . ANTsImage ) : raise ValueError ( 'kernel must be ANTsImage type' ) orig_ptype = image . pixeltype if image . pixeltype ...
Convolve one image with another
232,041
def ndimage_to_list ( image ) : inpixeltype = image . pixeltype dimension = image . dimension components = 1 imageShape = image . shape nSections = imageShape [ dimension - 1 ] subdimension = dimension - 1 suborigin = iio . get_origin ( image ) [ 0 : subdimension ] subspacing = iio . get_spacing ( image ) [ 0 : subdime...
Split a n dimensional ANTsImage into a list of n - 1 dimensional ANTsImages
232,042
def _int_antsProcessArguments ( args ) : p_args = [ ] if isinstance ( args , dict ) : for argname , argval in args . items ( ) : if '-MULTINAME-' in argname : argname = argname [ : argname . find ( '-MULTINAME-' ) ] if argval is not None : if len ( argname ) > 1 : p_args . append ( '--%s' % argname ) else : p_args . ap...
Needs to be better validated .
232,043
def initialize_eigenanatomy ( initmat , mask = None , initlabels = None , nreps = 1 , smoothing = 0 ) : if isinstance ( initmat , iio . ANTsImage ) : if mask is not None : selectvec = mask > 0 else : selectvec = initmat > 0 initmatvec = initmat [ selectvec ] if initlabels is None : ulabs = np . sort ( np . unique ( ini...
InitializeEigenanatomy is a helper function to initialize sparseDecom and sparseDecom2 . Can be used to estimate sparseness parameters per eigenvector . The user then only chooses nvecs and optional regularization parameters .
232,044
def eig_seg ( mask , img_list , apply_segmentation_to_images = False , cthresh = 0 , smooth = 1 ) : maskvox = mask > 0 maskseg = mask . clone ( ) maskseg [ maskvox ] = 0 if isinstance ( img_list , np . ndarray ) : mydata = img_list elif isinstance ( img_list , ( tuple , list ) ) : mydata = core . image_list_to_matrix (...
Segment a mask into regions based on the max value in an image list . At a given voxel the segmentation label will contain the index to the image that has the largest value . If the 3rd image has the greatest value the segmentation label will be 3 at that voxel .
232,045
def label_stats ( image , label_image ) : image_float = image . clone ( 'float' ) label_image_int = label_image . clone ( 'unsigned int' ) libfn = utils . get_lib_fn ( 'labelStats%iD' % image . dimension ) df = libfn ( image_float . pointer , label_image_int . pointer ) return pd . DataFrame ( df )
Get label statistics from image
232,046
def spacing ( self ) : libfn = utils . get_lib_fn ( 'getSpacing%s' % self . _libsuffix ) return libfn ( self . pointer )
Get image spacing
232,047
def set_spacing ( self , new_spacing ) : if not isinstance ( new_spacing , ( tuple , list ) ) : raise ValueError ( 'arg must be tuple or list' ) if len ( new_spacing ) != self . dimension : raise ValueError ( 'must give a spacing value for each dimension (%i)' % self . dimension ) libfn = utils . get_lib_fn ( 'setSpaci...
Set image spacing
232,048
def origin ( self ) : libfn = utils . get_lib_fn ( 'getOrigin%s' % self . _libsuffix ) return libfn ( self . pointer )
Get image origin
232,049
def set_origin ( self , new_origin ) : if not isinstance ( new_origin , ( tuple , list ) ) : raise ValueError ( 'arg must be tuple or list' ) if len ( new_origin ) != self . dimension : raise ValueError ( 'must give a origin value for each dimension (%i)' % self . dimension ) libfn = utils . get_lib_fn ( 'setOrigin%s' ...
Set image origin
232,050
def direction ( self ) : libfn = utils . get_lib_fn ( 'getDirection%s' % self . _libsuffix ) return libfn ( self . pointer )
Get image direction
232,051
def set_direction ( self , new_direction ) : if isinstance ( new_direction , ( tuple , list ) ) : new_direction = np . asarray ( new_direction ) if not isinstance ( new_direction , np . ndarray ) : raise ValueError ( 'arg must be np.ndarray or tuple or list' ) if len ( new_direction ) != self . dimension : raise ValueE...
Set image direction
232,052
def astype ( self , dtype ) : if dtype not in _supported_dtypes : raise ValueError ( 'Datatype %s not supported. Supported types are %s' % ( dtype , _supported_dtypes ) ) pixeltype = _npy_to_itk_map [ dtype ] return self . clone ( pixeltype )
Cast & clone an ANTsImage to a given numpy datatype .
232,053
def new_image_like ( self , data ) : if not isinstance ( data , np . ndarray ) : raise ValueError ( 'data must be a numpy array' ) if not self . has_components : if data . shape != self . shape : raise ValueError ( 'given array shape (%s) and image array shape (%s) do not match' % ( data . shape , self . shape ) ) else...
Create a new ANTsImage with the same header information but with a new image array .
232,054
def to_file ( self , filename ) : filename = os . path . expanduser ( filename ) libfn = utils . get_lib_fn ( 'toFile%s' % self . _libsuffix ) libfn ( self . pointer , filename )
Write the ANTsImage to file
232,055
def apply ( self , fn ) : this_array = self . numpy ( ) new_array = fn ( this_array ) return self . new_image_like ( new_array )
Apply an arbitrary function to ANTsImage .
232,056
def sum ( self , axis = None , keepdims = False ) : return self . numpy ( ) . sum ( axis = axis , keepdims = keepdims )
Return sum along specified axis
232,057
def range ( self , axis = None ) : return ( self . min ( axis = axis ) , self . max ( axis = axis ) )
Return range tuple along specified axis
232,058
def argrange ( self , axis = None ) : amin = self . argmin ( axis = axis ) amax = self . argmax ( axis = axis ) if axis is None : return ( amin , amax ) else : return np . stack ( [ amin , amax ] ) . T
Return argrange along specified axis
232,059
def unique ( self , sort = False ) : unique_vals = np . unique ( self . numpy ( ) ) if sort : unique_vals = np . sort ( unique_vals ) return unique_vals
Return unique set of values in image
232,060
def uniquekeys ( self , metakey = None ) : if metakey is None : return self . _uniquekeys else : if metakey not in self . metakeys ( ) : raise ValueError ( 'metakey %s does not exist' % metakey ) return self . _uniquekeys [ metakey ]
Get keys for a given metakey
232,061
def label_clusters ( image , min_cluster_size = 50 , min_thresh = 1e-6 , max_thresh = 1 , fully_connected = False ) : dim = image . dimension clust = threshold_image ( image , min_thresh , max_thresh ) temp = int ( fully_connected ) args = [ dim , clust , clust , min_cluster_size , temp ] processed_args = _int_antsProc...
This will give a unique ID to each connected component 1 through N of size > min_cluster_size
232,062
def make_points_image ( pts , mask , radius = 5 ) : powers_lblimg = mask * 0 npts = len ( pts ) dim = mask . dimension if pts . shape [ 1 ] != dim : raise ValueError ( 'points dimensionality should match that of images' ) for r in range ( npts ) : pt = pts [ r , : ] idx = tio . transform_physical_point_to_index ( mask ...
Create label image from physical space points
232,063
def weingarten_image_curvature ( image , sigma = 1.0 , opt = 'mean' ) : if image . dimension not in { 2 , 3 } : raise ValueError ( 'image must be 2D or 3D' ) if image . dimension == 2 : d = image . shape temp = np . zeros ( list ( d ) + [ 10 ] ) for k in range ( 1 , 7 ) : voxvals = image [ : d [ 0 ] , : d [ 1 ] ] temp ...
Uses the weingarten map to estimate image mean or gaussian curvature
232,064
def from_numpy ( data , origin = None , spacing = None , direction = None , has_components = False , is_rgb = False ) : data = data . astype ( 'float32' ) if data . dtype . name == 'float64' else data img = _from_numpy ( data . T . copy ( ) , origin , spacing , direction , has_components , is_rgb ) return img
Create an ANTsImage object from a numpy array
232,065
def _from_numpy ( data , origin = None , spacing = None , direction = None , has_components = False , is_rgb = False ) : if is_rgb : has_components = True ndim = data . ndim if has_components : ndim -= 1 dtype = data . dtype . name ptype = _npy_to_itk_map [ dtype ] data = np . array ( data ) if origin is None : origin ...
Internal function for creating an ANTsImage
232,066
def make_image ( imagesize , voxval = 0 , spacing = None , origin = None , direction = None , has_components = False , pixeltype = 'float' ) : if isinstance ( imagesize , iio . ANTsImage ) : img = imagesize . clone ( ) sel = imagesize > 0 if voxval . ndim > 1 : voxval = voxval . flatten ( ) if ( len ( voxval ) == int (...
Make an image with given size and voxel value or given a mask and vector
232,067
def matrix_to_images ( data_matrix , mask ) : if data_matrix . ndim > 2 : data_matrix = data_matrix . reshape ( data_matrix . shape [ 0 ] , - 1 ) numimages = len ( data_matrix ) numVoxelsInMatrix = data_matrix . shape [ 1 ] numVoxelsInMask = ( mask >= 0.5 ) . sum ( ) if numVoxelsInMask != numVoxelsInMatrix : raise Valu...
Unmasks rows of a matrix and writes as images
232,068
def images_to_matrix ( image_list , mask = None , sigma = None , epsilon = 0.5 ) : def listfunc ( x ) : if np . sum ( np . array ( x . shape ) - np . array ( mask . shape ) ) != 0 : x = reg . resample_image_to_target ( x , mask , 2 ) return x [ mask ] if mask is None : mask = utils . get_mask ( image_list [ 0 ] ) num_i...
Read images into rows of a matrix given a mask - much faster for large datasets as it is based on C ++ implementations .
232,069
def timeseries_to_matrix ( image , mask = None ) : temp = utils . ndimage_to_list ( image ) if mask is None : mask = temp [ 0 ] * 0 + 1 return image_list_to_matrix ( temp , mask )
Convert a timeseries image into a matrix .
232,070
def matrix_to_timeseries ( image , matrix , mask = None ) : if mask is None : mask = temp [ 0 ] * 0 + 1 temp = matrix_to_images ( matrix , mask ) newImage = utils . list_to_ndimage ( image , temp ) iio . copy_image_info ( image , newImage ) return ( newImage )
converts a matrix to a ND image .
232,071
def image_header_info ( filename ) : if not os . path . exists ( filename ) : raise Exception ( 'filename does not exist' ) libfn = utils . get_lib_fn ( 'antsImageHeaderInfo' ) retval = libfn ( filename ) retval [ 'dimensions' ] = tuple ( retval [ 'dimensions' ] ) retval [ 'origin' ] = tuple ( [ round ( o , 4 ) for o i...
Read file info from image header
232,072
def image_read ( filename , dimension = None , pixeltype = 'float' , reorient = False ) : if filename . endswith ( '.npy' ) : filename = os . path . expanduser ( filename ) img_array = np . load ( filename ) if os . path . exists ( filename . replace ( '.npy' , '.json' ) ) : with open ( filename . replace ( '.npy' , '....
Read an ANTsImage from file
232,073
def dicom_read ( directory , pixeltype = 'float' ) : slices = [ ] imgidx = 0 for imgpath in os . listdir ( directory ) : if imgpath . endswith ( '.dcm' ) : if imgidx == 0 : tmp = image_read ( os . path . join ( directory , imgpath ) , dimension = 3 , pixeltype = pixeltype ) origin = tmp . origin spacing = tmp . spacing...
Read a set of dicom files in a directory into a single ANTsImage . The origin of the resulting 3D image will be the origin of the first dicom image read .
232,074
def image_write ( image , filename , ri = False ) : if filename . endswith ( '.npy' ) : img_array = image . numpy ( ) img_header = { 'origin' : image . origin , 'spacing' : image . spacing , 'direction' : image . direction . tolist ( ) , 'components' : image . components } np . save ( filename , img_array ) with open (...
Write an ANTsImage to file
232,075
def otsu_segmentation ( image , k , mask = None ) : if mask is not None : image = image . mask_image ( mask ) seg = image . threshold_image ( 'Otsu' , k ) return seg
Otsu image segmentation
232,076
def crop_image ( image , label_image = None , label = 1 ) : inpixeltype = image . pixeltype ndim = image . dimension if image . pixeltype != 'float' : image = image . clone ( 'float' ) if label_image is None : label_image = get_mask ( image ) if label_image . pixeltype != 'float' : label_image = label_image . clone ( '...
Use a label image to crop a smaller ANTsImage from within a larger ANTsImage
232,077
def decrop_image ( cropped_image , full_image ) : inpixeltype = 'float' if cropped_image . pixeltype != 'float' : inpixeltype = cropped_image . pixeltype cropped_image = cropped_image . clone ( 'float' ) if full_image . pixeltype != 'float' : full_image = full_image . clone ( 'float' ) libfn = utils . get_lib_fn ( 'cro...
The inverse function for ants . crop_image
232,078
def kmeans_segmentation ( image , k , kmask = None , mrf = 0.1 ) : dim = image . dimension kmimage = utils . iMath ( image , 'Normalize' ) if kmask is None : kmask = utils . get_mask ( kmimage , 0.01 , 1 , cleanup = 2 ) kmask = utils . iMath ( kmask , 'FillHoles' ) . threshold_image ( 1 , 2 ) nhood = 'x' . join ( [ '1'...
K - means image segmentation that is a wrapper around ants . atropos
232,079
def reorient_image2 ( image , orientation = 'RAS' ) : if image . dimension != 3 : raise ValueError ( 'image must have 3 dimensions' ) inpixeltype = image . pixeltype ndim = image . dimension if image . pixeltype != 'float' : image = image . clone ( 'float' ) libfn = utils . get_lib_fn ( 'reorientImage2' ) itkimage = li...
Reorient an image .
232,080
def reorient_image ( image , axis1 , axis2 = None , doreflection = False , doscale = 0 , txfn = None ) : inpixeltype = image . pixeltype if image . pixeltype != 'float' : image = image . clone ( 'float' ) axis_was_none = False if axis2 is None : axis_was_none = True axis2 = [ 0 ] * image . dimension axis1 = np . array ...
Align image along a specified axis
232,081
def get_center_of_mass ( image ) : if image . pixeltype != 'float' : image = image . clone ( 'float' ) libfn = utils . get_lib_fn ( 'centerOfMass%s' % image . _libsuffix ) com = libfn ( image . pointer ) return tuple ( com )
Compute an image center of mass in physical space which is defined as the mean of the intensity weighted voxel coordinate system .
232,082
def to_nibabel ( image ) : if image . dimension != 3 : raise ValueError ( 'Only 3D images currently supported' ) import nibabel as nib array_data = image . numpy ( ) affine = np . hstack ( [ image . direction * np . diag ( image . spacing ) , np . array ( image . origin ) . reshape ( 3 , 1 ) ] ) affine = np . vstack ( ...
Convert an ANTsImage to a Nibabel image
232,083
def from_nibabel ( nib_image ) : tmpfile = mktemp ( suffix = '.nii.gz' ) nib_image . to_filename ( tmpfile ) new_img = iio2 . image_read ( tmpfile ) os . remove ( tmpfile ) return new_img
Convert a nibabel image to an ANTsImage
232,084
def transform ( self , X = None , y = None ) : shear_x = random . gauss ( self . shear_range [ 0 ] , self . shear_range [ 1 ] ) shear_y = random . gauss ( self . shear_range [ 0 ] , self . shear_range [ 1 ] ) shear_z = random . gauss ( self . shear_range [ 0 ] , self . shear_range [ 1 ] ) self . params = ( shear_x , sh...
Transform an image using an Affine transform with shear parameters randomly generated from the user - specified range . Return the transform if X = None .
232,085
def transform ( self , X = None , y = None ) : zoom_x = np . exp ( random . gauss ( np . log ( self . zoom_range [ 0 ] ) , np . log ( self . zoom_range [ 1 ] ) ) ) zoom_y = np . exp ( random . gauss ( np . log ( self . zoom_range [ 0 ] ) , np . log ( self . zoom_range [ 1 ] ) ) ) zoom_z = np . exp ( random . gauss ( np...
Transform an image using an Affine transform with zoom parameters randomly generated from the user - specified range . Return the transform if X = None .
232,086
def transform ( self , X = None , y = None ) : translation_x , translation_y = self . translation translation_matrix = np . array ( [ [ 1 , 0 , translation_x ] , [ 0 , 1 , translation_y ] ] ) self . tx . set_parameters ( translation_matrix ) if self . lazy or X is None : return self . tx else : return self . tx . apply...
Transform an image using an Affine transform with the given translation parameters . Return the transform if X = None .
232,087
def transform ( self , X = None , y = None ) : translation_x = random . gauss ( self . translation_range [ 0 ] , self . translation_range [ 1 ] ) translation_y = random . gauss ( self . translation_range [ 0 ] , self . translation_range [ 1 ] ) self . params = ( translation_x , translation_y ) tx = Translate2D ( ( tran...
Transform an image using an Affine transform with translation parameters randomly generated from the user - specified range . Return the transform if X = None .
232,088
def transform ( self , X = None , y = None ) : shear = [ math . pi / 180 * s for s in self . shear ] shear_x , shear_y = shear shear_matrix = np . array ( [ [ 1 , shear_x , 0 ] , [ shear_y , 1 , 0 ] ] ) self . tx . set_parameters ( shear_matrix ) if self . lazy or X is None : return self . tx else : return self . tx . ...
Transform an image using an Affine transform with the given shear parameters . Return the transform if X = None .
232,089
def transform ( self , X = None , y = None ) : zoom_x , zoom_y = self . zoom self . params = ( zoom_x , zoom_y ) zoom_matrix = np . array ( [ [ zoom_x , 0 , 0 ] , [ 0 , zoom_y , 0 ] ] ) self . tx . set_parameters ( zoom_matrix ) if self . lazy or X is None : return self . tx else : return self . tx . apply_to_image ( X...
Transform an image using an Affine transform with the given zoom parameters . Return the transform if X = None .
232,090
def kelly_kapowski ( s , g , w , its = 50 , r = 0.025 , m = 1.5 , ** kwargs ) : if isinstance ( s , iio . ANTsImage ) : s = s . clone ( 'unsigned int' ) d = s . dimension outimg = g . clone ( ) kellargs = { 'd' : d , 's' : s , 'g' : g , 'w' : w , 'c' : its , 'r' : r , 'm' : m , 'o' : outimg } for k , v in kwargs . item...
Compute cortical thickness using the DiReCT algorithm .
232,091
def new_ants_transform ( precision = 'float' , dimension = 3 , transform_type = 'AffineTransform' , parameters = None ) : libfn = utils . get_lib_fn ( 'newAntsTransform%s%i' % ( utils . short_ptype ( precision ) , dimension ) ) itk_tx = libfn ( precision , dimension , transform_type ) ants_tx = tio . ANTsTransform ( pr...
Create a new ANTsTransform
232,092
def create_ants_transform ( transform_type = 'AffineTransform' , precision = 'float' , dimension = 3 , matrix = None , offset = None , center = None , translation = None , parameters = None , fixed_parameters = None , displacement_field = None , supported_types = False ) : def _check_arg ( arg , dim = 1 ) : if arg is N...
Create and initialize an ANTsTransform
232,093
def read_transform ( filename , dimension = 2 , precision = 'float' ) : filename = os . path . expanduser ( filename ) if not os . path . exists ( filename ) : raise ValueError ( 'filename does not exist!' ) libfn1 = utils . get_lib_fn ( 'getTransformDimensionFromFile' ) dimension = libfn1 ( filename ) libfn2 = utils ....
Read a transform from file
232,094
def write_transform ( transform , filename ) : filename = os . path . expanduser ( filename ) libfn = utils . get_lib_fn ( 'writeTransform%s' % ( transform . _libsuffix ) ) libfn ( transform . pointer , filename )
Write ANTsTransform to file
232,095
def reflect_image ( image , axis = None , tx = None , metric = 'mattes' ) : if axis is None : axis = image . dimension - 1 if ( axis > image . dimension ) or ( axis < 0 ) : axis = image . dimension - 1 rflct = mktemp ( suffix = '.mat' ) libfn = utils . get_lib_fn ( 'reflectionMatrix%s' % image . _libsuffix ) libfn ( im...
Reflect an image along an axis
232,096
def create_sampler ( self , inputs , targets , input_reader = None , target_reader = None , input_transform = None , target_transform = None , co_transform = None , input_return_processor = None , target_return_processor = None , co_return_processor = None ) : pass
Create a BIDSSampler that can be used to generate infinite augmented samples
232,097
def slice_image ( image , axis = None , idx = None ) : if image . dimension < 3 : raise ValueError ( 'image must have at least 3 dimensions' ) inpixeltype = image . pixeltype ndim = image . dimension if image . pixeltype != 'float' : image = image . clone ( 'float' ) libfn = utils . get_lib_fn ( 'sliceImageF%i' % ndim ...
Slice an image .
232,098
def pad_image ( image , shape = None , pad_width = None , value = 0.0 , return_padvals = False ) : inpixeltype = image . pixeltype ndim = image . dimension if image . pixeltype != 'float' : image = image . clone ( 'float' ) if pad_width is None : if shape is None : shape = [ max ( image . shape ) ] * image . dimension ...
Pad an image to have the given shape or to be isotropic .
232,099
def set_fixed_image ( self , image ) : if not isinstance ( image , iio . ANTsImage ) : raise ValueError ( 'image must be ANTsImage type' ) if image . dimension != self . dimension : raise ValueError ( 'image dim (%i) does not match metric dim (%i)' % ( image . dimension , self . dimension ) ) self . _metric . setFixedI...
Set Fixed ANTsImage for metric