repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
mkorpela/pabot | pabot/pabotlib.py | PabotLib.get_value_from_set | def get_value_from_set(self, key):
"""
Get a value from previously reserved value set.
"""
#TODO: This should be done locally.
# We do not really need to call centralised server if the set is already
# reserved as the data there is immutable during execution
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_from_set(self, key, self._my_id) | python | def get_value_from_set(self, key):
"""
Get a value from previously reserved value set.
"""
#TODO: This should be done locally.
# We do not really need to call centralised server if the set is already
# reserved as the data there is immutable during execution
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_from_set(self, key, self._my_id) | [
"def",
"get_value_from_set",
"(",
"self",
",",
"key",
")",
":",
"#TODO: This should be done locally. ",
"# We do not really need to call centralised server if the set is already",
"# reserved as the data there is immutable during execution",
"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_from_set",
"(",
"self",
",",
"key",
",",
"self",
".",
"_my_id",
")"
] | Get a value from previously reserved value set. | [
"Get",
"a",
"value",
"from",
"previously",
"reserved",
"value",
"set",
"."
] | b7d85546a58e398d579bb14fd9135858ec08a031 | https://github.com/mkorpela/pabot/blob/b7d85546a58e398d579bb14fd9135858ec08a031/pabot/pabotlib.py#L260-L277 | train | 232,000 |
mkorpela/pabot | pabot/pabotlib.py | PabotLib.release_value_set | def release_value_set(self):
"""
Release a reserved value set so that other executions can use it also.
"""
if self._remotelib:
self._remotelib.run_keyword('release_value_set', [self._my_id], {})
else:
_PabotLib.release_value_set(self, self._my_id) | python | def release_value_set(self):
"""
Release a reserved value set so that other executions can use it also.
"""
if self._remotelib:
self._remotelib.run_keyword('release_value_set', [self._my_id], {})
else:
_PabotLib.release_value_set(self, self._my_id) | [
"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. | [
"Release",
"a",
"reserved",
"value",
"set",
"so",
"that",
"other",
"executions",
"can",
"use",
"it",
"also",
"."
] | b7d85546a58e398d579bb14fd9135858ec08a031 | https://github.com/mkorpela/pabot/blob/b7d85546a58e398d579bb14fd9135858ec08a031/pabot/pabotlib.py#L279-L286 | train | 232,001 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/client_hooks/__init__.py | install_all_patches | def install_all_patches():
"""
A convenience method that installs all available hooks.
If a specific module is not available on the path, it is ignored.
"""
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()
sqlalchemy.install_patches()
tornado_http.install_patches()
urllib.install_patches()
urllib2.install_patches()
requests.install_patches() | python | def install_all_patches():
"""
A convenience method that installs all available hooks.
If a specific module is not available on the path, it is ignored.
"""
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()
sqlalchemy.install_patches()
tornado_http.install_patches()
urllib.install_patches()
urllib2.install_patches()
requests.install_patches() | [
"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",
"(",
")",
"sqlalchemy",
".",
"install_patches",
"(",
")",
"tornado_http",
".",
"install_patches",
"(",
")",
"urllib",
".",
"install_patches",
"(",
")",
"urllib2",
".",
"install_patches",
"(",
")",
"requests",
".",
"install_patches",
"(",
")"
] | A convenience method that installs all available hooks.
If a specific module is not available on the path, it is ignored. | [
"A",
"convenience",
"method",
"that",
"installs",
"all",
"available",
"hooks",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/client_hooks/__init__.py#L33-L55 | train | 232,002 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/client_hooks/__init__.py | install_patches | def install_patches(patchers='all'):
"""
Usually called from middleware to install client hooks
specified in the client_hooks section of the configuration.
:param patchers: a list of patchers to run. Acceptable values include:
* None - installs all client patches
* 'all' - installs all client patches
* empty list - does not install any patches
* list of function names - executes the functions
"""
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)
patch_func = _load_symbol(patch_func_name)
logging.info('Applying client hook %s', patch_func_name)
patch_func() | python | def install_patches(patchers='all'):
"""
Usually called from middleware to install client hooks
specified in the client_hooks section of the configuration.
:param patchers: a list of patchers to run. Acceptable values include:
* None - installs all client patches
* 'all' - installs all client patches
* empty list - does not install any patches
* list of function names - executes the functions
"""
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)
patch_func = _load_symbol(patch_func_name)
logging.info('Applying client hook %s', patch_func_name)
patch_func() | [
"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",
")",
"patch_func",
"=",
"_load_symbol",
"(",
"patch_func_name",
")",
"logging",
".",
"info",
"(",
"'Applying client hook %s'",
",",
"patch_func_name",
")",
"patch_func",
"(",
")"
] | Usually called from middleware to install client hooks
specified in the client_hooks section of the configuration.
:param patchers: a list of patchers to run. Acceptable values include:
* None - installs all client patches
* 'all' - installs all client patches
* empty list - does not install any patches
* list of function names - executes the functions | [
"Usually",
"called",
"from",
"middleware",
"to",
"install",
"client",
"hooks",
"specified",
"in",
"the",
"client_hooks",
"section",
"of",
"the",
"configuration",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/client_hooks/__init__.py#L58-L79 | train | 232,003 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/client_hooks/__init__.py | install_client_interceptors | def install_client_interceptors(client_interceptors=()):
"""
Install client interceptors for the patchers.
:param client_interceptors: a list of client interceptors to install.
Should be a list of classes
"""
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', client_interceptor)
interceptor_class = _load_symbol(client_interceptor)
logging.info('Adding client interceptor %s', client_interceptor)
ClientInterceptors.append(interceptor_class()) | python | def install_client_interceptors(client_interceptors=()):
"""
Install client interceptors for the patchers.
:param client_interceptors: a list of client interceptors to install.
Should be a list of classes
"""
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', client_interceptor)
interceptor_class = _load_symbol(client_interceptor)
logging.info('Adding client interceptor %s', client_interceptor)
ClientInterceptors.append(interceptor_class()) | [
"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'",
",",
"client_interceptor",
")",
"interceptor_class",
"=",
"_load_symbol",
"(",
"client_interceptor",
")",
"logging",
".",
"info",
"(",
"'Adding client interceptor %s'",
",",
"client_interceptor",
")",
"ClientInterceptors",
".",
"append",
"(",
"interceptor_class",
"(",
")",
")"
] | Install client interceptors for the patchers.
:param client_interceptors: a list of client interceptors to install.
Should be a list of classes | [
"Install",
"client",
"interceptors",
"for",
"the",
"patchers",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/client_hooks/__init__.py#L82-L98 | train | 232,004 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/client_hooks/__init__.py | _load_symbol | def _load_symbol(name):
"""Load a symbol by name.
:param str name: The name to load, specified by `module.attr`.
:returns: The attribute value. If the specified module does not contain
the requested attribute then `None` is returned.
"""
module_name, key = name.rsplit('.', 1)
try:
module = importlib.import_module(module_name)
except ImportError as err:
# it's possible the symbol is a class method
module_name, class_name = module_name.rsplit('.', 1)
module = importlib.import_module(module_name)
cls = getattr(module, class_name, None)
if cls:
attr = getattr(cls, key, None)
else:
raise err
else:
attr = getattr(module, key, None)
if not callable(attr):
raise ValueError('%s is not callable (was %r)' % (name, attr))
return attr | python | def _load_symbol(name):
"""Load a symbol by name.
:param str name: The name to load, specified by `module.attr`.
:returns: The attribute value. If the specified module does not contain
the requested attribute then `None` is returned.
"""
module_name, key = name.rsplit('.', 1)
try:
module = importlib.import_module(module_name)
except ImportError as err:
# it's possible the symbol is a class method
module_name, class_name = module_name.rsplit('.', 1)
module = importlib.import_module(module_name)
cls = getattr(module, class_name, None)
if cls:
attr = getattr(cls, key, None)
else:
raise err
else:
attr = getattr(module, key, None)
if not callable(attr):
raise ValueError('%s is not callable (was %r)' % (name, attr))
return attr | [
"def",
"_load_symbol",
"(",
"name",
")",
":",
"module_name",
",",
"key",
"=",
"name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"except",
"ImportError",
"as",
"err",
":",
"# it's possible the symbol is a class method",
"module_name",
",",
"class_name",
"=",
"module_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"cls",
"=",
"getattr",
"(",
"module",
",",
"class_name",
",",
"None",
")",
"if",
"cls",
":",
"attr",
"=",
"getattr",
"(",
"cls",
",",
"key",
",",
"None",
")",
"else",
":",
"raise",
"err",
"else",
":",
"attr",
"=",
"getattr",
"(",
"module",
",",
"key",
",",
"None",
")",
"if",
"not",
"callable",
"(",
"attr",
")",
":",
"raise",
"ValueError",
"(",
"'%s is not callable (was %r)'",
"%",
"(",
"name",
",",
"attr",
")",
")",
"return",
"attr"
] | Load a symbol by name.
:param str name: The name to load, specified by `module.attr`.
:returns: The attribute value. If the specified module does not contain
the requested attribute then `None` is returned. | [
"Load",
"a",
"symbol",
"by",
"name",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/client_hooks/__init__.py#L106-L129 | train | 232,005 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/request_context.py | span_in_stack_context | def span_in_stack_context(span):
"""
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.
## Usage example in Tornado application
Suppose you have a method `handle_request(request)` in the http server.
Instead of calling it directly, use a wrapper:
.. code-block:: python
from opentracing_instrumentation import request_context
@tornado.gen.coroutine
def handle_request_wrapper(request, actual_handler, *args, **kwargs)
request_wrapper = TornadoRequestWrapper(request=request)
span = http_server.before_request(request=request_wrapper)
with request_context.span_in_stack_context(span):
return actual_handler(*args, **kwargs)
:param span:
:return:
Return StackContext that wraps the request context.
"""
if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
raise RuntimeError('scope_manager is not TornadoScopeManager')
# Enter the newly created stack context so we have
# storage available for Span activation.
context = tracer_stack_context()
entered_context = _TracerEnteredStackContext(context)
if span is None:
return entered_context
opentracing.tracer.scope_manager.activate(span, False)
assert opentracing.tracer.active_span is not None
assert opentracing.tracer.active_span is span
return entered_context | python | def span_in_stack_context(span):
"""
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.
## Usage example in Tornado application
Suppose you have a method `handle_request(request)` in the http server.
Instead of calling it directly, use a wrapper:
.. code-block:: python
from opentracing_instrumentation import request_context
@tornado.gen.coroutine
def handle_request_wrapper(request, actual_handler, *args, **kwargs)
request_wrapper = TornadoRequestWrapper(request=request)
span = http_server.before_request(request=request_wrapper)
with request_context.span_in_stack_context(span):
return actual_handler(*args, **kwargs)
:param span:
:return:
Return StackContext that wraps the request context.
"""
if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
raise RuntimeError('scope_manager is not TornadoScopeManager')
# Enter the newly created stack context so we have
# storage available for Span activation.
context = tracer_stack_context()
entered_context = _TracerEnteredStackContext(context)
if span is None:
return entered_context
opentracing.tracer.scope_manager.activate(span, False)
assert opentracing.tracer.active_span is not None
assert opentracing.tracer.active_span is span
return entered_context | [
"def",
"span_in_stack_context",
"(",
"span",
")",
":",
"if",
"not",
"isinstance",
"(",
"opentracing",
".",
"tracer",
".",
"scope_manager",
",",
"TornadoScopeManager",
")",
":",
"raise",
"RuntimeError",
"(",
"'scope_manager is not TornadoScopeManager'",
")",
"# Enter the newly created stack context so we have",
"# storage available for Span activation.",
"context",
"=",
"tracer_stack_context",
"(",
")",
"entered_context",
"=",
"_TracerEnteredStackContext",
"(",
"context",
")",
"if",
"span",
"is",
"None",
":",
"return",
"entered_context",
"opentracing",
".",
"tracer",
".",
"scope_manager",
".",
"activate",
"(",
"span",
",",
"False",
")",
"assert",
"opentracing",
".",
"tracer",
".",
"active_span",
"is",
"not",
"None",
"assert",
"opentracing",
".",
"tracer",
".",
"active_span",
"is",
"span",
"return",
"entered_context"
] | 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.
## Usage example in Tornado application
Suppose you have a method `handle_request(request)` in the http server.
Instead of calling it directly, use a wrapper:
.. code-block:: python
from opentracing_instrumentation import request_context
@tornado.gen.coroutine
def handle_request_wrapper(request, actual_handler, *args, **kwargs)
request_wrapper = TornadoRequestWrapper(request=request)
span = http_server.before_request(request=request_wrapper)
with request_context.span_in_stack_context(span):
return actual_handler(*args, **kwargs)
:param span:
:return:
Return StackContext that wraps the request context. | [
"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",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/request_context.py#L181-L226 | train | 232,006 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/local_span.py | traced_function | def traced_function(func=None, name=None, on_start=None,
require_active_trace=False):
"""
A decorator that enables tracing of the wrapped function or
Tornado co-routine provided there is a parent span already established.
.. code-block:: python
@traced_function
def my_function1(arg1, arg2=None)
...
:param func: decorated function or Tornado co-routine
:param name: optional name to use as the Span.operation_name.
If not provided, func.__name__ will be used.
:param on_start: an optional callback to be executed once the child span
is started, but before the decorated function is called. It can be
used to set any additional tags on the span, perhaps by inspecting
the decorated function arguments. The callback must have a signature
`(span, *args, *kwargs)`, where the last two collections are the
arguments passed to the actual decorated function.
.. code-block:: python
def extract_call_site_tag(span, *args, *kwargs)
if 'call_site_tag' in kwargs:
span.set_tag('call_site_tag', kwargs['call_site_tag'])
@traced_function(on_start=extract_call_site_tag)
@tornado.get.coroutine
def my_function(arg1, arg2=None, call_site_tag=None)
...
:param require_active_trace: controls what to do when there is no active
trace. If require_active_trace=True, then no span is created.
If require_active_trace=False, a new trace is started.
:return: returns a tracing decorator
"""
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__
@functools.wraps(func)
def decorator(*args, **kwargs):
parent_span = get_current_span()
if parent_span is None and require_active_trace:
return func(*args, **kwargs)
span = utils.start_child_span(
operation_name=operation_name, parent=parent_span)
if callable(on_start):
on_start(span, *args, **kwargs)
# We explicitly invoke deactivation callback for the StackContext,
# because there are scenarios when it gets retained forever, for
# example when a Periodic Callback is scheduled lazily while in the
# scope of a tracing StackContext.
with span_in_stack_context(span) as deactivate_cb:
try:
res = func(*args, **kwargs)
# Tornado co-routines usually return futures, so we must wait
# until the future is completed, in order to accurately
# capture the function's execution time.
if tornado.concurrent.is_future(res):
def done_callback(future):
deactivate_cb()
exception = future.exception()
if exception is not None:
span.log(event='exception', payload=exception)
span.set_tag('error', 'true')
span.finish()
res.add_done_callback(done_callback)
else:
deactivate_cb()
span.finish()
return res
except Exception as e:
deactivate_cb()
span.log(event='exception', payload=e)
span.set_tag('error', 'true')
span.finish()
raise
return decorator | python | def traced_function(func=None, name=None, on_start=None,
require_active_trace=False):
"""
A decorator that enables tracing of the wrapped function or
Tornado co-routine provided there is a parent span already established.
.. code-block:: python
@traced_function
def my_function1(arg1, arg2=None)
...
:param func: decorated function or Tornado co-routine
:param name: optional name to use as the Span.operation_name.
If not provided, func.__name__ will be used.
:param on_start: an optional callback to be executed once the child span
is started, but before the decorated function is called. It can be
used to set any additional tags on the span, perhaps by inspecting
the decorated function arguments. The callback must have a signature
`(span, *args, *kwargs)`, where the last two collections are the
arguments passed to the actual decorated function.
.. code-block:: python
def extract_call_site_tag(span, *args, *kwargs)
if 'call_site_tag' in kwargs:
span.set_tag('call_site_tag', kwargs['call_site_tag'])
@traced_function(on_start=extract_call_site_tag)
@tornado.get.coroutine
def my_function(arg1, arg2=None, call_site_tag=None)
...
:param require_active_trace: controls what to do when there is no active
trace. If require_active_trace=True, then no span is created.
If require_active_trace=False, a new trace is started.
:return: returns a tracing decorator
"""
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__
@functools.wraps(func)
def decorator(*args, **kwargs):
parent_span = get_current_span()
if parent_span is None and require_active_trace:
return func(*args, **kwargs)
span = utils.start_child_span(
operation_name=operation_name, parent=parent_span)
if callable(on_start):
on_start(span, *args, **kwargs)
# We explicitly invoke deactivation callback for the StackContext,
# because there are scenarios when it gets retained forever, for
# example when a Periodic Callback is scheduled lazily while in the
# scope of a tracing StackContext.
with span_in_stack_context(span) as deactivate_cb:
try:
res = func(*args, **kwargs)
# Tornado co-routines usually return futures, so we must wait
# until the future is completed, in order to accurately
# capture the function's execution time.
if tornado.concurrent.is_future(res):
def done_callback(future):
deactivate_cb()
exception = future.exception()
if exception is not None:
span.log(event='exception', payload=exception)
span.set_tag('error', 'true')
span.finish()
res.add_done_callback(done_callback)
else:
deactivate_cb()
span.finish()
return res
except Exception as e:
deactivate_cb()
span.log(event='exception', payload=e)
span.set_tag('error', 'true')
span.finish()
raise
return decorator | [
"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__",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"decorator",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"parent_span",
"=",
"get_current_span",
"(",
")",
"if",
"parent_span",
"is",
"None",
"and",
"require_active_trace",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"span",
"=",
"utils",
".",
"start_child_span",
"(",
"operation_name",
"=",
"operation_name",
",",
"parent",
"=",
"parent_span",
")",
"if",
"callable",
"(",
"on_start",
")",
":",
"on_start",
"(",
"span",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# We explicitly invoke deactivation callback for the StackContext,",
"# because there are scenarios when it gets retained forever, for",
"# example when a Periodic Callback is scheduled lazily while in the",
"# scope of a tracing StackContext.",
"with",
"span_in_stack_context",
"(",
"span",
")",
"as",
"deactivate_cb",
":",
"try",
":",
"res",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Tornado co-routines usually return futures, so we must wait",
"# until the future is completed, in order to accurately",
"# capture the function's execution time.",
"if",
"tornado",
".",
"concurrent",
".",
"is_future",
"(",
"res",
")",
":",
"def",
"done_callback",
"(",
"future",
")",
":",
"deactivate_cb",
"(",
")",
"exception",
"=",
"future",
".",
"exception",
"(",
")",
"if",
"exception",
"is",
"not",
"None",
":",
"span",
".",
"log",
"(",
"event",
"=",
"'exception'",
",",
"payload",
"=",
"exception",
")",
"span",
".",
"set_tag",
"(",
"'error'",
",",
"'true'",
")",
"span",
".",
"finish",
"(",
")",
"res",
".",
"add_done_callback",
"(",
"done_callback",
")",
"else",
":",
"deactivate_cb",
"(",
")",
"span",
".",
"finish",
"(",
")",
"return",
"res",
"except",
"Exception",
"as",
"e",
":",
"deactivate_cb",
"(",
")",
"span",
".",
"log",
"(",
"event",
"=",
"'exception'",
",",
"payload",
"=",
"e",
")",
"span",
".",
"set_tag",
"(",
"'error'",
",",
"'true'",
")",
"span",
".",
"finish",
"(",
")",
"raise",
"return",
"decorator"
] | A decorator that enables tracing of the wrapped function or
Tornado co-routine provided there is a parent span already established.
.. code-block:: python
@traced_function
def my_function1(arg1, arg2=None)
...
:param func: decorated function or Tornado co-routine
:param name: optional name to use as the Span.operation_name.
If not provided, func.__name__ will be used.
:param on_start: an optional callback to be executed once the child span
is started, but before the decorated function is called. It can be
used to set any additional tags on the span, perhaps by inspecting
the decorated function arguments. The callback must have a signature
`(span, *args, *kwargs)`, where the last two collections are the
arguments passed to the actual decorated function.
.. code-block:: python
def extract_call_site_tag(span, *args, *kwargs)
if 'call_site_tag' in kwargs:
span.set_tag('call_site_tag', kwargs['call_site_tag'])
@traced_function(on_start=extract_call_site_tag)
@tornado.get.coroutine
def my_function(arg1, arg2=None, call_site_tag=None)
...
:param require_active_trace: controls what to do when there is no active
trace. If require_active_trace=True, then no span is created.
If require_active_trace=False, a new trace is started.
:return: returns a tracing decorator | [
"A",
"decorator",
"that",
"enables",
"tracing",
"of",
"the",
"wrapped",
"function",
"or",
"Tornado",
"co",
"-",
"routine",
"provided",
"there",
"is",
"a",
"parent",
"span",
"already",
"established",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/local_span.py#L64-L153 | train | 232,007 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/utils.py | start_child_span | def start_child_span(operation_name, tracer=None, parent=None, tags=None):
"""
Start a new span as a child of parent_span. If parent_span is None,
start a new root span.
:param operation_name: operation name
:param tracer: Tracer or None (defaults to opentracing.tracer)
:param parent: parent Span or None
:param tags: optional tags
:return: new span
"""
tracer = tracer or opentracing.tracer
return tracer.start_span(
operation_name=operation_name,
child_of=parent.context if parent else None,
tags=tags
) | python | def start_child_span(operation_name, tracer=None, parent=None, tags=None):
"""
Start a new span as a child of parent_span. If parent_span is None,
start a new root span.
:param operation_name: operation name
:param tracer: Tracer or None (defaults to opentracing.tracer)
:param parent: parent Span or None
:param tags: optional tags
:return: new span
"""
tracer = tracer or opentracing.tracer
return tracer.start_span(
operation_name=operation_name,
child_of=parent.context if parent else None,
tags=tags
) | [
"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.
:param operation_name: operation name
:param tracer: Tracer or None (defaults to opentracing.tracer)
:param parent: parent Span or None
:param tags: optional tags
:return: new span | [
"Start",
"a",
"new",
"span",
"as",
"a",
"child",
"of",
"parent_span",
".",
"If",
"parent_span",
"is",
"None",
"start",
"a",
"new",
"root",
"span",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/utils.py#L25-L41 | train | 232,008 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/http_server.py | before_request | def before_request(request, tracer=None):
"""
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.
:param request: HTTP request with `.headers` property exposed
that satisfies a regular dictionary interface
:param tracer: optional tracer instance to use. If not specified
the global opentracing.tracer will be used.
:return: returns a new, already started span.
"""
if tracer is None: # pragma: no cover
tracer = opentracing.tracer
# we need to prepare tags upfront, mainly because RPC_SERVER tag must be
# set when starting the span, to support Zipkin's one-span-per-RPC model
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.caller_name
if caller_name:
tags_dict[tags.PEER_SERVICE] = caller_name
remote_port = request.remote_port
if remote_port:
tags_dict[tags.PEER_PORT] = remote_port
operation = request.operation
try:
carrier = {}
for key, value in six.iteritems(request.headers):
carrier[key] = value
parent_ctx = tracer.extract(
format=Format.HTTP_HEADERS, carrier=carrier
)
except Exception as e:
logging.exception('trace extract failed: %s' % e)
parent_ctx = None
span = tracer.start_span(
operation_name=operation,
child_of=parent_ctx,
tags=tags_dict)
return span | python | def before_request(request, tracer=None):
"""
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.
:param request: HTTP request with `.headers` property exposed
that satisfies a regular dictionary interface
:param tracer: optional tracer instance to use. If not specified
the global opentracing.tracer will be used.
:return: returns a new, already started span.
"""
if tracer is None: # pragma: no cover
tracer = opentracing.tracer
# we need to prepare tags upfront, mainly because RPC_SERVER tag must be
# set when starting the span, to support Zipkin's one-span-per-RPC model
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.caller_name
if caller_name:
tags_dict[tags.PEER_SERVICE] = caller_name
remote_port = request.remote_port
if remote_port:
tags_dict[tags.PEER_PORT] = remote_port
operation = request.operation
try:
carrier = {}
for key, value in six.iteritems(request.headers):
carrier[key] = value
parent_ctx = tracer.extract(
format=Format.HTTP_HEADERS, carrier=carrier
)
except Exception as e:
logging.exception('trace extract failed: %s' % e)
parent_ctx = None
span = tracer.start_span(
operation_name=operation,
child_of=parent_ctx,
tags=tags_dict)
return span | [
"def",
"before_request",
"(",
"request",
",",
"tracer",
"=",
"None",
")",
":",
"if",
"tracer",
"is",
"None",
":",
"# pragma: no cover",
"tracer",
"=",
"opentracing",
".",
"tracer",
"# we need to prepare tags upfront, mainly because RPC_SERVER tag must be",
"# set when starting the span, to support Zipkin's one-span-per-RPC model",
"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",
".",
"caller_name",
"if",
"caller_name",
":",
"tags_dict",
"[",
"tags",
".",
"PEER_SERVICE",
"]",
"=",
"caller_name",
"remote_port",
"=",
"request",
".",
"remote_port",
"if",
"remote_port",
":",
"tags_dict",
"[",
"tags",
".",
"PEER_PORT",
"]",
"=",
"remote_port",
"operation",
"=",
"request",
".",
"operation",
"try",
":",
"carrier",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"request",
".",
"headers",
")",
":",
"carrier",
"[",
"key",
"]",
"=",
"value",
"parent_ctx",
"=",
"tracer",
".",
"extract",
"(",
"format",
"=",
"Format",
".",
"HTTP_HEADERS",
",",
"carrier",
"=",
"carrier",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"exception",
"(",
"'trace extract failed: %s'",
"%",
"e",
")",
"parent_ctx",
"=",
"None",
"span",
"=",
"tracer",
".",
"start_span",
"(",
"operation_name",
"=",
"operation",
",",
"child_of",
"=",
"parent_ctx",
",",
"tags",
"=",
"tags_dict",
")",
"return",
"span"
] | 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.
:param request: HTTP request with `.headers` property exposed
that satisfies a regular dictionary interface
:param tracer: optional tracer instance to use. If not specified
the global opentracing.tracer will be used.
:return: returns a new, already started span. | [
"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",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/http_server.py#L35-L86 | train | 232,009 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/http_server.py | WSGIRequestWrapper._parse_wsgi_headers | def _parse_wsgi_headers(wsgi_environ):
"""
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.
:param wsgi_environ:
:return: returns a dictionary of headers
"""
prefix = 'HTTP_'
p_len = len(prefix)
# use .items() despite suspected memory pressure bc GC occasionally
# collects wsgi_environ.iteritems() during iteration.
headers = {
key[p_len:].replace('_', '-').lower():
val for (key, val) in wsgi_environ.items()
if key.startswith(prefix)}
return headers | python | def _parse_wsgi_headers(wsgi_environ):
"""
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.
:param wsgi_environ:
:return: returns a dictionary of headers
"""
prefix = 'HTTP_'
p_len = len(prefix)
# use .items() despite suspected memory pressure bc GC occasionally
# collects wsgi_environ.iteritems() during iteration.
headers = {
key[p_len:].replace('_', '-').lower():
val for (key, val) in wsgi_environ.items()
if key.startswith(prefix)}
return headers | [
"def",
"_parse_wsgi_headers",
"(",
"wsgi_environ",
")",
":",
"prefix",
"=",
"'HTTP_'",
"p_len",
"=",
"len",
"(",
"prefix",
")",
"# use .items() despite suspected memory pressure bc GC occasionally",
"# collects wsgi_environ.iteritems() during iteration.",
"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.
:param wsgi_environ:
:return: returns a dictionary of 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",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/http_server.py#L174-L191 | train | 232,010 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/interceptors.py | ClientInterceptors.append | def append(cls, interceptor):
"""
Add interceptor to the end of the internal list.
Note: Raises ``ValueError`` if interceptor
does not extend ``OpenTracingInterceptor``
"""
cls._check(interceptor)
cls._interceptors.append(interceptor) | python | def append(cls, interceptor):
"""
Add interceptor to the end of the internal list.
Note: Raises ``ValueError`` if interceptor
does not extend ``OpenTracingInterceptor``
"""
cls._check(interceptor)
cls._interceptors.append(interceptor) | [
"def",
"append",
"(",
"cls",
",",
"interceptor",
")",
":",
"cls",
".",
"_check",
"(",
"interceptor",
")",
"cls",
".",
"_interceptors",
".",
"append",
"(",
"interceptor",
")"
] | Add interceptor to the end of the internal list.
Note: Raises ``ValueError`` if interceptor
does not extend ``OpenTracingInterceptor`` | [
"Add",
"interceptor",
"to",
"the",
"end",
"of",
"the",
"internal",
"list",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/interceptors.py#L80-L88 | train | 232,011 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/interceptors.py | ClientInterceptors.insert | def insert(cls, index, interceptor):
"""
Add interceptor to the given index in the internal list.
Note: Raises ``ValueError`` if interceptor
does not extend ``OpenTracingInterceptor``
"""
cls._check(interceptor)
cls._interceptors.insert(index, interceptor) | python | def insert(cls, index, interceptor):
"""
Add interceptor to the given index in the internal list.
Note: Raises ``ValueError`` if interceptor
does not extend ``OpenTracingInterceptor``
"""
cls._check(interceptor)
cls._interceptors.insert(index, interceptor) | [
"def",
"insert",
"(",
"cls",
",",
"index",
",",
"interceptor",
")",
":",
"cls",
".",
"_check",
"(",
"interceptor",
")",
"cls",
".",
"_interceptors",
".",
"insert",
"(",
"index",
",",
"interceptor",
")"
] | Add interceptor to the given index in the internal list.
Note: Raises ``ValueError`` if interceptor
does not extend ``OpenTracingInterceptor`` | [
"Add",
"interceptor",
"to",
"the",
"given",
"index",
"in",
"the",
"internal",
"list",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/interceptors.py#L91-L99 | train | 232,012 |
uber-common/opentracing-python-instrumentation | opentracing_instrumentation/client_hooks/_singleton.py | singleton | def singleton(func):
"""
This decorator allows you to make sure that a function is called once and
only once. Note that recursive functions will still work.
WARNING: Not thread-safe!!!
"""
@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()
# save original func to be able to patch and restore multiple times from
# unit tests
wrapper.__original_func = func
return wrapper | python | def singleton(func):
"""
This decorator allows you to make sure that a function is called once and
only once. Note that recursive functions will still work.
WARNING: Not thread-safe!!!
"""
@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()
# save original func to be able to patch and restore multiple times from
# unit tests
wrapper.__original_func = func
return wrapper | [
"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",
"(",
")",
"# save original func to be able to patch and restore multiple times from",
"# unit tests",
"wrapper",
".",
"__original_func",
"=",
"func",
"return",
"wrapper"
] | This decorator allows you to make sure that a function is called once and
only once. Note that recursive functions will still work.
WARNING: Not thread-safe!!! | [
"This",
"decorator",
"allows",
"you",
"to",
"make",
"sure",
"that",
"a",
"function",
"is",
"called",
"once",
"and",
"only",
"once",
".",
"Note",
"that",
"recursive",
"functions",
"will",
"still",
"work",
"."
] | 57b29fb9f647e073cde8c75155f4708cb5661d20 | https://github.com/uber-common/opentracing-python-instrumentation/blob/57b29fb9f647e073cde8c75155f4708cb5661d20/opentracing_instrumentation/client_hooks/_singleton.py#L30-L55 | train | 232,013 |
ANTsX/ANTsPy | ants/utils/smooth_image.py | smooth_image | def smooth_image(image, sigma, sigma_in_physical_coordinates=True, FWHM=False, max_kernel_width=32):
"""
Smooth an image
ANTsR function: `smoothImage`
Arguments
---------
image
Image to smooth
sigma
Smoothing factor. Can be scalar, in which case the same sigma is applied to each dimension, or a vector of length dim(inimage) to specify a unique smoothness for each dimension.
sigma_in_physical_coordinates : boolean
If true, the smoothing factor is in millimeters; if false, it is in pixels.
FWHM : boolean
If true, sigma is interpreted as the full-width-half-max (FWHM) of the filter, not the sigma of a Gaussian kernel.
max_kernel_width : scalar
Maximum kernel width
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16'))
>>> simage = ants.smooth_image(image, (1.2,1.5))
"""
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 image in imagelist:
newimage = _smooth_image_helper(image, sigma, sigma_in_physical_coordinates, FWHM, max_kernel_width)
newimages.append(newimage)
return utils.merge_channels(newimages) | python | def smooth_image(image, sigma, sigma_in_physical_coordinates=True, FWHM=False, max_kernel_width=32):
"""
Smooth an image
ANTsR function: `smoothImage`
Arguments
---------
image
Image to smooth
sigma
Smoothing factor. Can be scalar, in which case the same sigma is applied to each dimension, or a vector of length dim(inimage) to specify a unique smoothness for each dimension.
sigma_in_physical_coordinates : boolean
If true, the smoothing factor is in millimeters; if false, it is in pixels.
FWHM : boolean
If true, sigma is interpreted as the full-width-half-max (FWHM) of the filter, not the sigma of a Gaussian kernel.
max_kernel_width : scalar
Maximum kernel width
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16'))
>>> simage = ants.smooth_image(image, (1.2,1.5))
"""
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 image in imagelist:
newimage = _smooth_image_helper(image, sigma, sigma_in_physical_coordinates, FWHM, max_kernel_width)
newimages.append(newimage)
return utils.merge_channels(newimages) | [
"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",
"image",
"in",
"imagelist",
":",
"newimage",
"=",
"_smooth_image_helper",
"(",
"image",
",",
"sigma",
",",
"sigma_in_physical_coordinates",
",",
"FWHM",
",",
"max_kernel_width",
")",
"newimages",
".",
"append",
"(",
"newimage",
")",
"return",
"utils",
".",
"merge_channels",
"(",
"newimages",
")"
] | Smooth an image
ANTsR function: `smoothImage`
Arguments
---------
image
Image to smooth
sigma
Smoothing factor. Can be scalar, in which case the same sigma is applied to each dimension, or a vector of length dim(inimage) to specify a unique smoothness for each dimension.
sigma_in_physical_coordinates : boolean
If true, the smoothing factor is in millimeters; if false, it is in pixels.
FWHM : boolean
If true, sigma is interpreted as the full-width-half-max (FWHM) of the filter, not the sigma of a Gaussian kernel.
max_kernel_width : scalar
Maximum kernel width
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16'))
>>> simage = ants.smooth_image(image, (1.2,1.5)) | [
"Smooth",
"an",
"image"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/smooth_image.py#L34-L75 | train | 232,014 |
ANTsX/ANTsPy | ants/registration/build_template.py | build_template | def build_template(
initial_template=None,
image_list=None,
iterations = 3,
gradient_step = 0.2,
**kwargs ):
"""
Estimate an optimal template from an input image_list
ANTsR function: N/A
Arguments
---------
initial_template : ANTsImage
initialization for the template building
image_list : ANTsImages
images from which to estimate template
iterations : integer
number of template building iterations
gradient_step : scalar
for shape update gradient
kwargs : keyword args
extra arguments passed to ants registration
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') , 'float')
>>> image2 = ants.image_read( ants.get_ants_data('r27') , 'float')
>>> image3 = ants.image_read( ants.get_ants_data('r85') , 'float')
>>> timage = ants.build_template( image_list = ( image, image2, image3 ) )
"""
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
xavg = initial_template.clone()
for i in range( iterations ):
for k in range( len( image_list ) ):
w1 = registration( xavg, image_list[k],
type_of_transform='SyN', **kwargs )
if k == 0:
wavg = iio.image_read( w1['fwdtransforms'][0] ) * wt
xavgNew = w1['warpedmovout'] * wt
else:
wavg = wavg + iio.image_read( w1['fwdtransforms'][0] ) * wt
xavgNew = xavgNew + w1['warpedmovout'] * wt
print( wavg.abs().mean() )
wscl = (-1.0) * gradient_step
wavg = wavg * wscl
wavgfn = mktemp(suffix='.nii.gz')
iio.image_write(wavg, wavgfn)
xavg = apply_transforms( xavg, xavg, wavgfn )
return xavg | python | def build_template(
initial_template=None,
image_list=None,
iterations = 3,
gradient_step = 0.2,
**kwargs ):
"""
Estimate an optimal template from an input image_list
ANTsR function: N/A
Arguments
---------
initial_template : ANTsImage
initialization for the template building
image_list : ANTsImages
images from which to estimate template
iterations : integer
number of template building iterations
gradient_step : scalar
for shape update gradient
kwargs : keyword args
extra arguments passed to ants registration
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') , 'float')
>>> image2 = ants.image_read( ants.get_ants_data('r27') , 'float')
>>> image3 = ants.image_read( ants.get_ants_data('r85') , 'float')
>>> timage = ants.build_template( image_list = ( image, image2, image3 ) )
"""
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
xavg = initial_template.clone()
for i in range( iterations ):
for k in range( len( image_list ) ):
w1 = registration( xavg, image_list[k],
type_of_transform='SyN', **kwargs )
if k == 0:
wavg = iio.image_read( w1['fwdtransforms'][0] ) * wt
xavgNew = w1['warpedmovout'] * wt
else:
wavg = wavg + iio.image_read( w1['fwdtransforms'][0] ) * wt
xavgNew = xavgNew + w1['warpedmovout'] * wt
print( wavg.abs().mean() )
wscl = (-1.0) * gradient_step
wavg = wavg * wscl
wavgfn = mktemp(suffix='.nii.gz')
iio.image_write(wavg, wavgfn)
xavg = apply_transforms( xavg, xavg, wavgfn )
return xavg | [
"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",
"xavg",
"=",
"initial_template",
".",
"clone",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"iterations",
")",
":",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"image_list",
")",
")",
":",
"w1",
"=",
"registration",
"(",
"xavg",
",",
"image_list",
"[",
"k",
"]",
",",
"type_of_transform",
"=",
"'SyN'",
",",
"*",
"*",
"kwargs",
")",
"if",
"k",
"==",
"0",
":",
"wavg",
"=",
"iio",
".",
"image_read",
"(",
"w1",
"[",
"'fwdtransforms'",
"]",
"[",
"0",
"]",
")",
"*",
"wt",
"xavgNew",
"=",
"w1",
"[",
"'warpedmovout'",
"]",
"*",
"wt",
"else",
":",
"wavg",
"=",
"wavg",
"+",
"iio",
".",
"image_read",
"(",
"w1",
"[",
"'fwdtransforms'",
"]",
"[",
"0",
"]",
")",
"*",
"wt",
"xavgNew",
"=",
"xavgNew",
"+",
"w1",
"[",
"'warpedmovout'",
"]",
"*",
"wt",
"print",
"(",
"wavg",
".",
"abs",
"(",
")",
".",
"mean",
"(",
")",
")",
"wscl",
"=",
"(",
"-",
"1.0",
")",
"*",
"gradient_step",
"wavg",
"=",
"wavg",
"*",
"wscl",
"wavgfn",
"=",
"mktemp",
"(",
"suffix",
"=",
"'.nii.gz'",
")",
"iio",
".",
"image_write",
"(",
"wavg",
",",
"wavgfn",
")",
"xavg",
"=",
"apply_transforms",
"(",
"xavg",
",",
"xavg",
",",
"wavgfn",
")",
"return",
"xavg"
] | Estimate an optimal template from an input image_list
ANTsR function: N/A
Arguments
---------
initial_template : ANTsImage
initialization for the template building
image_list : ANTsImages
images from which to estimate template
iterations : integer
number of template building iterations
gradient_step : scalar
for shape update gradient
kwargs : keyword args
extra arguments passed to ants registration
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') , 'float')
>>> image2 = ants.image_read( ants.get_ants_data('r27') , 'float')
>>> image3 = ants.image_read( ants.get_ants_data('r85') , 'float')
>>> timage = ants.build_template( image_list = ( image, image2, image3 ) ) | [
"Estimate",
"an",
"optimal",
"template",
"from",
"an",
"input",
"image_list"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/build_template.py#L13-L77 | train | 232,015 |
ANTsX/ANTsPy | ants/registration/resample_image.py | resample_image | def resample_image(image, resample_params, use_voxels=False, interp_type=1):
"""
Resample image by spacing or number of voxels with
various interpolators. Works with multi-channel images.
ANTsR function: `resampleImage`
Arguments
---------
image : ANTsImage
input image
resample_params : tuple/list
vector of size dimension with numeric values
use_voxels : boolean
True means interpret resample params as voxel counts
interp_type : integer
one of 0 (linear), 1 (nearest neighbor), 2 (gaussian), 3 (windowed sinc), 4 (bspline)
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data("r16"))
>>> finn = ants.resample_image(fi,(50,60),True,0)
>>> filin = ants.resample_image(fi,(1.5,1.5),False,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(use_voxels), interp_type]
processed_args = utils._int_antsProcessArguments(args)
libfn = utils.get_lib_fn('ResampleImage')
libfn(processed_args)
outimage = outimage.clone(image.pixeltype)
return outimage
else:
raise ValueError('images with more than 1 component not currently supported') | python | def resample_image(image, resample_params, use_voxels=False, interp_type=1):
"""
Resample image by spacing or number of voxels with
various interpolators. Works with multi-channel images.
ANTsR function: `resampleImage`
Arguments
---------
image : ANTsImage
input image
resample_params : tuple/list
vector of size dimension with numeric values
use_voxels : boolean
True means interpret resample params as voxel counts
interp_type : integer
one of 0 (linear), 1 (nearest neighbor), 2 (gaussian), 3 (windowed sinc), 4 (bspline)
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data("r16"))
>>> finn = ants.resample_image(fi,(50,60),True,0)
>>> filin = ants.resample_image(fi,(1.5,1.5),False,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(use_voxels), interp_type]
processed_args = utils._int_antsProcessArguments(args)
libfn = utils.get_lib_fn('ResampleImage')
libfn(processed_args)
outimage = outimage.clone(image.pixeltype)
return outimage
else:
raise ValueError('images with more than 1 component not currently supported') | [
"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",
"(",
"use_voxels",
")",
",",
"interp_type",
"]",
"processed_args",
"=",
"utils",
".",
"_int_antsProcessArguments",
"(",
"args",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'ResampleImage'",
")",
"libfn",
"(",
"processed_args",
")",
"outimage",
"=",
"outimage",
".",
"clone",
"(",
"image",
".",
"pixeltype",
")",
"return",
"outimage",
"else",
":",
"raise",
"ValueError",
"(",
"'images with more than 1 component not currently supported'",
")"
] | Resample image by spacing or number of voxels with
various interpolators. Works with multi-channel images.
ANTsR function: `resampleImage`
Arguments
---------
image : ANTsImage
input image
resample_params : tuple/list
vector of size dimension with numeric values
use_voxels : boolean
True means interpret resample params as voxel counts
interp_type : integer
one of 0 (linear), 1 (nearest neighbor), 2 (gaussian), 3 (windowed sinc), 4 (bspline)
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data("r16"))
>>> finn = ants.resample_image(fi,(50,60),True,0)
>>> filin = ants.resample_image(fi,(1.5,1.5),False,1) | [
"Resample",
"image",
"by",
"spacing",
"or",
"number",
"of",
"voxels",
"with",
"various",
"interpolators",
".",
"Works",
"with",
"multi",
"-",
"channel",
"images",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/resample_image.py#L12-L56 | train | 232,016 |
ANTsX/ANTsPy | ants/core/ants_transform.py | apply_ants_transform | def apply_ants_transform(transform, data, data_type="point", reference=None, **kwargs):
"""
Apply ANTsTransform to data
ANTsR function: `applyAntsrTransform`
Arguments
---------
transform : ANTsTransform
transform to apply to image
data : ndarray/list/tuple
data to which transform will be applied
data_type : string
type of data
Options :
'point'
'vector'
'image'
reference : ANTsImage
target space for transforming image
kwargs : kwargs
additional options passed to `apply_ants_transform_to_image`
Returns
-------
ANTsImage if data_type == 'point'
OR
tuple if data_type == 'point' or data_type == 'vector'
"""
return transform.apply(data, data_type, reference, **kwargs) | python | def apply_ants_transform(transform, data, data_type="point", reference=None, **kwargs):
"""
Apply ANTsTransform to data
ANTsR function: `applyAntsrTransform`
Arguments
---------
transform : ANTsTransform
transform to apply to image
data : ndarray/list/tuple
data to which transform will be applied
data_type : string
type of data
Options :
'point'
'vector'
'image'
reference : ANTsImage
target space for transforming image
kwargs : kwargs
additional options passed to `apply_ants_transform_to_image`
Returns
-------
ANTsImage if data_type == 'point'
OR
tuple if data_type == 'point' or data_type == 'vector'
"""
return transform.apply(data, data_type, reference, **kwargs) | [
"def",
"apply_ants_transform",
"(",
"transform",
",",
"data",
",",
"data_type",
"=",
"\"point\"",
",",
"reference",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"transform",
".",
"apply",
"(",
"data",
",",
"data_type",
",",
"reference",
",",
"*",
"*",
"kwargs",
")"
] | Apply ANTsTransform to data
ANTsR function: `applyAntsrTransform`
Arguments
---------
transform : ANTsTransform
transform to apply to image
data : ndarray/list/tuple
data to which transform will be applied
data_type : string
type of data
Options :
'point'
'vector'
'image'
reference : ANTsImage
target space for transforming image
kwargs : kwargs
additional options passed to `apply_ants_transform_to_image`
Returns
-------
ANTsImage if data_type == 'point'
OR
tuple if data_type == 'point' or data_type == 'vector' | [
"Apply",
"ANTsTransform",
"to",
"data"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform.py#L225-L258 | train | 232,017 |
ANTsX/ANTsPy | ants/core/ants_transform.py | compose_ants_transforms | def compose_ants_transforms(transform_list):
"""
Compose multiple ANTsTransform's together
ANTsR function: `composeAntsrTransforms`
Arguments
---------
transform_list : list/tuple of ANTsTransform object
list of transforms to compose together
Returns
-------
ANTsTransform
one transform that contains all given transforms
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_ants_data("r16")).clone('float')
>>> tx = ants.new_ants_transform(dimension=2)
>>> tx.set_parameters((0.9,0,0,1.1,10,11))
>>> inv_tx = tx.invert()
>>> single_tx = ants.compose_ants_transforms([tx, inv_tx])
>>> img_orig = single_tx.apply_to_image(img, img)
>>> rRotGenerator = ants.contrib.RandomRotate2D( ( 0, 40 ), reference=img )
>>> rShearGenerator=ants.contrib.RandomShear2D( (0,50), reference=img )
>>> tx1 = rRotGenerator.transform()
>>> tx2 = rShearGenerator.transform()
>>> rSrR = ants.compose_ants_transforms([tx1, tx2])
>>> rSrR.apply_to_image( img )
"""
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('All transforms must have the same dimension')
tx_ptr_list = list(reversed([tf.pointer for tf in transform_list]))
libfn = utils.get_lib_fn('composeTransforms%s' % (transform_list[0]._libsuffix))
itk_composed_tx = libfn(tx_ptr_list, precision, dimension)
return ANTsTransform(precision=precision, dimension=dimension,
transform_type='CompositeTransform', pointer=itk_composed_tx) | python | def compose_ants_transforms(transform_list):
"""
Compose multiple ANTsTransform's together
ANTsR function: `composeAntsrTransforms`
Arguments
---------
transform_list : list/tuple of ANTsTransform object
list of transforms to compose together
Returns
-------
ANTsTransform
one transform that contains all given transforms
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_ants_data("r16")).clone('float')
>>> tx = ants.new_ants_transform(dimension=2)
>>> tx.set_parameters((0.9,0,0,1.1,10,11))
>>> inv_tx = tx.invert()
>>> single_tx = ants.compose_ants_transforms([tx, inv_tx])
>>> img_orig = single_tx.apply_to_image(img, img)
>>> rRotGenerator = ants.contrib.RandomRotate2D( ( 0, 40 ), reference=img )
>>> rShearGenerator=ants.contrib.RandomShear2D( (0,50), reference=img )
>>> tx1 = rRotGenerator.transform()
>>> tx2 = rShearGenerator.transform()
>>> rSrR = ants.compose_ants_transforms([tx1, tx2])
>>> rSrR.apply_to_image( img )
"""
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('All transforms must have the same dimension')
tx_ptr_list = list(reversed([tf.pointer for tf in transform_list]))
libfn = utils.get_lib_fn('composeTransforms%s' % (transform_list[0]._libsuffix))
itk_composed_tx = libfn(tx_ptr_list, precision, dimension)
return ANTsTransform(precision=precision, dimension=dimension,
transform_type='CompositeTransform', pointer=itk_composed_tx) | [
"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",
"(",
"'All transforms must have the same dimension'",
")",
"tx_ptr_list",
"=",
"list",
"(",
"reversed",
"(",
"[",
"tf",
".",
"pointer",
"for",
"tf",
"in",
"transform_list",
"]",
")",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'composeTransforms%s'",
"%",
"(",
"transform_list",
"[",
"0",
"]",
".",
"_libsuffix",
")",
")",
"itk_composed_tx",
"=",
"libfn",
"(",
"tx_ptr_list",
",",
"precision",
",",
"dimension",
")",
"return",
"ANTsTransform",
"(",
"precision",
"=",
"precision",
",",
"dimension",
"=",
"dimension",
",",
"transform_type",
"=",
"'CompositeTransform'",
",",
"pointer",
"=",
"itk_composed_tx",
")"
] | Compose multiple ANTsTransform's together
ANTsR function: `composeAntsrTransforms`
Arguments
---------
transform_list : list/tuple of ANTsTransform object
list of transforms to compose together
Returns
-------
ANTsTransform
one transform that contains all given transforms
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_ants_data("r16")).clone('float')
>>> tx = ants.new_ants_transform(dimension=2)
>>> tx.set_parameters((0.9,0,0,1.1,10,11))
>>> inv_tx = tx.invert()
>>> single_tx = ants.compose_ants_transforms([tx, inv_tx])
>>> img_orig = single_tx.apply_to_image(img, img)
>>> rRotGenerator = ants.contrib.RandomRotate2D( ( 0, 40 ), reference=img )
>>> rShearGenerator=ants.contrib.RandomShear2D( (0,50), reference=img )
>>> tx1 = rRotGenerator.transform()
>>> tx2 = rShearGenerator.transform()
>>> rSrR = ants.compose_ants_transforms([tx1, tx2])
>>> rSrR.apply_to_image( img ) | [
"Compose",
"multiple",
"ANTsTransform",
"s",
"together"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform.py#L355-L400 | train | 232,018 |
ANTsX/ANTsPy | ants/core/ants_transform.py | transform_index_to_physical_point | def transform_index_to_physical_point(image, index):
"""
Get spatial point from index of an image.
ANTsR function: `antsTransformIndexToPhysicalPoint`
Arguments
---------
img : ANTsImage
image to get values from
index : list or tuple or numpy.ndarray
location in image
Returns
-------
tuple
Example
-------
>>> import ants
>>> import numpy as np
>>> img = ants.make_image((10,10),np.random.randn(100))
>>> pt = ants.transform_index_to_physical_point(img, (2,2))
"""
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 list')
if len(index) != image.dimension:
raise ValueError('len(index) != image.dimension')
index = [i+1 for i in index]
ndim = image.dimension
ptype = image.pixeltype
libfn = utils.get_lib_fn('TransformIndexToPhysicalPoint%s%i' % (utils.short_ptype(ptype), ndim))
point = libfn(image.pointer, [list(index)])
return np.array(point[0]) | python | def transform_index_to_physical_point(image, index):
"""
Get spatial point from index of an image.
ANTsR function: `antsTransformIndexToPhysicalPoint`
Arguments
---------
img : ANTsImage
image to get values from
index : list or tuple or numpy.ndarray
location in image
Returns
-------
tuple
Example
-------
>>> import ants
>>> import numpy as np
>>> img = ants.make_image((10,10),np.random.randn(100))
>>> pt = ants.transform_index_to_physical_point(img, (2,2))
"""
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 list')
if len(index) != image.dimension:
raise ValueError('len(index) != image.dimension')
index = [i+1 for i in index]
ndim = image.dimension
ptype = image.pixeltype
libfn = utils.get_lib_fn('TransformIndexToPhysicalPoint%s%i' % (utils.short_ptype(ptype), ndim))
point = libfn(image.pointer, [list(index)])
return np.array(point[0]) | [
"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 list'",
")",
"if",
"len",
"(",
"index",
")",
"!=",
"image",
".",
"dimension",
":",
"raise",
"ValueError",
"(",
"'len(index) != image.dimension'",
")",
"index",
"=",
"[",
"i",
"+",
"1",
"for",
"i",
"in",
"index",
"]",
"ndim",
"=",
"image",
".",
"dimension",
"ptype",
"=",
"image",
".",
"pixeltype",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'TransformIndexToPhysicalPoint%s%i'",
"%",
"(",
"utils",
".",
"short_ptype",
"(",
"ptype",
")",
",",
"ndim",
")",
")",
"point",
"=",
"libfn",
"(",
"image",
".",
"pointer",
",",
"[",
"list",
"(",
"index",
")",
"]",
")",
"return",
"np",
".",
"array",
"(",
"point",
"[",
"0",
"]",
")"
] | Get spatial point from index of an image.
ANTsR function: `antsTransformIndexToPhysicalPoint`
Arguments
---------
img : ANTsImage
image to get values from
index : list or tuple or numpy.ndarray
location in image
Returns
-------
tuple
Example
-------
>>> import ants
>>> import numpy as np
>>> img = ants.make_image((10,10),np.random.randn(100))
>>> pt = ants.transform_index_to_physical_point(img, (2,2)) | [
"Get",
"spatial",
"point",
"from",
"index",
"of",
"an",
"image",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform.py#L403-L446 | train | 232,019 |
ANTsX/ANTsPy | ants/core/ants_transform.py | ANTsTransform.invert | def invert(self):
""" Invert the transform """
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 | python | def invert(self):
""" Invert the transform """
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 | [
"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 | [
"Invert",
"the",
"transform"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform.py#L87-L95 | train | 232,020 |
ANTsX/ANTsPy | ants/core/ants_transform.py | ANTsTransform.apply | def apply(self, data, data_type='point', reference=None, **kwargs):
"""
Apply transform to data
"""
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) | python | def apply(self, data, data_type='point', reference=None, **kwargs):
"""
Apply transform to data
"""
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) | [
"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 | [
"Apply",
"transform",
"to",
"data"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform.py#L97-L107 | train | 232,021 |
ANTsX/ANTsPy | ants/core/ants_transform.py | ANTsTransform.apply_to_point | def apply_to_point(self, point):
"""
Apply transform to a point
Arguments
---------
point : list/tuple
point to which the transform will be applied
Returns
-------
list : transformed point
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform()
>>> params = tx.parameters
>>> tx.set_parameters(params*2)
>>> pt2 = tx.apply_to_point((1,2,3)) # should be (2,4,6)
"""
libfn = utils.get_lib_fn('transformPoint%s' % (self._libsuffix))
return tuple(libfn(self.pointer, point)) | python | def apply_to_point(self, point):
"""
Apply transform to a point
Arguments
---------
point : list/tuple
point to which the transform will be applied
Returns
-------
list : transformed point
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform()
>>> params = tx.parameters
>>> tx.set_parameters(params*2)
>>> pt2 = tx.apply_to_point((1,2,3)) # should be (2,4,6)
"""
libfn = utils.get_lib_fn('transformPoint%s' % (self._libsuffix))
return tuple(libfn(self.pointer, point)) | [
"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
Arguments
---------
point : list/tuple
point to which the transform will be applied
Returns
-------
list : transformed point
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform()
>>> params = tx.parameters
>>> tx.set_parameters(params*2)
>>> pt2 = tx.apply_to_point((1,2,3)) # should be (2,4,6) | [
"Apply",
"transform",
"to",
"a",
"point"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform.py#L109-L131 | train | 232,022 |
ANTsX/ANTsPy | ants/core/ants_transform.py | ANTsTransform.apply_to_vector | def apply_to_vector(self, vector):
"""
Apply transform to a vector
Arguments
---------
vector : list/tuple
vector to which the transform will be applied
Returns
-------
list : transformed 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)) | python | def apply_to_vector(self, vector):
"""
Apply transform to a vector
Arguments
---------
vector : list/tuple
vector to which the transform will be applied
Returns
-------
list : transformed 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)) | [
"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
Arguments
---------
vector : list/tuple
vector to which the transform will be applied
Returns
-------
list : transformed vector | [
"Apply",
"transform",
"to",
"a",
"vector"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform.py#L133-L150 | train | 232,023 |
ANTsX/ANTsPy | ants/viz/plot.py | plot_hist | def plot_hist(image, threshold=0., fit_line=False, normfreq=True,
## plot label arguments
title=None, grid=True, xlabel=None, ylabel=None,
## other plot arguments
facecolor='green', alpha=0.75):
"""
Plot a histogram from an ANTsImage
Arguments
---------
image : ANTsImage
image from which histogram will be created
"""
img_arr = image.numpy().flatten()
img_arr = img_arr[np.abs(img_arr) > threshold]
if normfreq != False:
normfreq = 1. if normfreq == True else normfreq
n, bins, patches = plt.hist(img_arr, 50, normed=normfreq, facecolor=facecolor, alpha=alpha)
if fit_line:
# add a 'best fit' line
y = mlab.normpdf( bins, img_arr.mean(), img_arr.std())
l = plt.plot(bins, y, 'r--', linewidth=1)
if xlabel is not None:
plt.xlabel(xlabel)
if ylabel is not None:
plt.ylabel(ylabel)
if title is not None:
plt.title(title)
plt.grid(grid)
plt.show() | python | def plot_hist(image, threshold=0., fit_line=False, normfreq=True,
## plot label arguments
title=None, grid=True, xlabel=None, ylabel=None,
## other plot arguments
facecolor='green', alpha=0.75):
"""
Plot a histogram from an ANTsImage
Arguments
---------
image : ANTsImage
image from which histogram will be created
"""
img_arr = image.numpy().flatten()
img_arr = img_arr[np.abs(img_arr) > threshold]
if normfreq != False:
normfreq = 1. if normfreq == True else normfreq
n, bins, patches = plt.hist(img_arr, 50, normed=normfreq, facecolor=facecolor, alpha=alpha)
if fit_line:
# add a 'best fit' line
y = mlab.normpdf( bins, img_arr.mean(), img_arr.std())
l = plt.plot(bins, y, 'r--', linewidth=1)
if xlabel is not None:
plt.xlabel(xlabel)
if ylabel is not None:
plt.ylabel(ylabel)
if title is not None:
plt.title(title)
plt.grid(grid)
plt.show() | [
"def",
"plot_hist",
"(",
"image",
",",
"threshold",
"=",
"0.",
",",
"fit_line",
"=",
"False",
",",
"normfreq",
"=",
"True",
",",
"## plot label arguments",
"title",
"=",
"None",
",",
"grid",
"=",
"True",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"=",
"None",
",",
"## other plot arguments",
"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",
"normfreq",
"==",
"True",
"else",
"normfreq",
"n",
",",
"bins",
",",
"patches",
"=",
"plt",
".",
"hist",
"(",
"img_arr",
",",
"50",
",",
"normed",
"=",
"normfreq",
",",
"facecolor",
"=",
"facecolor",
",",
"alpha",
"=",
"alpha",
")",
"if",
"fit_line",
":",
"# add a 'best fit' line",
"y",
"=",
"mlab",
".",
"normpdf",
"(",
"bins",
",",
"img_arr",
".",
"mean",
"(",
")",
",",
"img_arr",
".",
"std",
"(",
")",
")",
"l",
"=",
"plt",
".",
"plot",
"(",
"bins",
",",
"y",
",",
"'r--'",
",",
"linewidth",
"=",
"1",
")",
"if",
"xlabel",
"is",
"not",
"None",
":",
"plt",
".",
"xlabel",
"(",
"xlabel",
")",
"if",
"ylabel",
"is",
"not",
"None",
":",
"plt",
".",
"ylabel",
"(",
"ylabel",
")",
"if",
"title",
"is",
"not",
"None",
":",
"plt",
".",
"title",
"(",
"title",
")",
"plt",
".",
"grid",
"(",
"grid",
")",
"plt",
".",
"show",
"(",
")"
] | Plot a histogram from an ANTsImage
Arguments
---------
image : ANTsImage
image from which histogram will be created | [
"Plot",
"a",
"histogram",
"from",
"an",
"ANTsImage"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/viz/plot.py#L91-L124 | train | 232,024 |
ANTsX/ANTsPy | ants/utils/morphology.py | morphology | def morphology(image, operation, radius, mtype='binary', value=1,
shape='ball', radius_is_parametric=False, thickness=1,
lines=3, include_center=False):
"""
Apply morphological operations to an image
ANTsR function: `morphology`
Arguments
---------
input : ANTsImage
input image
operation : string
operation to apply
"close" Morpholgical closing
"dilate" Morpholgical dilation
"erode" Morpholgical erosion
"open" Morpholgical opening
radius : scalar
radius of structuring element
mtype : string
type of morphology
"binary" Binary operation on a single value
"grayscale" Grayscale operations
value : scalar
value to operation on (type='binary' only)
shape : string
shape of the structuring element ( type='binary' only )
"ball" spherical structuring element
"box" box shaped structuring element
"cross" cross shaped structuring element
"annulus" annulus shaped structuring element
"polygon" polygon structuring element
radius_is_parametric : boolean
used parametric radius boolean (shape='ball' and shape='annulus' only)
thickness : scalar
thickness (shape='annulus' only)
lines : integer
number of lines in polygon (shape='polygon' only)
include_center : boolean
include center of annulus boolean (shape='annulus' only)
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') , 2 )
>>> mask = ants.get_mask( fi )
>>> dilated_ball = ants.morphology( mask, operation='dilate', radius=3, mtype='binary', shape='ball')
>>> eroded_box = ants.morphology( mask, operation='erode', radius=3, mtype='binary', shape='box')
>>> opened_annulus = ants.morphology( mask, operation='open', radius=5, mtype='binary', shape='annulus', thickness=2)
"""
if image.components > 1:
raise ValueError('multichannel images not yet supported')
_sflag_dict = {'ball': 1, 'box': 2, 'cross': 3, 'annulus': 4, 'polygon': 5}
sFlag = _sflag_dict.get(shape, 0)
if sFlag == 0:
raise ValueError('invalid element shape')
radius_is_parametric = radius_is_parametric * 1
include_center = include_center * 1
if (mtype == 'binary'):
if (operation == 'dilate'):
if (sFlag == 5):
ret = iMath(image, 'MD', radius, value, sFlag, lines)
else:
ret = iMath(image, 'MD', radius, value, sFlag, radius_is_parametric, thickness, include_center)
elif (operation == 'erode'):
if (sFlag == 5):
ret = iMath(image, 'ME', radius, value, sFlag, lines)
else:
ret = iMath(image, 'ME', radius, value, sFlag, radius_is_parametric, thickness, include_center)
elif (operation == 'open'):
if (sFlag == 5):
ret = iMath(image, 'MO', radius, value, sFlag, lines)
else:
ret = iMath(image, 'MO', radius, value, sFlag, radius_is_parametric, thickness, include_center)
elif (operation == 'close'):
if (sFlag == 5):
ret = iMath(image, 'MC', radius, value, sFlag, lines)
else:
ret = iMath(image, 'MC', radius, value, sFlag, radius_is_parametric, thickness, include_center)
else:
raise ValueError('Invalid morphology operation')
elif (mtype == 'grayscale'):
if (operation == 'dilate'):
ret = iMath(image, 'GD', radius)
elif (operation == 'erode'):
ret = iMath(image, 'GE', radius)
elif (operation == 'open'):
ret = iMath(image, 'GO', radius)
elif (operation == 'close'):
ret = iMath(image, 'GC', radius)
else:
raise ValueError('Invalid morphology operation')
else:
raise ValueError('Invalid morphology type')
return ret | python | def morphology(image, operation, radius, mtype='binary', value=1,
shape='ball', radius_is_parametric=False, thickness=1,
lines=3, include_center=False):
"""
Apply morphological operations to an image
ANTsR function: `morphology`
Arguments
---------
input : ANTsImage
input image
operation : string
operation to apply
"close" Morpholgical closing
"dilate" Morpholgical dilation
"erode" Morpholgical erosion
"open" Morpholgical opening
radius : scalar
radius of structuring element
mtype : string
type of morphology
"binary" Binary operation on a single value
"grayscale" Grayscale operations
value : scalar
value to operation on (type='binary' only)
shape : string
shape of the structuring element ( type='binary' only )
"ball" spherical structuring element
"box" box shaped structuring element
"cross" cross shaped structuring element
"annulus" annulus shaped structuring element
"polygon" polygon structuring element
radius_is_parametric : boolean
used parametric radius boolean (shape='ball' and shape='annulus' only)
thickness : scalar
thickness (shape='annulus' only)
lines : integer
number of lines in polygon (shape='polygon' only)
include_center : boolean
include center of annulus boolean (shape='annulus' only)
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') , 2 )
>>> mask = ants.get_mask( fi )
>>> dilated_ball = ants.morphology( mask, operation='dilate', radius=3, mtype='binary', shape='ball')
>>> eroded_box = ants.morphology( mask, operation='erode', radius=3, mtype='binary', shape='box')
>>> opened_annulus = ants.morphology( mask, operation='open', radius=5, mtype='binary', shape='annulus', thickness=2)
"""
if image.components > 1:
raise ValueError('multichannel images not yet supported')
_sflag_dict = {'ball': 1, 'box': 2, 'cross': 3, 'annulus': 4, 'polygon': 5}
sFlag = _sflag_dict.get(shape, 0)
if sFlag == 0:
raise ValueError('invalid element shape')
radius_is_parametric = radius_is_parametric * 1
include_center = include_center * 1
if (mtype == 'binary'):
if (operation == 'dilate'):
if (sFlag == 5):
ret = iMath(image, 'MD', radius, value, sFlag, lines)
else:
ret = iMath(image, 'MD', radius, value, sFlag, radius_is_parametric, thickness, include_center)
elif (operation == 'erode'):
if (sFlag == 5):
ret = iMath(image, 'ME', radius, value, sFlag, lines)
else:
ret = iMath(image, 'ME', radius, value, sFlag, radius_is_parametric, thickness, include_center)
elif (operation == 'open'):
if (sFlag == 5):
ret = iMath(image, 'MO', radius, value, sFlag, lines)
else:
ret = iMath(image, 'MO', radius, value, sFlag, radius_is_parametric, thickness, include_center)
elif (operation == 'close'):
if (sFlag == 5):
ret = iMath(image, 'MC', radius, value, sFlag, lines)
else:
ret = iMath(image, 'MC', radius, value, sFlag, radius_is_parametric, thickness, include_center)
else:
raise ValueError('Invalid morphology operation')
elif (mtype == 'grayscale'):
if (operation == 'dilate'):
ret = iMath(image, 'GD', radius)
elif (operation == 'erode'):
ret = iMath(image, 'GE', radius)
elif (operation == 'open'):
ret = iMath(image, 'GO', radius)
elif (operation == 'close'):
ret = iMath(image, 'GC', radius)
else:
raise ValueError('Invalid morphology operation')
else:
raise ValueError('Invalid morphology type')
return ret | [
"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'",
":",
"3",
",",
"'annulus'",
":",
"4",
",",
"'polygon'",
":",
"5",
"}",
"sFlag",
"=",
"_sflag_dict",
".",
"get",
"(",
"shape",
",",
"0",
")",
"if",
"sFlag",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'invalid element shape'",
")",
"radius_is_parametric",
"=",
"radius_is_parametric",
"*",
"1",
"include_center",
"=",
"include_center",
"*",
"1",
"if",
"(",
"mtype",
"==",
"'binary'",
")",
":",
"if",
"(",
"operation",
"==",
"'dilate'",
")",
":",
"if",
"(",
"sFlag",
"==",
"5",
")",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'MD'",
",",
"radius",
",",
"value",
",",
"sFlag",
",",
"lines",
")",
"else",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'MD'",
",",
"radius",
",",
"value",
",",
"sFlag",
",",
"radius_is_parametric",
",",
"thickness",
",",
"include_center",
")",
"elif",
"(",
"operation",
"==",
"'erode'",
")",
":",
"if",
"(",
"sFlag",
"==",
"5",
")",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'ME'",
",",
"radius",
",",
"value",
",",
"sFlag",
",",
"lines",
")",
"else",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'ME'",
",",
"radius",
",",
"value",
",",
"sFlag",
",",
"radius_is_parametric",
",",
"thickness",
",",
"include_center",
")",
"elif",
"(",
"operation",
"==",
"'open'",
")",
":",
"if",
"(",
"sFlag",
"==",
"5",
")",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'MO'",
",",
"radius",
",",
"value",
",",
"sFlag",
",",
"lines",
")",
"else",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'MO'",
",",
"radius",
",",
"value",
",",
"sFlag",
",",
"radius_is_parametric",
",",
"thickness",
",",
"include_center",
")",
"elif",
"(",
"operation",
"==",
"'close'",
")",
":",
"if",
"(",
"sFlag",
"==",
"5",
")",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'MC'",
",",
"radius",
",",
"value",
",",
"sFlag",
",",
"lines",
")",
"else",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'MC'",
",",
"radius",
",",
"value",
",",
"sFlag",
",",
"radius_is_parametric",
",",
"thickness",
",",
"include_center",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid morphology operation'",
")",
"elif",
"(",
"mtype",
"==",
"'grayscale'",
")",
":",
"if",
"(",
"operation",
"==",
"'dilate'",
")",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'GD'",
",",
"radius",
")",
"elif",
"(",
"operation",
"==",
"'erode'",
")",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'GE'",
",",
"radius",
")",
"elif",
"(",
"operation",
"==",
"'open'",
")",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'GO'",
",",
"radius",
")",
"elif",
"(",
"operation",
"==",
"'close'",
")",
":",
"ret",
"=",
"iMath",
"(",
"image",
",",
"'GC'",
",",
"radius",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid morphology operation'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid morphology type'",
")",
"return",
"ret"
] | Apply morphological operations to an image
ANTsR function: `morphology`
Arguments
---------
input : ANTsImage
input image
operation : string
operation to apply
"close" Morpholgical closing
"dilate" Morpholgical dilation
"erode" Morpholgical erosion
"open" Morpholgical opening
radius : scalar
radius of structuring element
mtype : string
type of morphology
"binary" Binary operation on a single value
"grayscale" Grayscale operations
value : scalar
value to operation on (type='binary' only)
shape : string
shape of the structuring element ( type='binary' only )
"ball" spherical structuring element
"box" box shaped structuring element
"cross" cross shaped structuring element
"annulus" annulus shaped structuring element
"polygon" polygon structuring element
radius_is_parametric : boolean
used parametric radius boolean (shape='ball' and shape='annulus' only)
thickness : scalar
thickness (shape='annulus' only)
lines : integer
number of lines in polygon (shape='polygon' only)
include_center : boolean
include center of annulus boolean (shape='annulus' only)
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') , 2 )
>>> mask = ants.get_mask( fi )
>>> dilated_ball = ants.morphology( mask, operation='dilate', radius=3, mtype='binary', shape='ball')
>>> eroded_box = ants.morphology( mask, operation='erode', radius=3, mtype='binary', shape='box')
>>> opened_annulus = ants.morphology( mask, operation='open', radius=5, mtype='binary', shape='annulus', thickness=2) | [
"Apply",
"morphological",
"operations",
"to",
"an",
"image"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/morphology.py#L8-L120 | train | 232,025 |
ANTsX/ANTsPy | ants/utils/scalar_rgb_vector.py | rgb_to_vector | def rgb_to_vector(image):
"""
Convert an RGB ANTsImage to a Vector ANTsImage
Arguments
---------
image : ANTsImage
RGB image to be converted
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni_rgb = mni.scalar_to_rgb()
>>> mni_vector = mni.rgb_to_vector()
>>> mni_rgb2 = mni.vector_to_rgb()
"""
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,
components=3, pointer=new_ptr, is_rgb=False)
return new_img | python | def rgb_to_vector(image):
"""
Convert an RGB ANTsImage to a Vector ANTsImage
Arguments
---------
image : ANTsImage
RGB image to be converted
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni_rgb = mni.scalar_to_rgb()
>>> mni_vector = mni.rgb_to_vector()
>>> mni_rgb2 = mni.vector_to_rgb()
"""
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,
components=3, pointer=new_ptr, is_rgb=False)
return new_img | [
"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",
",",
"components",
"=",
"3",
",",
"pointer",
"=",
"new_ptr",
",",
"is_rgb",
"=",
"False",
")",
"return",
"new_img"
] | Convert an RGB ANTsImage to a Vector ANTsImage
Arguments
---------
image : ANTsImage
RGB image to be converted
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni_rgb = mni.scalar_to_rgb()
>>> mni_vector = mni.rgb_to_vector()
>>> mni_rgb2 = mni.vector_to_rgb() | [
"Convert",
"an",
"RGB",
"ANTsImage",
"to",
"a",
"Vector",
"ANTsImage"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/scalar_rgb_vector.py#L78-L106 | train | 232,026 |
ANTsX/ANTsPy | ants/utils/scalar_rgb_vector.py | vector_to_rgb | def vector_to_rgb(image):
"""
Convert an Vector ANTsImage to a RGB ANTsImage
Arguments
---------
image : ANTsImage
RGB image to be converted
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'), pixeltype='unsigned char')
>>> img_rgb = img.clone().scalar_to_rgb()
>>> img_vec = img_rgb.rgb_to_vector()
>>> img_rgb2 = img_vec.vector_to_rgb()
"""
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,
components=3, pointer=new_ptr, is_rgb=True)
return new_img | python | def vector_to_rgb(image):
"""
Convert an Vector ANTsImage to a RGB ANTsImage
Arguments
---------
image : ANTsImage
RGB image to be converted
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'), pixeltype='unsigned char')
>>> img_rgb = img.clone().scalar_to_rgb()
>>> img_vec = img_rgb.rgb_to_vector()
>>> img_rgb2 = img_vec.vector_to_rgb()
"""
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,
components=3, pointer=new_ptr, is_rgb=True)
return new_img | [
"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",
",",
"components",
"=",
"3",
",",
"pointer",
"=",
"new_ptr",
",",
"is_rgb",
"=",
"True",
")",
"return",
"new_img"
] | Convert an Vector ANTsImage to a RGB ANTsImage
Arguments
---------
image : ANTsImage
RGB image to be converted
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'), pixeltype='unsigned char')
>>> img_rgb = img.clone().scalar_to_rgb()
>>> img_vec = img_rgb.rgb_to_vector()
>>> img_rgb2 = img_vec.vector_to_rgb() | [
"Convert",
"an",
"Vector",
"ANTsImage",
"to",
"a",
"RGB",
"ANTsImage"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/scalar_rgb_vector.py#L109-L137 | train | 232,027 |
ANTsX/ANTsPy | ants/utils/quantile.py | quantile | def quantile(image, q, nonzero=True):
"""
Get the quantile values from an ANTsImage
"""
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,int)):
if q <= 1.:
q = q*100.
if nonzero:
img_arr = img_arr[img_arr>0]
return np.percentile(img_arr[img_arr>0], q)
else:
raise ValueError('q argument must be list/tuple or float/int') | python | def quantile(image, q, nonzero=True):
"""
Get the quantile values from an ANTsImage
"""
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,int)):
if q <= 1.:
q = q*100.
if nonzero:
img_arr = img_arr[img_arr>0]
return np.percentile(img_arr[img_arr>0], q)
else:
raise ValueError('q argument must be list/tuple or float/int') | [
"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",
",",
"int",
")",
")",
":",
"if",
"q",
"<=",
"1.",
":",
"q",
"=",
"q",
"*",
"100.",
"if",
"nonzero",
":",
"img_arr",
"=",
"img_arr",
"[",
"img_arr",
">",
"0",
"]",
"return",
"np",
".",
"percentile",
"(",
"img_arr",
"[",
"img_arr",
">",
"0",
"]",
",",
"q",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'q argument must be list/tuple or float/int'",
")"
] | Get the quantile values from an ANTsImage | [
"Get",
"the",
"quantile",
"values",
"from",
"an",
"ANTsImage"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/quantile.py#L153-L171 | train | 232,028 |
ANTsX/ANTsPy | ants/utils/quantile.py | bandpass_filter_matrix | def bandpass_filter_matrix( matrix,
tr=1, lowf=0.01, highf=0.1, order = 3):
"""
Bandpass filter the input time series image
ANTsR function: `frequencyFilterfMRI`
Arguments
---------
image: input time series image
tr: sampling time interval (inverse of sampling rate)
lowf: low frequency cutoff
highf: high frequency cutoff
order: order of the butterworth filter run using `filtfilt`
Returns
-------
filtered matrix
Example
-------
>>> import numpy as np
>>> import ants
>>> import matplotlib.pyplot as plt
>>> brainSignal = np.random.randn( 400, 1000 )
>>> tr = 1
>>> filtered = ants.bandpass_filter_matrix( brainSignal, tr = tr )
>>> nsamples = brainSignal.shape[0]
>>> t = np.linspace(0, tr*nsamples, nsamples, endpoint=False)
>>> k = 20
>>> plt.plot(t, brainSignal[:,k], label='Noisy signal')
>>> plt.plot(t, filtered[:,k], label='Filtered signal')
>>> plt.xlabel('time (seconds)')
>>> plt.grid(True)
>>> plt.axis('tight')
>>> plt.legend(loc='upper left')
>>> plt.show()
"""
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 butter_bandpass_filter(data, lowcut, highcut, fs, order ):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = filtfilt(b, a, data)
return y
fs = 1/tr # sampling rate based on tr
nsamples = matrix.shape[0]
ncolumns = matrix.shape[1]
matrixOut = matrix.copy()
for k in range( ncolumns ):
matrixOut[:,k] = butter_bandpass_filter(
matrix[:,k], lowf, highf, fs, order=order )
return matrixOut | python | def bandpass_filter_matrix( matrix,
tr=1, lowf=0.01, highf=0.1, order = 3):
"""
Bandpass filter the input time series image
ANTsR function: `frequencyFilterfMRI`
Arguments
---------
image: input time series image
tr: sampling time interval (inverse of sampling rate)
lowf: low frequency cutoff
highf: high frequency cutoff
order: order of the butterworth filter run using `filtfilt`
Returns
-------
filtered matrix
Example
-------
>>> import numpy as np
>>> import ants
>>> import matplotlib.pyplot as plt
>>> brainSignal = np.random.randn( 400, 1000 )
>>> tr = 1
>>> filtered = ants.bandpass_filter_matrix( brainSignal, tr = tr )
>>> nsamples = brainSignal.shape[0]
>>> t = np.linspace(0, tr*nsamples, nsamples, endpoint=False)
>>> k = 20
>>> plt.plot(t, brainSignal[:,k], label='Noisy signal')
>>> plt.plot(t, filtered[:,k], label='Filtered signal')
>>> plt.xlabel('time (seconds)')
>>> plt.grid(True)
>>> plt.axis('tight')
>>> plt.legend(loc='upper left')
>>> plt.show()
"""
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 butter_bandpass_filter(data, lowcut, highcut, fs, order ):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = filtfilt(b, a, data)
return y
fs = 1/tr # sampling rate based on tr
nsamples = matrix.shape[0]
ncolumns = matrix.shape[1]
matrixOut = matrix.copy()
for k in range( ncolumns ):
matrixOut[:,k] = butter_bandpass_filter(
matrix[:,k], lowf, highf, fs, order=order )
return matrixOut | [
"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",
"butter_bandpass_filter",
"(",
"data",
",",
"lowcut",
",",
"highcut",
",",
"fs",
",",
"order",
")",
":",
"b",
",",
"a",
"=",
"butter_bandpass",
"(",
"lowcut",
",",
"highcut",
",",
"fs",
",",
"order",
"=",
"order",
")",
"y",
"=",
"filtfilt",
"(",
"b",
",",
"a",
",",
"data",
")",
"return",
"y",
"fs",
"=",
"1",
"/",
"tr",
"# sampling rate based on tr",
"nsamples",
"=",
"matrix",
".",
"shape",
"[",
"0",
"]",
"ncolumns",
"=",
"matrix",
".",
"shape",
"[",
"1",
"]",
"matrixOut",
"=",
"matrix",
".",
"copy",
"(",
")",
"for",
"k",
"in",
"range",
"(",
"ncolumns",
")",
":",
"matrixOut",
"[",
":",
",",
"k",
"]",
"=",
"butter_bandpass_filter",
"(",
"matrix",
"[",
":",
",",
"k",
"]",
",",
"lowf",
",",
"highf",
",",
"fs",
",",
"order",
"=",
"order",
")",
"return",
"matrixOut"
] | Bandpass filter the input time series image
ANTsR function: `frequencyFilterfMRI`
Arguments
---------
image: input time series image
tr: sampling time interval (inverse of sampling rate)
lowf: low frequency cutoff
highf: high frequency cutoff
order: order of the butterworth filter run using `filtfilt`
Returns
-------
filtered matrix
Example
-------
>>> import numpy as np
>>> import ants
>>> import matplotlib.pyplot as plt
>>> brainSignal = np.random.randn( 400, 1000 )
>>> tr = 1
>>> filtered = ants.bandpass_filter_matrix( brainSignal, tr = tr )
>>> nsamples = brainSignal.shape[0]
>>> t = np.linspace(0, tr*nsamples, nsamples, endpoint=False)
>>> k = 20
>>> plt.plot(t, brainSignal[:,k], label='Noisy signal')
>>> plt.plot(t, filtered[:,k], label='Filtered signal')
>>> plt.xlabel('time (seconds)')
>>> plt.grid(True)
>>> plt.axis('tight')
>>> plt.legend(loc='upper left')
>>> plt.show() | [
"Bandpass",
"filter",
"the",
"input",
"time",
"series",
"image"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/quantile.py#L227-L292 | train | 232,029 |
ANTsX/ANTsPy | ants/utils/quantile.py | compcor | def compcor( boldImage, ncompcor=4, quantile=0.975, mask=None, filter_type=False, degree=2 ):
"""
Compute noise components from the input image
ANTsR function: `compcor`
this is adapted from nipy code https://github.com/nipy/nipype/blob/e29ac95fc0fc00fedbcaa0adaf29d5878408ca7c/nipype/algorithms/confounds.py
Arguments
---------
boldImage: input time series image
ncompcor: number of noise components to return
quantile: quantile defining high-variance
mask: mask defining brain or specific tissues
filter_type: type off filter to apply to time series before computing
noise components.
'polynomial' - Legendre polynomial basis
False - None (mean-removal only)
degree: order of polynomial used to remove trends from the timeseries
Returns
-------
dictionary containing:
components: a numpy array
basis: a numpy array containing the (non-constant) filter regressors
Example
-------
>>> cc = ants.compcor( ants.image_read(ants.get_ants_data("ch2")) )
"""
def compute_tSTD(M, quantile, x=0, axis=0):
stdM = np.std(M, axis=axis)
# set bad values to x
stdM[stdM == 0] = x
stdM[np.isnan(stdM)] = x
tt = round( quantile*100 )
threshold_std = np.percentile( stdM, tt )
# threshold_std = quantile( stdM, quantile )
return { 'tSTD': stdM, 'threshold_std': threshold_std}
if mask is None:
temp = utils.slice_image( boldImage, axis=boldImage.dimension-1, idx=0 )
mask = utils.get_mask( temp )
imagematrix = core.timeseries_to_matrix( boldImage, mask )
temp = compute_tSTD( imagematrix, quantile, 0 )
tsnrmask = core.make_image( mask, temp['tSTD'] )
tsnrmask = utils.threshold_image( tsnrmask, temp['threshold_std'], temp['tSTD'].max() )
M = core.timeseries_to_matrix( boldImage, tsnrmask )
components = None
basis = np.array([])
if filter_type in ('polynomial', False):
M, basis = regress_poly(degree, M)
# M = M / compute_tSTD(M, 1.)['tSTD']
# "The covariance matrix C = MMT was constructed and decomposed into its
# principal components using a singular value decomposition."
u, _, _ = linalg.svd(M, full_matrices=False)
if components is None:
components = u[:, :ncompcor]
else:
components = np.hstack((components, u[:, :ncompcor]))
if components is None and ncompcor > 0:
raise ValueError('No components found')
return { 'components': components, 'basis': basis } | python | def compcor( boldImage, ncompcor=4, quantile=0.975, mask=None, filter_type=False, degree=2 ):
"""
Compute noise components from the input image
ANTsR function: `compcor`
this is adapted from nipy code https://github.com/nipy/nipype/blob/e29ac95fc0fc00fedbcaa0adaf29d5878408ca7c/nipype/algorithms/confounds.py
Arguments
---------
boldImage: input time series image
ncompcor: number of noise components to return
quantile: quantile defining high-variance
mask: mask defining brain or specific tissues
filter_type: type off filter to apply to time series before computing
noise components.
'polynomial' - Legendre polynomial basis
False - None (mean-removal only)
degree: order of polynomial used to remove trends from the timeseries
Returns
-------
dictionary containing:
components: a numpy array
basis: a numpy array containing the (non-constant) filter regressors
Example
-------
>>> cc = ants.compcor( ants.image_read(ants.get_ants_data("ch2")) )
"""
def compute_tSTD(M, quantile, x=0, axis=0):
stdM = np.std(M, axis=axis)
# set bad values to x
stdM[stdM == 0] = x
stdM[np.isnan(stdM)] = x
tt = round( quantile*100 )
threshold_std = np.percentile( stdM, tt )
# threshold_std = quantile( stdM, quantile )
return { 'tSTD': stdM, 'threshold_std': threshold_std}
if mask is None:
temp = utils.slice_image( boldImage, axis=boldImage.dimension-1, idx=0 )
mask = utils.get_mask( temp )
imagematrix = core.timeseries_to_matrix( boldImage, mask )
temp = compute_tSTD( imagematrix, quantile, 0 )
tsnrmask = core.make_image( mask, temp['tSTD'] )
tsnrmask = utils.threshold_image( tsnrmask, temp['threshold_std'], temp['tSTD'].max() )
M = core.timeseries_to_matrix( boldImage, tsnrmask )
components = None
basis = np.array([])
if filter_type in ('polynomial', False):
M, basis = regress_poly(degree, M)
# M = M / compute_tSTD(M, 1.)['tSTD']
# "The covariance matrix C = MMT was constructed and decomposed into its
# principal components using a singular value decomposition."
u, _, _ = linalg.svd(M, full_matrices=False)
if components is None:
components = u[:, :ncompcor]
else:
components = np.hstack((components, u[:, :ncompcor]))
if components is None and ncompcor > 0:
raise ValueError('No components found')
return { 'components': components, 'basis': basis } | [
"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",
")",
"# set bad values to x",
"stdM",
"[",
"stdM",
"==",
"0",
"]",
"=",
"x",
"stdM",
"[",
"np",
".",
"isnan",
"(",
"stdM",
")",
"]",
"=",
"x",
"tt",
"=",
"round",
"(",
"quantile",
"*",
"100",
")",
"threshold_std",
"=",
"np",
".",
"percentile",
"(",
"stdM",
",",
"tt",
")",
"# threshold_std = quantile( stdM, quantile )",
"return",
"{",
"'tSTD'",
":",
"stdM",
",",
"'threshold_std'",
":",
"threshold_std",
"}",
"if",
"mask",
"is",
"None",
":",
"temp",
"=",
"utils",
".",
"slice_image",
"(",
"boldImage",
",",
"axis",
"=",
"boldImage",
".",
"dimension",
"-",
"1",
",",
"idx",
"=",
"0",
")",
"mask",
"=",
"utils",
".",
"get_mask",
"(",
"temp",
")",
"imagematrix",
"=",
"core",
".",
"timeseries_to_matrix",
"(",
"boldImage",
",",
"mask",
")",
"temp",
"=",
"compute_tSTD",
"(",
"imagematrix",
",",
"quantile",
",",
"0",
")",
"tsnrmask",
"=",
"core",
".",
"make_image",
"(",
"mask",
",",
"temp",
"[",
"'tSTD'",
"]",
")",
"tsnrmask",
"=",
"utils",
".",
"threshold_image",
"(",
"tsnrmask",
",",
"temp",
"[",
"'threshold_std'",
"]",
",",
"temp",
"[",
"'tSTD'",
"]",
".",
"max",
"(",
")",
")",
"M",
"=",
"core",
".",
"timeseries_to_matrix",
"(",
"boldImage",
",",
"tsnrmask",
")",
"components",
"=",
"None",
"basis",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"filter_type",
"in",
"(",
"'polynomial'",
",",
"False",
")",
":",
"M",
",",
"basis",
"=",
"regress_poly",
"(",
"degree",
",",
"M",
")",
"# M = M / compute_tSTD(M, 1.)['tSTD']",
"# \"The covariance matrix C = MMT was constructed and decomposed into its",
"# principal components using a singular value decomposition.\"",
"u",
",",
"_",
",",
"_",
"=",
"linalg",
".",
"svd",
"(",
"M",
",",
"full_matrices",
"=",
"False",
")",
"if",
"components",
"is",
"None",
":",
"components",
"=",
"u",
"[",
":",
",",
":",
"ncompcor",
"]",
"else",
":",
"components",
"=",
"np",
".",
"hstack",
"(",
"(",
"components",
",",
"u",
"[",
":",
",",
":",
"ncompcor",
"]",
")",
")",
"if",
"components",
"is",
"None",
"and",
"ncompcor",
">",
"0",
":",
"raise",
"ValueError",
"(",
"'No components found'",
")",
"return",
"{",
"'components'",
":",
"components",
",",
"'basis'",
":",
"basis",
"}"
] | Compute noise components from the input image
ANTsR function: `compcor`
this is adapted from nipy code https://github.com/nipy/nipype/blob/e29ac95fc0fc00fedbcaa0adaf29d5878408ca7c/nipype/algorithms/confounds.py
Arguments
---------
boldImage: input time series image
ncompcor: number of noise components to return
quantile: quantile defining high-variance
mask: mask defining brain or specific tissues
filter_type: type off filter to apply to time series before computing
noise components.
'polynomial' - Legendre polynomial basis
False - None (mean-removal only)
degree: order of polynomial used to remove trends from the timeseries
Returns
-------
dictionary containing:
components: a numpy array
basis: a numpy array containing the (non-constant) filter regressors
Example
-------
>>> cc = ants.compcor( ants.image_read(ants.get_ants_data("ch2")) ) | [
"Compute",
"noise",
"components",
"from",
"the",
"input",
"image"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/quantile.py#L295-L367 | train | 232,030 |
ANTsX/ANTsPy | ants/utils/bias_correction.py | n3_bias_field_correction | def n3_bias_field_correction(image, downsample_factor=3):
"""
N3 Bias Field Correction
ANTsR function: `n3BiasFieldCorrection`
Arguments
---------
image : ANTsImage
image to be bias corrected
downsample_factor : scalar
how much to downsample image before performing bias correction
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> image_n3 = ants.n3_bias_field_correction(image)
"""
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 | python | def n3_bias_field_correction(image, downsample_factor=3):
"""
N3 Bias Field Correction
ANTsR function: `n3BiasFieldCorrection`
Arguments
---------
image : ANTsImage
image to be bias corrected
downsample_factor : scalar
how much to downsample image before performing bias correction
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> image_n3 = ants.n3_bias_field_correction(image)
"""
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 | [
"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
ANTsR function: `n3BiasFieldCorrection`
Arguments
---------
image : ANTsImage
image to be bias corrected
downsample_factor : scalar
how much to downsample image before performing bias correction
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> image_n3 = ants.n3_bias_field_correction(image) | [
"N3",
"Bias",
"Field",
"Correction"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/bias_correction.py#L17-L46 | train | 232,031 |
ANTsX/ANTsPy | ants/utils/bias_correction.py | n4_bias_field_correction | 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):
"""
N4 Bias Field Correction
ANTsR function: `n4BiasFieldCorrection`
Arguments
---------
image : ANTsImage
image to bias correct
mask : ANTsImage
input mask, if one is not passed one will be made
shrink_factor : scalar
Shrink factor for multi-resolution correction, typically integer less than 4
convergence : dict w/ keys `iters` and `tol`
iters : vector of maximum number of iterations for each shrinkage factor
tol : the convergence tolerance.
spline_param : integer
Parameter controlling number of control points in spline. Either single value, indicating how many control points, or vector with one entry per dimension of image, indicating the spacing in each direction.
verbose : boolean
enables verbose output.
weight_mask : ANTsImage (optional)
antsImage of weight mask
Returns
-------
ANTsImage
Example
-------
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> image_n4 = ants.n4_bias_field_correction(image)
"""
if image.pixeltype != 'float':
image = image.clone('float')
iters = convergence['iters']
tol = convergence['tol']
if mask is None:
mask = get_mask(image)
N4_CONVERGENCE_1 = '[%s, %.10f]' % ('x'.join([str(it) for it in iters]), tol)
N4_SHRINK_FACTOR_1 = str(shrink_factor)
if (not isinstance(spline_param, (list,tuple))) or (len(spline_param) == 1):
N4_BSPLINE_PARAMS = '[%i]' % spline_param
elif (isinstance(spline_param, (list,tuple))) and (len(spline_param) == image.dimension):
N4_BSPLINE_PARAMS = '[%s]' % ('x'.join([str(sp) for sp in spline_param]))
else:
raise ValueError('Length of splineParam must either be 1 or dimensionality of image')
if weight_mask is not None:
if not isinstance(weight_mask, iio.ANTsImage):
raise ValueError('Weight Image must be an antsImage')
outimage = image.clone()
kwargs = {
'd': outimage.dimension,
'i': image,
'w': weight_mask,
's': N4_SHRINK_FACTOR_1,
'c': N4_CONVERGENCE_1,
'b': N4_BSPLINE_PARAMS,
'x': mask,
'o': outimage,
'v': int(verbose)
}
processed_args = pargs._int_antsProcessArguments(kwargs)
libfn = utils.get_lib_fn('N4BiasFieldCorrection')
libfn(processed_args)
return outimage | python | 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):
"""
N4 Bias Field Correction
ANTsR function: `n4BiasFieldCorrection`
Arguments
---------
image : ANTsImage
image to bias correct
mask : ANTsImage
input mask, if one is not passed one will be made
shrink_factor : scalar
Shrink factor for multi-resolution correction, typically integer less than 4
convergence : dict w/ keys `iters` and `tol`
iters : vector of maximum number of iterations for each shrinkage factor
tol : the convergence tolerance.
spline_param : integer
Parameter controlling number of control points in spline. Either single value, indicating how many control points, or vector with one entry per dimension of image, indicating the spacing in each direction.
verbose : boolean
enables verbose output.
weight_mask : ANTsImage (optional)
antsImage of weight mask
Returns
-------
ANTsImage
Example
-------
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> image_n4 = ants.n4_bias_field_correction(image)
"""
if image.pixeltype != 'float':
image = image.clone('float')
iters = convergence['iters']
tol = convergence['tol']
if mask is None:
mask = get_mask(image)
N4_CONVERGENCE_1 = '[%s, %.10f]' % ('x'.join([str(it) for it in iters]), tol)
N4_SHRINK_FACTOR_1 = str(shrink_factor)
if (not isinstance(spline_param, (list,tuple))) or (len(spline_param) == 1):
N4_BSPLINE_PARAMS = '[%i]' % spline_param
elif (isinstance(spline_param, (list,tuple))) and (len(spline_param) == image.dimension):
N4_BSPLINE_PARAMS = '[%s]' % ('x'.join([str(sp) for sp in spline_param]))
else:
raise ValueError('Length of splineParam must either be 1 or dimensionality of image')
if weight_mask is not None:
if not isinstance(weight_mask, iio.ANTsImage):
raise ValueError('Weight Image must be an antsImage')
outimage = image.clone()
kwargs = {
'd': outimage.dimension,
'i': image,
'w': weight_mask,
's': N4_SHRINK_FACTOR_1,
'c': N4_CONVERGENCE_1,
'b': N4_BSPLINE_PARAMS,
'x': mask,
'o': outimage,
'v': int(verbose)
}
processed_args = pargs._int_antsProcessArguments(kwargs)
libfn = utils.get_lib_fn('N4BiasFieldCorrection')
libfn(processed_args)
return outimage | [
"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",
"[",
"'tol'",
"]",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"get_mask",
"(",
"image",
")",
"N4_CONVERGENCE_1",
"=",
"'[%s, %.10f]'",
"%",
"(",
"'x'",
".",
"join",
"(",
"[",
"str",
"(",
"it",
")",
"for",
"it",
"in",
"iters",
"]",
")",
",",
"tol",
")",
"N4_SHRINK_FACTOR_1",
"=",
"str",
"(",
"shrink_factor",
")",
"if",
"(",
"not",
"isinstance",
"(",
"spline_param",
",",
"(",
"list",
",",
"tuple",
")",
")",
")",
"or",
"(",
"len",
"(",
"spline_param",
")",
"==",
"1",
")",
":",
"N4_BSPLINE_PARAMS",
"=",
"'[%i]'",
"%",
"spline_param",
"elif",
"(",
"isinstance",
"(",
"spline_param",
",",
"(",
"list",
",",
"tuple",
")",
")",
")",
"and",
"(",
"len",
"(",
"spline_param",
")",
"==",
"image",
".",
"dimension",
")",
":",
"N4_BSPLINE_PARAMS",
"=",
"'[%s]'",
"%",
"(",
"'x'",
".",
"join",
"(",
"[",
"str",
"(",
"sp",
")",
"for",
"sp",
"in",
"spline_param",
"]",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Length of splineParam must either be 1 or dimensionality of image'",
")",
"if",
"weight_mask",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"weight_mask",
",",
"iio",
".",
"ANTsImage",
")",
":",
"raise",
"ValueError",
"(",
"'Weight Image must be an antsImage'",
")",
"outimage",
"=",
"image",
".",
"clone",
"(",
")",
"kwargs",
"=",
"{",
"'d'",
":",
"outimage",
".",
"dimension",
",",
"'i'",
":",
"image",
",",
"'w'",
":",
"weight_mask",
",",
"'s'",
":",
"N4_SHRINK_FACTOR_1",
",",
"'c'",
":",
"N4_CONVERGENCE_1",
",",
"'b'",
":",
"N4_BSPLINE_PARAMS",
",",
"'x'",
":",
"mask",
",",
"'o'",
":",
"outimage",
",",
"'v'",
":",
"int",
"(",
"verbose",
")",
"}",
"processed_args",
"=",
"pargs",
".",
"_int_antsProcessArguments",
"(",
"kwargs",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'N4BiasFieldCorrection'",
")",
"libfn",
"(",
"processed_args",
")",
"return",
"outimage"
] | N4 Bias Field Correction
ANTsR function: `n4BiasFieldCorrection`
Arguments
---------
image : ANTsImage
image to bias correct
mask : ANTsImage
input mask, if one is not passed one will be made
shrink_factor : scalar
Shrink factor for multi-resolution correction, typically integer less than 4
convergence : dict w/ keys `iters` and `tol`
iters : vector of maximum number of iterations for each shrinkage factor
tol : the convergence tolerance.
spline_param : integer
Parameter controlling number of control points in spline. Either single value, indicating how many control points, or vector with one entry per dimension of image, indicating the spacing in each direction.
verbose : boolean
enables verbose output.
weight_mask : ANTsImage (optional)
antsImage of weight mask
Returns
-------
ANTsImage
Example
-------
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> image_n4 = ants.n4_bias_field_correction(image) | [
"N4",
"Bias",
"Field",
"Correction"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/bias_correction.py#L49-L126 | train | 232,032 |
ANTsX/ANTsPy | ants/utils/bias_correction.py | abp_n4 | def abp_n4(image, intensity_truncation=(0.025,0.975,256), mask=None, usen3=False):
"""
Truncate outlier intensities and bias correct with the N4 algorithm.
ANTsR function: `abpN4`
Arguments
---------
image : ANTsImage
image to correct and truncate
intensity_truncation : 3-tuple
quantiles for intensity truncation
mask : ANTsImage (optional)
mask for bias correction
usen3 : boolean
if True, use N3 bias correction instead of N4
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> image2 = ants.abp_n4(image)
"""
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, 'TruncateIntensity',
intensity_truncation[0], intensity_truncation[1], intensity_truncation[2])
if usen3 == True:
outimage = n3_bias_field_correction(outimage, 4)
outimage = n3_bias_field_correction(outimage, 2)
return outimage
else:
outimage = n4_bias_field_correction(outimage, mask)
return outimage | python | def abp_n4(image, intensity_truncation=(0.025,0.975,256), mask=None, usen3=False):
"""
Truncate outlier intensities and bias correct with the N4 algorithm.
ANTsR function: `abpN4`
Arguments
---------
image : ANTsImage
image to correct and truncate
intensity_truncation : 3-tuple
quantiles for intensity truncation
mask : ANTsImage (optional)
mask for bias correction
usen3 : boolean
if True, use N3 bias correction instead of N4
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> image2 = ants.abp_n4(image)
"""
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, 'TruncateIntensity',
intensity_truncation[0], intensity_truncation[1], intensity_truncation[2])
if usen3 == True:
outimage = n3_bias_field_correction(outimage, 4)
outimage = n3_bias_field_correction(outimage, 2)
return outimage
else:
outimage = n4_bias_field_correction(outimage, mask)
return outimage | [
"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",
",",
"'TruncateIntensity'",
",",
"intensity_truncation",
"[",
"0",
"]",
",",
"intensity_truncation",
"[",
"1",
"]",
",",
"intensity_truncation",
"[",
"2",
"]",
")",
"if",
"usen3",
"==",
"True",
":",
"outimage",
"=",
"n3_bias_field_correction",
"(",
"outimage",
",",
"4",
")",
"outimage",
"=",
"n3_bias_field_correction",
"(",
"outimage",
",",
"2",
")",
"return",
"outimage",
"else",
":",
"outimage",
"=",
"n4_bias_field_correction",
"(",
"outimage",
",",
"mask",
")",
"return",
"outimage"
] | Truncate outlier intensities and bias correct with the N4 algorithm.
ANTsR function: `abpN4`
Arguments
---------
image : ANTsImage
image to correct and truncate
intensity_truncation : 3-tuple
quantiles for intensity truncation
mask : ANTsImage (optional)
mask for bias correction
usen3 : boolean
if True, use N3 bias correction instead of N4
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> image2 = ants.abp_n4(image) | [
"Truncate",
"outlier",
"intensities",
"and",
"bias",
"correct",
"with",
"the",
"N4",
"algorithm",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/bias_correction.py#L129-L169 | train | 232,033 |
ANTsX/ANTsPy | ants/registration/metrics.py | image_mutual_information | def image_mutual_information(image1, image2):
"""
Compute mutual information between two ANTsImage types
ANTsR function: `antsImageMutualInformation`
Arguments
---------
image1 : ANTsImage
image 1
image2 : ANTsImage
image 2
Returns
-------
scalar
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') ).clone('float')
>>> mi = ants.image_read( ants.get_ants_data('r64') ).clone('float')
>>> mival = ants.image_mutual_information(fi, mi) # -0.1796141
"""
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('antsImageMutualInformation%iD' % image1.dimension)
return libfn(image1.pointer, image2.pointer) | python | def image_mutual_information(image1, image2):
"""
Compute mutual information between two ANTsImage types
ANTsR function: `antsImageMutualInformation`
Arguments
---------
image1 : ANTsImage
image 1
image2 : ANTsImage
image 2
Returns
-------
scalar
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') ).clone('float')
>>> mi = ants.image_read( ants.get_ants_data('r64') ).clone('float')
>>> mival = ants.image_mutual_information(fi, mi) # -0.1796141
"""
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('antsImageMutualInformation%iD' % image1.dimension)
return libfn(image1.pointer, image2.pointer) | [
"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",
"(",
"'antsImageMutualInformation%iD'",
"%",
"image1",
".",
"dimension",
")",
"return",
"libfn",
"(",
"image1",
".",
"pointer",
",",
"image2",
".",
"pointer",
")"
] | Compute mutual information between two ANTsImage types
ANTsR function: `antsImageMutualInformation`
Arguments
---------
image1 : ANTsImage
image 1
image2 : ANTsImage
image 2
Returns
-------
scalar
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') ).clone('float')
>>> mi = ants.image_read( ants.get_ants_data('r64') ).clone('float')
>>> mival = ants.image_mutual_information(fi, mi) # -0.1796141 | [
"Compute",
"mutual",
"information",
"between",
"two",
"ANTsImage",
"types"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/metrics.py#L10-L42 | train | 232,034 |
ANTsX/ANTsPy | ants/utils/get_mask.py | get_mask | def get_mask(image, low_thresh=None, high_thresh=None, cleanup=2):
"""
Get a binary mask image from the given image after thresholding
ANTsR function: `getMask`
Arguments
---------
image : ANTsImage
image from which mask will be computed. Can be an antsImage of 2, 3 or 4 dimensions.
low_thresh : scalar (optional)
An inclusive lower threshold for voxels to be included in the mask.
If not given, defaults to image mean.
high_thresh : scalar (optional)
An inclusive upper threshold for voxels to be included in the mask.
If not given, defaults to image max
cleanup : integer
If > 0, morphological operations will be applied to clean up the mask by eroding away small or weakly-connected areas, and closing holes.
If cleanup is >0, the following steps are applied
1. Erosion with radius 2 voxels
2. Retain largest component
3. Dilation with radius 1 voxel
4. Morphological closing
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> mask = ants.get_mask(image)
"""
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.max()
mask_image = threshold_image(image, low_thresh, high_thresh)
if cleanup > 0:
mask_image = iMath(mask_image, 'ME', cleanup)
mask_image = iMath(mask_image, 'GetLargestComponent')
mask_image = iMath(mask_image, 'MD', cleanup)
mask_image = iMath(mask_image, 'FillHoles').threshold_image( 1, 2 )
while ((mask_image.min() == mask_image.max()) and (cleanup > 0)):
cleanup = cleanup - 1
mask_image = threshold_image(image, low_thresh, high_thresh)
if cleanup > 0:
mask_image = iMath(mask_image, 'ME', cleanup)
mask_image = iMath(mask_image, 'MD', cleanup)
mask_image = iMath(mask_image, 'FillHoles').threshold_image( 1, 2 )
#if cleanup == 0:
# clustlab = label_clusters(mask_image, 1)
# mask_image = threshold_image(clustlab, 1, 1)
return mask_image | python | def get_mask(image, low_thresh=None, high_thresh=None, cleanup=2):
"""
Get a binary mask image from the given image after thresholding
ANTsR function: `getMask`
Arguments
---------
image : ANTsImage
image from which mask will be computed. Can be an antsImage of 2, 3 or 4 dimensions.
low_thresh : scalar (optional)
An inclusive lower threshold for voxels to be included in the mask.
If not given, defaults to image mean.
high_thresh : scalar (optional)
An inclusive upper threshold for voxels to be included in the mask.
If not given, defaults to image max
cleanup : integer
If > 0, morphological operations will be applied to clean up the mask by eroding away small or weakly-connected areas, and closing holes.
If cleanup is >0, the following steps are applied
1. Erosion with radius 2 voxels
2. Retain largest component
3. Dilation with radius 1 voxel
4. Morphological closing
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> mask = ants.get_mask(image)
"""
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.max()
mask_image = threshold_image(image, low_thresh, high_thresh)
if cleanup > 0:
mask_image = iMath(mask_image, 'ME', cleanup)
mask_image = iMath(mask_image, 'GetLargestComponent')
mask_image = iMath(mask_image, 'MD', cleanup)
mask_image = iMath(mask_image, 'FillHoles').threshold_image( 1, 2 )
while ((mask_image.min() == mask_image.max()) and (cleanup > 0)):
cleanup = cleanup - 1
mask_image = threshold_image(image, low_thresh, high_thresh)
if cleanup > 0:
mask_image = iMath(mask_image, 'ME', cleanup)
mask_image = iMath(mask_image, 'MD', cleanup)
mask_image = iMath(mask_image, 'FillHoles').threshold_image( 1, 2 )
#if cleanup == 0:
# clustlab = label_clusters(mask_image, 1)
# mask_image = threshold_image(clustlab, 1, 1)
return mask_image | [
"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",
".",
"max",
"(",
")",
"mask_image",
"=",
"threshold_image",
"(",
"image",
",",
"low_thresh",
",",
"high_thresh",
")",
"if",
"cleanup",
">",
"0",
":",
"mask_image",
"=",
"iMath",
"(",
"mask_image",
",",
"'ME'",
",",
"cleanup",
")",
"mask_image",
"=",
"iMath",
"(",
"mask_image",
",",
"'GetLargestComponent'",
")",
"mask_image",
"=",
"iMath",
"(",
"mask_image",
",",
"'MD'",
",",
"cleanup",
")",
"mask_image",
"=",
"iMath",
"(",
"mask_image",
",",
"'FillHoles'",
")",
".",
"threshold_image",
"(",
"1",
",",
"2",
")",
"while",
"(",
"(",
"mask_image",
".",
"min",
"(",
")",
"==",
"mask_image",
".",
"max",
"(",
")",
")",
"and",
"(",
"cleanup",
">",
"0",
")",
")",
":",
"cleanup",
"=",
"cleanup",
"-",
"1",
"mask_image",
"=",
"threshold_image",
"(",
"image",
",",
"low_thresh",
",",
"high_thresh",
")",
"if",
"cleanup",
">",
"0",
":",
"mask_image",
"=",
"iMath",
"(",
"mask_image",
",",
"'ME'",
",",
"cleanup",
")",
"mask_image",
"=",
"iMath",
"(",
"mask_image",
",",
"'MD'",
",",
"cleanup",
")",
"mask_image",
"=",
"iMath",
"(",
"mask_image",
",",
"'FillHoles'",
")",
".",
"threshold_image",
"(",
"1",
",",
"2",
")",
"#if cleanup == 0:",
"# clustlab = label_clusters(mask_image, 1)",
"# mask_image = threshold_image(clustlab, 1, 1)",
"return",
"mask_image"
] | Get a binary mask image from the given image after thresholding
ANTsR function: `getMask`
Arguments
---------
image : ANTsImage
image from which mask will be computed. Can be an antsImage of 2, 3 or 4 dimensions.
low_thresh : scalar (optional)
An inclusive lower threshold for voxels to be included in the mask.
If not given, defaults to image mean.
high_thresh : scalar (optional)
An inclusive upper threshold for voxels to be included in the mask.
If not given, defaults to image max
cleanup : integer
If > 0, morphological operations will be applied to clean up the mask by eroding away small or weakly-connected areas, and closing holes.
If cleanup is >0, the following steps are applied
1. Erosion with radius 2 voxels
2. Retain largest component
3. Dilation with radius 1 voxel
4. Morphological closing
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> mask = ants.get_mask(image) | [
"Get",
"a",
"binary",
"mask",
"image",
"from",
"the",
"given",
"image",
"after",
"thresholding"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/get_mask.py#L13-L78 | train | 232,035 |
ANTsX/ANTsPy | ants/utils/label_image_centroids.py | label_image_centroids | def label_image_centroids(image, physical=False, convex=True, verbose=False):
"""
Converts a label image to coordinates summarizing their positions
ANTsR function: `labelImageCentroids`
Arguments
---------
image : ANTsImage
image of integer labels
physical : boolean
whether you want physical space coordinates or not
convex : boolean
if True, return centroid
if False return point with min average distance to other points with same label
Returns
-------
dictionary w/ following key-value pairs:
`labels` : 1D-ndarray
array of label values
`vertices` : pd.DataFrame
coordinates of label centroids
Example
-------
>>> import ants
>>> import numpy as np
>>> image = ants.from_numpy(np.asarray([[[0,2],[1,3]],[[4,6],[5,7]]]).astype('float32'))
>>> labels = ants.label_image_centroids(image)
"""
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(d[1]),d[0]).tolist()*d[2])
zcoords = np.asarray(np.repeat(np.arange(d[1]), d[0]*d[2]))
labels = image.numpy()
mylabels = np.sort(np.unique(labels[labels > 0])).astype('int')
n_labels = len(mylabels)
xc = np.zeros(n_labels)
yc = np.zeros(n_labels)
zc = np.zeros(n_labels)
if convex:
for i in mylabels:
idx = (labels == i).flatten()
xc[i-1] = np.mean(xcoords[idx])
yc[i-1] = np.mean(ycoords[idx])
zc[i-1] = np.mean(zcoords[idx])
else:
for i in mylabels:
idx = (labels == i).flatten()
xci = xcoords[idx]
yci = ycoords[idx]
zci = zcoords[idx]
dist = np.zeros(len(xci))
for j in range(len(xci)):
dist[j] = np.mean(np.sqrt((xci[j] - xci)**2 + (yci[j] - yci)**2 + (zci[j] - zci)**2))
mid = np.where(dist==np.min(dist))
xc[i-1] = xci[mid]
yc[i-1] = yci[mid]
zc[i-1] = zci[mid]
centroids = np.vstack([xc,yc,zc]).T
#if physical:
# centroids = tio.transform_index_to_physical_point(image, centroids)
return {
'labels': mylabels,
'vertices': centroids
} | python | def label_image_centroids(image, physical=False, convex=True, verbose=False):
"""
Converts a label image to coordinates summarizing their positions
ANTsR function: `labelImageCentroids`
Arguments
---------
image : ANTsImage
image of integer labels
physical : boolean
whether you want physical space coordinates or not
convex : boolean
if True, return centroid
if False return point with min average distance to other points with same label
Returns
-------
dictionary w/ following key-value pairs:
`labels` : 1D-ndarray
array of label values
`vertices` : pd.DataFrame
coordinates of label centroids
Example
-------
>>> import ants
>>> import numpy as np
>>> image = ants.from_numpy(np.asarray([[[0,2],[1,3]],[[4,6],[5,7]]]).astype('float32'))
>>> labels = ants.label_image_centroids(image)
"""
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(d[1]),d[0]).tolist()*d[2])
zcoords = np.asarray(np.repeat(np.arange(d[1]), d[0]*d[2]))
labels = image.numpy()
mylabels = np.sort(np.unique(labels[labels > 0])).astype('int')
n_labels = len(mylabels)
xc = np.zeros(n_labels)
yc = np.zeros(n_labels)
zc = np.zeros(n_labels)
if convex:
for i in mylabels:
idx = (labels == i).flatten()
xc[i-1] = np.mean(xcoords[idx])
yc[i-1] = np.mean(ycoords[idx])
zc[i-1] = np.mean(zcoords[idx])
else:
for i in mylabels:
idx = (labels == i).flatten()
xci = xcoords[idx]
yci = ycoords[idx]
zci = zcoords[idx]
dist = np.zeros(len(xci))
for j in range(len(xci)):
dist[j] = np.mean(np.sqrt((xci[j] - xci)**2 + (yci[j] - yci)**2 + (zci[j] - zci)**2))
mid = np.where(dist==np.min(dist))
xc[i-1] = xci[mid]
yc[i-1] = yci[mid]
zc[i-1] = zci[mid]
centroids = np.vstack([xc,yc,zc]).T
#if physical:
# centroids = tio.transform_index_to_physical_point(image, centroids)
return {
'labels': mylabels,
'vertices': centroids
} | [
"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",
"(",
"d",
"[",
"1",
"]",
")",
",",
"d",
"[",
"0",
"]",
")",
".",
"tolist",
"(",
")",
"*",
"d",
"[",
"2",
"]",
")",
"zcoords",
"=",
"np",
".",
"asarray",
"(",
"np",
".",
"repeat",
"(",
"np",
".",
"arange",
"(",
"d",
"[",
"1",
"]",
")",
",",
"d",
"[",
"0",
"]",
"*",
"d",
"[",
"2",
"]",
")",
")",
"labels",
"=",
"image",
".",
"numpy",
"(",
")",
"mylabels",
"=",
"np",
".",
"sort",
"(",
"np",
".",
"unique",
"(",
"labels",
"[",
"labels",
">",
"0",
"]",
")",
")",
".",
"astype",
"(",
"'int'",
")",
"n_labels",
"=",
"len",
"(",
"mylabels",
")",
"xc",
"=",
"np",
".",
"zeros",
"(",
"n_labels",
")",
"yc",
"=",
"np",
".",
"zeros",
"(",
"n_labels",
")",
"zc",
"=",
"np",
".",
"zeros",
"(",
"n_labels",
")",
"if",
"convex",
":",
"for",
"i",
"in",
"mylabels",
":",
"idx",
"=",
"(",
"labels",
"==",
"i",
")",
".",
"flatten",
"(",
")",
"xc",
"[",
"i",
"-",
"1",
"]",
"=",
"np",
".",
"mean",
"(",
"xcoords",
"[",
"idx",
"]",
")",
"yc",
"[",
"i",
"-",
"1",
"]",
"=",
"np",
".",
"mean",
"(",
"ycoords",
"[",
"idx",
"]",
")",
"zc",
"[",
"i",
"-",
"1",
"]",
"=",
"np",
".",
"mean",
"(",
"zcoords",
"[",
"idx",
"]",
")",
"else",
":",
"for",
"i",
"in",
"mylabels",
":",
"idx",
"=",
"(",
"labels",
"==",
"i",
")",
".",
"flatten",
"(",
")",
"xci",
"=",
"xcoords",
"[",
"idx",
"]",
"yci",
"=",
"ycoords",
"[",
"idx",
"]",
"zci",
"=",
"zcoords",
"[",
"idx",
"]",
"dist",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"xci",
")",
")",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"xci",
")",
")",
":",
"dist",
"[",
"j",
"]",
"=",
"np",
".",
"mean",
"(",
"np",
".",
"sqrt",
"(",
"(",
"xci",
"[",
"j",
"]",
"-",
"xci",
")",
"**",
"2",
"+",
"(",
"yci",
"[",
"j",
"]",
"-",
"yci",
")",
"**",
"2",
"+",
"(",
"zci",
"[",
"j",
"]",
"-",
"zci",
")",
"**",
"2",
")",
")",
"mid",
"=",
"np",
".",
"where",
"(",
"dist",
"==",
"np",
".",
"min",
"(",
"dist",
")",
")",
"xc",
"[",
"i",
"-",
"1",
"]",
"=",
"xci",
"[",
"mid",
"]",
"yc",
"[",
"i",
"-",
"1",
"]",
"=",
"yci",
"[",
"mid",
"]",
"zc",
"[",
"i",
"-",
"1",
"]",
"=",
"zci",
"[",
"mid",
"]",
"centroids",
"=",
"np",
".",
"vstack",
"(",
"[",
"xc",
",",
"yc",
",",
"zc",
"]",
")",
".",
"T",
"#if physical:",
"# centroids = tio.transform_index_to_physical_point(image, centroids)",
"return",
"{",
"'labels'",
":",
"mylabels",
",",
"'vertices'",
":",
"centroids",
"}"
] | Converts a label image to coordinates summarizing their positions
ANTsR function: `labelImageCentroids`
Arguments
---------
image : ANTsImage
image of integer labels
physical : boolean
whether you want physical space coordinates or not
convex : boolean
if True, return centroid
if False return point with min average distance to other points with same label
Returns
-------
dictionary w/ following key-value pairs:
`labels` : 1D-ndarray
array of label values
`vertices` : pd.DataFrame
coordinates of label centroids
Example
-------
>>> import ants
>>> import numpy as np
>>> image = ants.from_numpy(np.asarray([[[0,2],[1,3]],[[4,6],[5,7]]]).astype('float32'))
>>> labels = ants.label_image_centroids(image) | [
"Converts",
"a",
"label",
"image",
"to",
"coordinates",
"summarizing",
"their",
"positions"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/label_image_centroids.py#L10-L89 | train | 232,036 |
ANTsX/ANTsPy | ants/contrib/sampling/transforms.py | MultiResolutionImage.transform | def transform(self, X, y=None):
"""
Generate a set of multi-resolution ANTsImage types
Arguments
---------
X : ANTsImage
image to transform
y : ANTsImage (optional)
another image to transform
Example
-------
>>> import ants
>>> multires = ants.contrib.MultiResolutionImage(levels=4)
>>> img = ants.image_read(ants.get_data('r16'))
>>> imgs = multires.transform(img)
"""
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.dimension,
components=X.components, pointer=casted_ptr)
if self.keep_shape:
img = img.resample_image_to_target(X)
imgs.append(img)
return imgs | python | def transform(self, X, y=None):
"""
Generate a set of multi-resolution ANTsImage types
Arguments
---------
X : ANTsImage
image to transform
y : ANTsImage (optional)
another image to transform
Example
-------
>>> import ants
>>> multires = ants.contrib.MultiResolutionImage(levels=4)
>>> img = ants.image_read(ants.get_data('r16'))
>>> imgs = multires.transform(img)
"""
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.dimension,
components=X.components, pointer=casted_ptr)
if self.keep_shape:
img = img.resample_image_to_target(X)
imgs.append(img)
return imgs | [
"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",
".",
"dimension",
",",
"components",
"=",
"X",
".",
"components",
",",
"pointer",
"=",
"casted_ptr",
")",
"if",
"self",
".",
"keep_shape",
":",
"img",
"=",
"img",
".",
"resample_image_to_target",
"(",
"X",
")",
"imgs",
".",
"append",
"(",
"img",
")",
"return",
"imgs"
] | Generate a set of multi-resolution ANTsImage types
Arguments
---------
X : ANTsImage
image to transform
y : ANTsImage (optional)
another image to transform
Example
-------
>>> import ants
>>> multires = ants.contrib.MultiResolutionImage(levels=4)
>>> img = ants.image_read(ants.get_data('r16'))
>>> imgs = multires.transform(img) | [
"Generate",
"a",
"set",
"of",
"multi",
"-",
"resolution",
"ANTsImage",
"types"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/transforms.py#L60-L91 | train | 232,037 |
ANTsX/ANTsPy | ants/contrib/sampling/transforms.py | LocallyBlurIntensity.transform | def transform(self, X, y=None):
"""
Locally blur an image by applying a gradient anisotropic diffusion filter.
Arguments
---------
X : ANTsImage
image to transform
y : ANTsImage (optional)
another image to transform.
Example
-------
>>> import ants
>>> blur = ants.contrib.LocallyBlurIntensity(1,5)
>>> img2d = ants.image_read(ants.get_data('r16'))
>>> img2d_b = blur.transform(img2d)
>>> ants.plot(img2d)
>>> ants.plot(img2d_b)
>>> img3d = ants.image_read(ants.get_data('mni'))
>>> img3d_b = blur.transform(img3d)
>>> ants.plot(img3d)
>>> ants.plot(img3d_b)
"""
#if X.pixeltype != 'float':
# raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float')
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, pointer=casted_ptr) | python | def transform(self, X, y=None):
"""
Locally blur an image by applying a gradient anisotropic diffusion filter.
Arguments
---------
X : ANTsImage
image to transform
y : ANTsImage (optional)
another image to transform.
Example
-------
>>> import ants
>>> blur = ants.contrib.LocallyBlurIntensity(1,5)
>>> img2d = ants.image_read(ants.get_data('r16'))
>>> img2d_b = blur.transform(img2d)
>>> ants.plot(img2d)
>>> ants.plot(img2d_b)
>>> img3d = ants.image_read(ants.get_data('mni'))
>>> img3d_b = blur.transform(img3d)
>>> ants.plot(img3d)
>>> ants.plot(img3d_b)
"""
#if X.pixeltype != 'float':
# raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float')
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, pointer=casted_ptr) | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"#if X.pixeltype != 'float':",
"# raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float')",
"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",
",",
"pointer",
"=",
"casted_ptr",
")"
] | Locally blur an image by applying a gradient anisotropic diffusion filter.
Arguments
---------
X : ANTsImage
image to transform
y : ANTsImage (optional)
another image to transform.
Example
-------
>>> import ants
>>> blur = ants.contrib.LocallyBlurIntensity(1,5)
>>> img2d = ants.image_read(ants.get_data('r16'))
>>> img2d_b = blur.transform(img2d)
>>> ants.plot(img2d)
>>> ants.plot(img2d_b)
>>> img3d = ants.image_read(ants.get_data('mni'))
>>> img3d_b = blur.transform(img3d)
>>> ants.plot(img3d)
>>> ants.plot(img3d_b) | [
"Locally",
"blur",
"an",
"image",
"by",
"applying",
"a",
"gradient",
"anisotropic",
"diffusion",
"filter",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/transforms.py#L242-L273 | train | 232,038 |
ANTsX/ANTsPy | ants/utils/get_ants_data.py | get_data | def get_data(name=None):
"""
Get ANTsPy test data filename
ANTsR function: `getANTsRData`
Arguments
---------
name : string
name of test image tag to retrieve
Options:
- 'r16'
- 'r27'
- 'r64'
- 'r85'
- 'ch2'
- 'mni'
- 'surf'
Returns
-------
string
filepath of test image
Example
-------
>>> import ants
>>> mnipath = ants.get_ants_data('mni')
"""
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
for fname in os.listdir(data_path):
if (name == fname.split('.')[0]) or ((name+'slice') == fname.split('.')[0]):
datapath = os.path.join(data_path, fname)
if datapath is None:
raise ValueError('File doesnt exist. Options: ' , os.listdir(data_path))
return datapath | python | def get_data(name=None):
"""
Get ANTsPy test data filename
ANTsR function: `getANTsRData`
Arguments
---------
name : string
name of test image tag to retrieve
Options:
- 'r16'
- 'r27'
- 'r64'
- 'r85'
- 'ch2'
- 'mni'
- 'surf'
Returns
-------
string
filepath of test image
Example
-------
>>> import ants
>>> mnipath = ants.get_ants_data('mni')
"""
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
for fname in os.listdir(data_path):
if (name == fname.split('.')[0]) or ((name+'slice') == fname.split('.')[0]):
datapath = os.path.join(data_path, fname)
if datapath is None:
raise ValueError('File doesnt exist. Options: ' , os.listdir(data_path))
return datapath | [
"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",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"data_path",
")",
":",
"if",
"(",
"name",
"==",
"fname",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"or",
"(",
"(",
"name",
"+",
"'slice'",
")",
"==",
"fname",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
":",
"datapath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_path",
",",
"fname",
")",
"if",
"datapath",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'File doesnt exist. Options: '",
",",
"os",
".",
"listdir",
"(",
"data_path",
")",
")",
"return",
"datapath"
] | Get ANTsPy test data filename
ANTsR function: `getANTsRData`
Arguments
---------
name : string
name of test image tag to retrieve
Options:
- 'r16'
- 'r27'
- 'r64'
- 'r85'
- 'ch2'
- 'mni'
- 'surf'
Returns
-------
string
filepath of test image
Example
-------
>>> import ants
>>> mnipath = ants.get_ants_data('mni') | [
"Get",
"ANTsPy",
"test",
"data",
"filename"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/get_ants_data.py#L11-L54 | train | 232,039 |
ANTsX/ANTsPy | ants/utils/invariant_image_similarity.py | convolve_image | def convolve_image(image, kernel_image, crop=True):
"""
Convolve one image with another
ANTsR function: `convolveImage`
Arguments
---------
image : ANTsImage
image to convolve
kernel_image : ANTsImage
image acting as kernel
crop : boolean
whether to automatically crop kernel_image
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> convimg = ants.make_image( (3,3), (1,0,1,0,-4,0,1,0,1) )
>>> convout = ants.convolve_image( fi, convimg )
>>> convimg2 = ants.make_image( (3,3), (0,1,0,1,0,-1,0,-1,0) )
>>> convout2 = ants.convolve_image( fi, convimg2 )
"""
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 != 'float':
image = image.clone('float')
if kernel_image.pixeltype != 'float':
kernel_image = kernel_image.clone('float')
if crop:
kernel_image_mask = utils.get_mask(kernel_image)
kernel_image = utils.crop_image(kernel_image, kernel_image_mask)
kernel_image_mask = utils.crop_image(kernel_image_mask, kernel_image_mask)
kernel_image[kernel_image_mask==0] = kernel_image[kernel_image_mask==1].mean()
libfn = utils.get_lib_fn('convolveImageF%i' % image.dimension)
conv_itk_image = libfn(image.pointer, kernel_image.pointer)
conv_ants_image = iio.ANTsImage(pixeltype=image.pixeltype, dimension=image.dimension,
components=image.components, pointer=conv_itk_image)
if orig_ptype != 'float':
conv_ants_image = conv_ants_image.clone(orig_ptype)
return conv_ants_image | python | def convolve_image(image, kernel_image, crop=True):
"""
Convolve one image with another
ANTsR function: `convolveImage`
Arguments
---------
image : ANTsImage
image to convolve
kernel_image : ANTsImage
image acting as kernel
crop : boolean
whether to automatically crop kernel_image
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> convimg = ants.make_image( (3,3), (1,0,1,0,-4,0,1,0,1) )
>>> convout = ants.convolve_image( fi, convimg )
>>> convimg2 = ants.make_image( (3,3), (0,1,0,1,0,-1,0,-1,0) )
>>> convout2 = ants.convolve_image( fi, convimg2 )
"""
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 != 'float':
image = image.clone('float')
if kernel_image.pixeltype != 'float':
kernel_image = kernel_image.clone('float')
if crop:
kernel_image_mask = utils.get_mask(kernel_image)
kernel_image = utils.crop_image(kernel_image, kernel_image_mask)
kernel_image_mask = utils.crop_image(kernel_image_mask, kernel_image_mask)
kernel_image[kernel_image_mask==0] = kernel_image[kernel_image_mask==1].mean()
libfn = utils.get_lib_fn('convolveImageF%i' % image.dimension)
conv_itk_image = libfn(image.pointer, kernel_image.pointer)
conv_ants_image = iio.ANTsImage(pixeltype=image.pixeltype, dimension=image.dimension,
components=image.components, pointer=conv_itk_image)
if orig_ptype != 'float':
conv_ants_image = conv_ants_image.clone(orig_ptype)
return conv_ants_image | [
"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",
"!=",
"'float'",
":",
"image",
"=",
"image",
".",
"clone",
"(",
"'float'",
")",
"if",
"kernel_image",
".",
"pixeltype",
"!=",
"'float'",
":",
"kernel_image",
"=",
"kernel_image",
".",
"clone",
"(",
"'float'",
")",
"if",
"crop",
":",
"kernel_image_mask",
"=",
"utils",
".",
"get_mask",
"(",
"kernel_image",
")",
"kernel_image",
"=",
"utils",
".",
"crop_image",
"(",
"kernel_image",
",",
"kernel_image_mask",
")",
"kernel_image_mask",
"=",
"utils",
".",
"crop_image",
"(",
"kernel_image_mask",
",",
"kernel_image_mask",
")",
"kernel_image",
"[",
"kernel_image_mask",
"==",
"0",
"]",
"=",
"kernel_image",
"[",
"kernel_image_mask",
"==",
"1",
"]",
".",
"mean",
"(",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'convolveImageF%i'",
"%",
"image",
".",
"dimension",
")",
"conv_itk_image",
"=",
"libfn",
"(",
"image",
".",
"pointer",
",",
"kernel_image",
".",
"pointer",
")",
"conv_ants_image",
"=",
"iio",
".",
"ANTsImage",
"(",
"pixeltype",
"=",
"image",
".",
"pixeltype",
",",
"dimension",
"=",
"image",
".",
"dimension",
",",
"components",
"=",
"image",
".",
"components",
",",
"pointer",
"=",
"conv_itk_image",
")",
"if",
"orig_ptype",
"!=",
"'float'",
":",
"conv_ants_image",
"=",
"conv_ants_image",
".",
"clone",
"(",
"orig_ptype",
")",
"return",
"conv_ants_image"
] | Convolve one image with another
ANTsR function: `convolveImage`
Arguments
---------
image : ANTsImage
image to convolve
kernel_image : ANTsImage
image acting as kernel
crop : boolean
whether to automatically crop kernel_image
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> convimg = ants.make_image( (3,3), (1,0,1,0,-4,0,1,0,1) )
>>> convout = ants.convolve_image( fi, convimg )
>>> convimg2 = ants.make_image( (3,3), (0,1,0,1,0,-1,0,-1,0) )
>>> convout2 = ants.convolve_image( fi, convimg2 ) | [
"Convolve",
"one",
"image",
"with",
"another"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/invariant_image_similarity.py#L200-L255 | train | 232,040 |
ANTsX/ANTsPy | ants/utils/ndimage_to_list.py | ndimage_to_list | def ndimage_to_list(image):
"""
Split a n dimensional ANTsImage into a list
of n-1 dimensional ANTsImages
Arguments
---------
image : ANTsImage
n-dimensional image to split
Returns
-------
list of ANTsImage types
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> image2 = ants.image_read(ants.get_ants_data('r16'))
>>> imageTar = ants.make_image( ( *image2.shape, 2 ) )
>>> image3 = ants.list_to_ndimage( imageTar, [image,image2])
>>> image3.dimension == 3
>>> images_unmerged = ants.ndimage_to_list( image3 )
>>> len(images_unmerged) == 2
>>> images_unmerged[0].dimension == 2
"""
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:subdimension]
subdirection = np.eye( subdimension )
for i in range( subdimension ):
subdirection[i,:] = iio.get_direction( image )[i,0:subdimension]
subdim = image.shape[ 0:subdimension ]
imagelist = []
for i in range( nSections ):
img = utils.slice_image( image, axis = subdimension, idx = i )
iio.set_spacing( img, subspacing )
iio.set_origin( img, suborigin )
iio.set_direction( img, subdirection )
imagelist.append( img )
return imagelist | python | def ndimage_to_list(image):
"""
Split a n dimensional ANTsImage into a list
of n-1 dimensional ANTsImages
Arguments
---------
image : ANTsImage
n-dimensional image to split
Returns
-------
list of ANTsImage types
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> image2 = ants.image_read(ants.get_ants_data('r16'))
>>> imageTar = ants.make_image( ( *image2.shape, 2 ) )
>>> image3 = ants.list_to_ndimage( imageTar, [image,image2])
>>> image3.dimension == 3
>>> images_unmerged = ants.ndimage_to_list( image3 )
>>> len(images_unmerged) == 2
>>> images_unmerged[0].dimension == 2
"""
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:subdimension]
subdirection = np.eye( subdimension )
for i in range( subdimension ):
subdirection[i,:] = iio.get_direction( image )[i,0:subdimension]
subdim = image.shape[ 0:subdimension ]
imagelist = []
for i in range( nSections ):
img = utils.slice_image( image, axis = subdimension, idx = i )
iio.set_spacing( img, subspacing )
iio.set_origin( img, suborigin )
iio.set_direction( img, subdirection )
imagelist.append( img )
return imagelist | [
"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",
":",
"subdimension",
"]",
"subdirection",
"=",
"np",
".",
"eye",
"(",
"subdimension",
")",
"for",
"i",
"in",
"range",
"(",
"subdimension",
")",
":",
"subdirection",
"[",
"i",
",",
":",
"]",
"=",
"iio",
".",
"get_direction",
"(",
"image",
")",
"[",
"i",
",",
"0",
":",
"subdimension",
"]",
"subdim",
"=",
"image",
".",
"shape",
"[",
"0",
":",
"subdimension",
"]",
"imagelist",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"nSections",
")",
":",
"img",
"=",
"utils",
".",
"slice_image",
"(",
"image",
",",
"axis",
"=",
"subdimension",
",",
"idx",
"=",
"i",
")",
"iio",
".",
"set_spacing",
"(",
"img",
",",
"subspacing",
")",
"iio",
".",
"set_origin",
"(",
"img",
",",
"suborigin",
")",
"iio",
".",
"set_direction",
"(",
"img",
",",
"subdirection",
")",
"imagelist",
".",
"append",
"(",
"img",
")",
"return",
"imagelist"
] | Split a n dimensional ANTsImage into a list
of n-1 dimensional ANTsImages
Arguments
---------
image : ANTsImage
n-dimensional image to split
Returns
-------
list of ANTsImage types
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> image2 = ants.image_read(ants.get_ants_data('r16'))
>>> imageTar = ants.make_image( ( *image2.shape, 2 ) )
>>> image3 = ants.list_to_ndimage( imageTar, [image,image2])
>>> image3.dimension == 3
>>> images_unmerged = ants.ndimage_to_list( image3 )
>>> len(images_unmerged) == 2
>>> images_unmerged[0].dimension == 2 | [
"Split",
"a",
"n",
"dimensional",
"ANTsImage",
"into",
"a",
"list",
"of",
"n",
"-",
"1",
"dimensional",
"ANTsImages"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/ndimage_to_list.py#L67-L113 | train | 232,041 |
ANTsX/ANTsPy | ants/utils/process_args.py | _int_antsProcessArguments | def _int_antsProcessArguments(args):
"""
Needs to be better validated.
"""
p_args = []
if isinstance(args, dict):
for argname, argval in args.items():
if '-MULTINAME-' in argname:
# have this little hack because python doesnt support
# multiple dict entries w/ the same key like R lists
argname = argname[:argname.find('-MULTINAME-')]
if argval is not None:
if len(argname) > 1:
p_args.append('--%s' % argname)
else:
p_args.append('-%s' % argname)
if isinstance(argval, iio.ANTsImage):
p_args.append(_ptrstr(argval.pointer))
elif isinstance(argval, list):
for av in argval:
if isinstance(av, iio.ANTsImage):
av = _ptrstr(av.pointer)
p_args.append(av)
else:
p_args.append(str(argval))
elif isinstance(args, list):
for arg in args:
if isinstance(arg, iio.ANTsImage):
pointer_string = _ptrstr(arg.pointer)
p_arg = pointer_string
elif arg is None:
pass
else:
p_arg = str(arg)
p_args.append(p_arg)
return p_args | python | def _int_antsProcessArguments(args):
"""
Needs to be better validated.
"""
p_args = []
if isinstance(args, dict):
for argname, argval in args.items():
if '-MULTINAME-' in argname:
# have this little hack because python doesnt support
# multiple dict entries w/ the same key like R lists
argname = argname[:argname.find('-MULTINAME-')]
if argval is not None:
if len(argname) > 1:
p_args.append('--%s' % argname)
else:
p_args.append('-%s' % argname)
if isinstance(argval, iio.ANTsImage):
p_args.append(_ptrstr(argval.pointer))
elif isinstance(argval, list):
for av in argval:
if isinstance(av, iio.ANTsImage):
av = _ptrstr(av.pointer)
p_args.append(av)
else:
p_args.append(str(argval))
elif isinstance(args, list):
for arg in args:
if isinstance(arg, iio.ANTsImage):
pointer_string = _ptrstr(arg.pointer)
p_arg = pointer_string
elif arg is None:
pass
else:
p_arg = str(arg)
p_args.append(p_arg)
return p_args | [
"def",
"_int_antsProcessArguments",
"(",
"args",
")",
":",
"p_args",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"args",
",",
"dict",
")",
":",
"for",
"argname",
",",
"argval",
"in",
"args",
".",
"items",
"(",
")",
":",
"if",
"'-MULTINAME-'",
"in",
"argname",
":",
"# have this little hack because python doesnt support",
"# multiple dict entries w/ the same key like R lists",
"argname",
"=",
"argname",
"[",
":",
"argname",
".",
"find",
"(",
"'-MULTINAME-'",
")",
"]",
"if",
"argval",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"argname",
")",
">",
"1",
":",
"p_args",
".",
"append",
"(",
"'--%s'",
"%",
"argname",
")",
"else",
":",
"p_args",
".",
"append",
"(",
"'-%s'",
"%",
"argname",
")",
"if",
"isinstance",
"(",
"argval",
",",
"iio",
".",
"ANTsImage",
")",
":",
"p_args",
".",
"append",
"(",
"_ptrstr",
"(",
"argval",
".",
"pointer",
")",
")",
"elif",
"isinstance",
"(",
"argval",
",",
"list",
")",
":",
"for",
"av",
"in",
"argval",
":",
"if",
"isinstance",
"(",
"av",
",",
"iio",
".",
"ANTsImage",
")",
":",
"av",
"=",
"_ptrstr",
"(",
"av",
".",
"pointer",
")",
"p_args",
".",
"append",
"(",
"av",
")",
"else",
":",
"p_args",
".",
"append",
"(",
"str",
"(",
"argval",
")",
")",
"elif",
"isinstance",
"(",
"args",
",",
"list",
")",
":",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"iio",
".",
"ANTsImage",
")",
":",
"pointer_string",
"=",
"_ptrstr",
"(",
"arg",
".",
"pointer",
")",
"p_arg",
"=",
"pointer_string",
"elif",
"arg",
"is",
"None",
":",
"pass",
"else",
":",
"p_arg",
"=",
"str",
"(",
"arg",
")",
"p_args",
".",
"append",
"(",
"p_arg",
")",
"return",
"p_args"
] | Needs to be better validated. | [
"Needs",
"to",
"be",
"better",
"validated",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/process_args.py#L34-L71 | train | 232,042 |
ANTsX/ANTsPy | ants/learn/decomposition.py | initialize_eigenanatomy | def initialize_eigenanatomy(initmat, mask=None, initlabels=None, nreps=1, smoothing=0):
"""
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.
Arguments
---------
initmat : np.ndarray or ANTsImage
input matrix where rows provide initial vector values.
alternatively, this can be an antsImage which contains labeled regions.
mask : ANTsImage
mask if available
initlabels : list/tuple of integers
which labels in initmat to use as initial components
nreps : integer
nrepetitions to use
smoothing : float
if using an initial label image, optionally smooth each roi
Returns
-------
dict w/ the following key/value pairs:
`initlist` : list of ANTsImage types
initialization list(s) for sparseDecom(2)
`mask` : ANTsImage
mask(s) for sparseDecom(2)
`enames` : list of strings
string names of components for sparseDecom(2)
Example
-------
>>> import ants
>>> import numpy as np
>>> mat = np.random.randn(4,100).astype('float32')
>>> init = ants.initialize_eigenanatomy(mat)
"""
if isinstance(initmat, iio.ANTsImage):
# create initmat from each of the unique labels
if mask is not None:
selectvec = mask > 0
else:
selectvec = initmat > 0
initmatvec = initmat[selectvec]
if initlabels is None:
ulabs = np.sort(np.unique(initmatvec))
ulabs = ulabs[ulabs > 0]
else:
ulabs = initlabels
nvox = len(initmatvec)
temp = np.zeros((len(ulabs), nvox))
for x in range(len(ulabs)):
timg = utils.threshold_image(initmat, ulabs[x]-1e-4, ulabs[x]+1e-4)
if smoothing > 0:
timg = utils.smooth_image(timg, smoothing)
temp[x,:] = timg[selectvec]
initmat = temp
nclasses = initmat.shape[0]
classlabels = ['init%i'%i for i in range(nclasses)]
initlist = []
if mask is None:
maskmat = np.zeros(initmat.shape)
maskmat[0,:] = 1
mask = core.from_numpy(maskmat.astype('float32'))
eanatnames = ['A'] * (nclasses*nreps)
ct = 0
for i in range(nclasses):
vecimg = mask.clone('float')
initf = initmat[i,:]
vecimg[mask==1] = initf
for nr in range(nreps):
initlist.append(vecimg)
eanatnames[ct+nr-1] = str(classlabels[i])
ct = ct + 1
return {'initlist': initlist, 'mask': mask, 'enames': eanatnames} | python | def initialize_eigenanatomy(initmat, mask=None, initlabels=None, nreps=1, smoothing=0):
"""
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.
Arguments
---------
initmat : np.ndarray or ANTsImage
input matrix where rows provide initial vector values.
alternatively, this can be an antsImage which contains labeled regions.
mask : ANTsImage
mask if available
initlabels : list/tuple of integers
which labels in initmat to use as initial components
nreps : integer
nrepetitions to use
smoothing : float
if using an initial label image, optionally smooth each roi
Returns
-------
dict w/ the following key/value pairs:
`initlist` : list of ANTsImage types
initialization list(s) for sparseDecom(2)
`mask` : ANTsImage
mask(s) for sparseDecom(2)
`enames` : list of strings
string names of components for sparseDecom(2)
Example
-------
>>> import ants
>>> import numpy as np
>>> mat = np.random.randn(4,100).astype('float32')
>>> init = ants.initialize_eigenanatomy(mat)
"""
if isinstance(initmat, iio.ANTsImage):
# create initmat from each of the unique labels
if mask is not None:
selectvec = mask > 0
else:
selectvec = initmat > 0
initmatvec = initmat[selectvec]
if initlabels is None:
ulabs = np.sort(np.unique(initmatvec))
ulabs = ulabs[ulabs > 0]
else:
ulabs = initlabels
nvox = len(initmatvec)
temp = np.zeros((len(ulabs), nvox))
for x in range(len(ulabs)):
timg = utils.threshold_image(initmat, ulabs[x]-1e-4, ulabs[x]+1e-4)
if smoothing > 0:
timg = utils.smooth_image(timg, smoothing)
temp[x,:] = timg[selectvec]
initmat = temp
nclasses = initmat.shape[0]
classlabels = ['init%i'%i for i in range(nclasses)]
initlist = []
if mask is None:
maskmat = np.zeros(initmat.shape)
maskmat[0,:] = 1
mask = core.from_numpy(maskmat.astype('float32'))
eanatnames = ['A'] * (nclasses*nreps)
ct = 0
for i in range(nclasses):
vecimg = mask.clone('float')
initf = initmat[i,:]
vecimg[mask==1] = initf
for nr in range(nreps):
initlist.append(vecimg)
eanatnames[ct+nr-1] = str(classlabels[i])
ct = ct + 1
return {'initlist': initlist, 'mask': mask, 'enames': eanatnames} | [
"def",
"initialize_eigenanatomy",
"(",
"initmat",
",",
"mask",
"=",
"None",
",",
"initlabels",
"=",
"None",
",",
"nreps",
"=",
"1",
",",
"smoothing",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"initmat",
",",
"iio",
".",
"ANTsImage",
")",
":",
"# create initmat from each of the unique labels",
"if",
"mask",
"is",
"not",
"None",
":",
"selectvec",
"=",
"mask",
">",
"0",
"else",
":",
"selectvec",
"=",
"initmat",
">",
"0",
"initmatvec",
"=",
"initmat",
"[",
"selectvec",
"]",
"if",
"initlabels",
"is",
"None",
":",
"ulabs",
"=",
"np",
".",
"sort",
"(",
"np",
".",
"unique",
"(",
"initmatvec",
")",
")",
"ulabs",
"=",
"ulabs",
"[",
"ulabs",
">",
"0",
"]",
"else",
":",
"ulabs",
"=",
"initlabels",
"nvox",
"=",
"len",
"(",
"initmatvec",
")",
"temp",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"ulabs",
")",
",",
"nvox",
")",
")",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"ulabs",
")",
")",
":",
"timg",
"=",
"utils",
".",
"threshold_image",
"(",
"initmat",
",",
"ulabs",
"[",
"x",
"]",
"-",
"1e-4",
",",
"ulabs",
"[",
"x",
"]",
"+",
"1e-4",
")",
"if",
"smoothing",
">",
"0",
":",
"timg",
"=",
"utils",
".",
"smooth_image",
"(",
"timg",
",",
"smoothing",
")",
"temp",
"[",
"x",
",",
":",
"]",
"=",
"timg",
"[",
"selectvec",
"]",
"initmat",
"=",
"temp",
"nclasses",
"=",
"initmat",
".",
"shape",
"[",
"0",
"]",
"classlabels",
"=",
"[",
"'init%i'",
"%",
"i",
"for",
"i",
"in",
"range",
"(",
"nclasses",
")",
"]",
"initlist",
"=",
"[",
"]",
"if",
"mask",
"is",
"None",
":",
"maskmat",
"=",
"np",
".",
"zeros",
"(",
"initmat",
".",
"shape",
")",
"maskmat",
"[",
"0",
",",
":",
"]",
"=",
"1",
"mask",
"=",
"core",
".",
"from_numpy",
"(",
"maskmat",
".",
"astype",
"(",
"'float32'",
")",
")",
"eanatnames",
"=",
"[",
"'A'",
"]",
"*",
"(",
"nclasses",
"*",
"nreps",
")",
"ct",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"nclasses",
")",
":",
"vecimg",
"=",
"mask",
".",
"clone",
"(",
"'float'",
")",
"initf",
"=",
"initmat",
"[",
"i",
",",
":",
"]",
"vecimg",
"[",
"mask",
"==",
"1",
"]",
"=",
"initf",
"for",
"nr",
"in",
"range",
"(",
"nreps",
")",
":",
"initlist",
".",
"append",
"(",
"vecimg",
")",
"eanatnames",
"[",
"ct",
"+",
"nr",
"-",
"1",
"]",
"=",
"str",
"(",
"classlabels",
"[",
"i",
"]",
")",
"ct",
"=",
"ct",
"+",
"1",
"return",
"{",
"'initlist'",
":",
"initlist",
",",
"'mask'",
":",
"mask",
",",
"'enames'",
":",
"eanatnames",
"}"
] | 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.
Arguments
---------
initmat : np.ndarray or ANTsImage
input matrix where rows provide initial vector values.
alternatively, this can be an antsImage which contains labeled regions.
mask : ANTsImage
mask if available
initlabels : list/tuple of integers
which labels in initmat to use as initial components
nreps : integer
nrepetitions to use
smoothing : float
if using an initial label image, optionally smooth each roi
Returns
-------
dict w/ the following key/value pairs:
`initlist` : list of ANTsImage types
initialization list(s) for sparseDecom(2)
`mask` : ANTsImage
mask(s) for sparseDecom(2)
`enames` : list of strings
string names of components for sparseDecom(2)
Example
-------
>>> import ants
>>> import numpy as np
>>> mat = np.random.randn(4,100).astype('float32')
>>> init = ants.initialize_eigenanatomy(mat) | [
"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",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/learn/decomposition.py#L251-L338 | train | 232,043 |
ANTsX/ANTsPy | ants/learn/decomposition.py | eig_seg | def eig_seg(mask, img_list, apply_segmentation_to_images=False, cthresh=0, smooth=1):
"""
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.
Arguments
---------
mask : ANTsImage
D-dimensional mask > 0 defining segmentation region.
img_list : collection of ANTsImage or np.ndarray
images to use
apply_segmentation_to_images : boolean
determines if original image list is modified by the segmentation.
cthresh : integer
throw away isolated clusters smaller than this value
smooth : float
smooth the input data first by this value
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mylist = [ants.image_read(ants.get_ants_data('r16')),
ants.image_read(ants.get_ants_data('r27')),
ants.image_read(ants.get_ants_data('r85'))]
>>> myseg = ants.eig_seg(ants.get_mask(mylist[0]), mylist)
"""
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(img_list, mask)
if (smooth > 0):
for i in range(mydata.shape[0]):
temp_img = core.make_image(mask, mydata[i,:], pixeltype='float')
temp_img = utils.smooth_image(temp_img, smooth, sigma_in_physical_coordinates=True)
mydata[i,:] = temp_img[mask >= 0.5]
segids = np.argmax(np.abs(mydata), axis=0)+1
segmax = np.max(np.abs(mydata), axis=0)
maskseg[maskvox] = (segids * (segmax > 1e-09))
if cthresh > 0:
for kk in range(int(maskseg.max())):
timg = utils.threshold_image(maskseg, kk, kk)
timg = utils.label_clusters(timg, cthresh)
timg = utils.threshold_image(timg, 1, 1e15) * float(kk)
maskseg[maskseg == kk] = timg[maskseg == kk]
if (apply_segmentation_to_images) and (not isinstance(img_list, np.ndarray)):
for i in range(len(img_list)):
img = img_list[i]
img[maskseg != float(i)] = 0
img_list[i] = img
return maskseg | python | def eig_seg(mask, img_list, apply_segmentation_to_images=False, cthresh=0, smooth=1):
"""
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.
Arguments
---------
mask : ANTsImage
D-dimensional mask > 0 defining segmentation region.
img_list : collection of ANTsImage or np.ndarray
images to use
apply_segmentation_to_images : boolean
determines if original image list is modified by the segmentation.
cthresh : integer
throw away isolated clusters smaller than this value
smooth : float
smooth the input data first by this value
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mylist = [ants.image_read(ants.get_ants_data('r16')),
ants.image_read(ants.get_ants_data('r27')),
ants.image_read(ants.get_ants_data('r85'))]
>>> myseg = ants.eig_seg(ants.get_mask(mylist[0]), mylist)
"""
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(img_list, mask)
if (smooth > 0):
for i in range(mydata.shape[0]):
temp_img = core.make_image(mask, mydata[i,:], pixeltype='float')
temp_img = utils.smooth_image(temp_img, smooth, sigma_in_physical_coordinates=True)
mydata[i,:] = temp_img[mask >= 0.5]
segids = np.argmax(np.abs(mydata), axis=0)+1
segmax = np.max(np.abs(mydata), axis=0)
maskseg[maskvox] = (segids * (segmax > 1e-09))
if cthresh > 0:
for kk in range(int(maskseg.max())):
timg = utils.threshold_image(maskseg, kk, kk)
timg = utils.label_clusters(timg, cthresh)
timg = utils.threshold_image(timg, 1, 1e15) * float(kk)
maskseg[maskseg == kk] = timg[maskseg == kk]
if (apply_segmentation_to_images) and (not isinstance(img_list, np.ndarray)):
for i in range(len(img_list)):
img = img_list[i]
img[maskseg != float(i)] = 0
img_list[i] = img
return maskseg | [
"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",
"(",
"img_list",
",",
"mask",
")",
"if",
"(",
"smooth",
">",
"0",
")",
":",
"for",
"i",
"in",
"range",
"(",
"mydata",
".",
"shape",
"[",
"0",
"]",
")",
":",
"temp_img",
"=",
"core",
".",
"make_image",
"(",
"mask",
",",
"mydata",
"[",
"i",
",",
":",
"]",
",",
"pixeltype",
"=",
"'float'",
")",
"temp_img",
"=",
"utils",
".",
"smooth_image",
"(",
"temp_img",
",",
"smooth",
",",
"sigma_in_physical_coordinates",
"=",
"True",
")",
"mydata",
"[",
"i",
",",
":",
"]",
"=",
"temp_img",
"[",
"mask",
">=",
"0.5",
"]",
"segids",
"=",
"np",
".",
"argmax",
"(",
"np",
".",
"abs",
"(",
"mydata",
")",
",",
"axis",
"=",
"0",
")",
"+",
"1",
"segmax",
"=",
"np",
".",
"max",
"(",
"np",
".",
"abs",
"(",
"mydata",
")",
",",
"axis",
"=",
"0",
")",
"maskseg",
"[",
"maskvox",
"]",
"=",
"(",
"segids",
"*",
"(",
"segmax",
">",
"1e-09",
")",
")",
"if",
"cthresh",
">",
"0",
":",
"for",
"kk",
"in",
"range",
"(",
"int",
"(",
"maskseg",
".",
"max",
"(",
")",
")",
")",
":",
"timg",
"=",
"utils",
".",
"threshold_image",
"(",
"maskseg",
",",
"kk",
",",
"kk",
")",
"timg",
"=",
"utils",
".",
"label_clusters",
"(",
"timg",
",",
"cthresh",
")",
"timg",
"=",
"utils",
".",
"threshold_image",
"(",
"timg",
",",
"1",
",",
"1e15",
")",
"*",
"float",
"(",
"kk",
")",
"maskseg",
"[",
"maskseg",
"==",
"kk",
"]",
"=",
"timg",
"[",
"maskseg",
"==",
"kk",
"]",
"if",
"(",
"apply_segmentation_to_images",
")",
"and",
"(",
"not",
"isinstance",
"(",
"img_list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"img_list",
")",
")",
":",
"img",
"=",
"img_list",
"[",
"i",
"]",
"img",
"[",
"maskseg",
"!=",
"float",
"(",
"i",
")",
"]",
"=",
"0",
"img_list",
"[",
"i",
"]",
"=",
"img",
"return",
"maskseg"
] | 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.
Arguments
---------
mask : ANTsImage
D-dimensional mask > 0 defining segmentation region.
img_list : collection of ANTsImage or np.ndarray
images to use
apply_segmentation_to_images : boolean
determines if original image list is modified by the segmentation.
cthresh : integer
throw away isolated clusters smaller than this value
smooth : float
smooth the input data first by this value
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mylist = [ants.image_read(ants.get_ants_data('r16')),
ants.image_read(ants.get_ants_data('r27')),
ants.image_read(ants.get_ants_data('r85'))]
>>> myseg = ants.eig_seg(ants.get_mask(mylist[0]), mylist) | [
"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",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/learn/decomposition.py#L342-L409 | train | 232,044 |
ANTsX/ANTsPy | ants/utils/label_stats.py | label_stats | def label_stats(image, label_image):
"""
Get label statistics from image
ANTsR function: `labelStats`
Arguments
---------
image : ANTsImage
Image from which statistics will be calculated
label_image : ANTsImage
Label image
Returns
-------
ndarray ?
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') , 2 )
>>> image = ants.resample_image( image, (64,64), 1, 0 )
>>> mask = ants.get_mask(image)
>>> segs1 = ants.kmeans_segmentation( image, 3 )
>>> stats = ants.label_stats(image, segs1['segmentation'])
"""
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)
#df = df[order(df$LabelValue), ]
return pd.DataFrame(df) | python | def label_stats(image, label_image):
"""
Get label statistics from image
ANTsR function: `labelStats`
Arguments
---------
image : ANTsImage
Image from which statistics will be calculated
label_image : ANTsImage
Label image
Returns
-------
ndarray ?
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') , 2 )
>>> image = ants.resample_image( image, (64,64), 1, 0 )
>>> mask = ants.get_mask(image)
>>> segs1 = ants.kmeans_segmentation( image, 3 )
>>> stats = ants.label_stats(image, segs1['segmentation'])
"""
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)
#df = df[order(df$LabelValue), ]
return pd.DataFrame(df) | [
"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",
")",
"#df = df[order(df$LabelValue), ]",
"return",
"pd",
".",
"DataFrame",
"(",
"df",
")"
] | Get label statistics from image
ANTsR function: `labelStats`
Arguments
---------
image : ANTsImage
Image from which statistics will be calculated
label_image : ANTsImage
Label image
Returns
-------
ndarray ?
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') , 2 )
>>> image = ants.resample_image( image, (64,64), 1, 0 )
>>> mask = ants.get_mask(image)
>>> segs1 = ants.kmeans_segmentation( image, 3 )
>>> stats = ants.label_stats(image, segs1['segmentation']) | [
"Get",
"label",
"statistics",
"from",
"image"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/label_stats.py#L8-L41 | train | 232,045 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.spacing | def spacing(self):
"""
Get image spacing
Returns
-------
tuple
"""
libfn = utils.get_lib_fn('getSpacing%s'%self._libsuffix)
return libfn(self.pointer) | python | def spacing(self):
"""
Get image spacing
Returns
-------
tuple
"""
libfn = utils.get_lib_fn('getSpacing%s'%self._libsuffix)
return libfn(self.pointer) | [
"def",
"spacing",
"(",
"self",
")",
":",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'getSpacing%s'",
"%",
"self",
".",
"_libsuffix",
")",
"return",
"libfn",
"(",
"self",
".",
"pointer",
")"
] | Get image spacing
Returns
-------
tuple | [
"Get",
"image",
"spacing"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L95-L104 | train | 232,046 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.set_spacing | def set_spacing(self, new_spacing):
"""
Set image spacing
Arguments
---------
new_spacing : tuple or list
updated spacing for the image.
should have one value for each dimension
Returns
-------
None
"""
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('setSpacing%s'%self._libsuffix)
libfn(self.pointer, new_spacing) | python | def set_spacing(self, new_spacing):
"""
Set image spacing
Arguments
---------
new_spacing : tuple or list
updated spacing for the image.
should have one value for each dimension
Returns
-------
None
"""
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('setSpacing%s'%self._libsuffix)
libfn(self.pointer, new_spacing) | [
"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",
"(",
"'setSpacing%s'",
"%",
"self",
".",
"_libsuffix",
")",
"libfn",
"(",
"self",
".",
"pointer",
",",
"new_spacing",
")"
] | Set image spacing
Arguments
---------
new_spacing : tuple or list
updated spacing for the image.
should have one value for each dimension
Returns
-------
None | [
"Set",
"image",
"spacing"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L106-L126 | train | 232,047 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.origin | def origin(self):
"""
Get image origin
Returns
-------
tuple
"""
libfn = utils.get_lib_fn('getOrigin%s'%self._libsuffix)
return libfn(self.pointer) | python | def origin(self):
"""
Get image origin
Returns
-------
tuple
"""
libfn = utils.get_lib_fn('getOrigin%s'%self._libsuffix)
return libfn(self.pointer) | [
"def",
"origin",
"(",
"self",
")",
":",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'getOrigin%s'",
"%",
"self",
".",
"_libsuffix",
")",
"return",
"libfn",
"(",
"self",
".",
"pointer",
")"
] | Get image origin
Returns
-------
tuple | [
"Get",
"image",
"origin"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L129-L138 | train | 232,048 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.set_origin | def set_origin(self, new_origin):
"""
Set image origin
Arguments
---------
new_origin : tuple or list
updated origin for the image.
should have one value for each dimension
Returns
-------
None
"""
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'%self._libsuffix)
libfn(self.pointer, new_origin) | python | def set_origin(self, new_origin):
"""
Set image origin
Arguments
---------
new_origin : tuple or list
updated origin for the image.
should have one value for each dimension
Returns
-------
None
"""
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'%self._libsuffix)
libfn(self.pointer, new_origin) | [
"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'",
"%",
"self",
".",
"_libsuffix",
")",
"libfn",
"(",
"self",
".",
"pointer",
",",
"new_origin",
")"
] | Set image origin
Arguments
---------
new_origin : tuple or list
updated origin for the image.
should have one value for each dimension
Returns
-------
None | [
"Set",
"image",
"origin"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L140-L160 | train | 232,049 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.direction | def direction(self):
"""
Get image direction
Returns
-------
tuple
"""
libfn = utils.get_lib_fn('getDirection%s'%self._libsuffix)
return libfn(self.pointer) | python | def direction(self):
"""
Get image direction
Returns
-------
tuple
"""
libfn = utils.get_lib_fn('getDirection%s'%self._libsuffix)
return libfn(self.pointer) | [
"def",
"direction",
"(",
"self",
")",
":",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'getDirection%s'",
"%",
"self",
".",
"_libsuffix",
")",
"return",
"libfn",
"(",
"self",
".",
"pointer",
")"
] | Get image direction
Returns
-------
tuple | [
"Get",
"image",
"direction"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L163-L172 | train | 232,050 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.set_direction | def set_direction(self, new_direction):
"""
Set image direction
Arguments
---------
new_direction : numpy.ndarray or tuple or list
updated direction for the image.
should have one value for each dimension
Returns
-------
None
"""
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 ValueError('must give a origin value for each dimension (%i)' % self.dimension)
libfn = utils.get_lib_fn('setDirection%s'%self._libsuffix)
libfn(self.pointer, new_direction) | python | def set_direction(self, new_direction):
"""
Set image direction
Arguments
---------
new_direction : numpy.ndarray or tuple or list
updated direction for the image.
should have one value for each dimension
Returns
-------
None
"""
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 ValueError('must give a origin value for each dimension (%i)' % self.dimension)
libfn = utils.get_lib_fn('setDirection%s'%self._libsuffix)
libfn(self.pointer, new_direction) | [
"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",
"ValueError",
"(",
"'must give a origin value for each dimension (%i)'",
"%",
"self",
".",
"dimension",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'setDirection%s'",
"%",
"self",
".",
"_libsuffix",
")",
"libfn",
"(",
"self",
".",
"pointer",
",",
"new_direction",
")"
] | Set image direction
Arguments
---------
new_direction : numpy.ndarray or tuple or list
updated direction for the image.
should have one value for each dimension
Returns
-------
None | [
"Set",
"image",
"direction"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L174-L197 | train | 232,051 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.astype | def astype(self, dtype):
"""
Cast & clone an ANTsImage to a given numpy datatype.
Map:
uint8 : unsigned char
uint32 : unsigned int
float32 : float
float64 : double
"""
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) | python | def astype(self, dtype):
"""
Cast & clone an ANTsImage to a given numpy datatype.
Map:
uint8 : unsigned char
uint32 : unsigned int
float32 : float
float64 : double
"""
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) | [
"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.
Map:
uint8 : unsigned char
uint32 : unsigned int
float32 : float
float64 : double | [
"Cast",
"&",
"clone",
"an",
"ANTsImage",
"to",
"a",
"given",
"numpy",
"datatype",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L302-L316 | train | 232,052 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.new_image_like | def new_image_like(self, data):
"""
Create a new ANTsImage with the same header information, but with
a new image array.
Arguments
---------
data : ndarray or py::capsule
New array or pointer for the image.
It must have the same shape as the current
image data.
Returns
-------
ANTsImage
"""
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:
if (data.shape[-1] != self.components) or (data.shape[:-1] != self.shape):
raise ValueError('given array shape (%s) and image array shape (%s) do not match' % (data.shape[1:], self.shape))
return iio2.from_numpy(data, origin=self.origin,
spacing=self.spacing, direction=self.direction,
has_components=self.has_components) | python | def new_image_like(self, data):
"""
Create a new ANTsImage with the same header information, but with
a new image array.
Arguments
---------
data : ndarray or py::capsule
New array or pointer for the image.
It must have the same shape as the current
image data.
Returns
-------
ANTsImage
"""
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:
if (data.shape[-1] != self.components) or (data.shape[:-1] != self.shape):
raise ValueError('given array shape (%s) and image array shape (%s) do not match' % (data.shape[1:], self.shape))
return iio2.from_numpy(data, origin=self.origin,
spacing=self.spacing, direction=self.direction,
has_components=self.has_components) | [
"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",
":",
"if",
"(",
"data",
".",
"shape",
"[",
"-",
"1",
"]",
"!=",
"self",
".",
"components",
")",
"or",
"(",
"data",
".",
"shape",
"[",
":",
"-",
"1",
"]",
"!=",
"self",
".",
"shape",
")",
":",
"raise",
"ValueError",
"(",
"'given array shape (%s) and image array shape (%s) do not match'",
"%",
"(",
"data",
".",
"shape",
"[",
"1",
":",
"]",
",",
"self",
".",
"shape",
")",
")",
"return",
"iio2",
".",
"from_numpy",
"(",
"data",
",",
"origin",
"=",
"self",
".",
"origin",
",",
"spacing",
"=",
"self",
".",
"spacing",
",",
"direction",
"=",
"self",
".",
"direction",
",",
"has_components",
"=",
"self",
".",
"has_components",
")"
] | Create a new ANTsImage with the same header information, but with
a new image array.
Arguments
---------
data : ndarray or py::capsule
New array or pointer for the image.
It must have the same shape as the current
image data.
Returns
-------
ANTsImage | [
"Create",
"a",
"new",
"ANTsImage",
"with",
"the",
"same",
"header",
"information",
"but",
"with",
"a",
"new",
"image",
"array",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L318-L345 | train | 232,053 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.to_file | def to_file(self, filename):
"""
Write the ANTsImage to file
Args
----
filename : string
filepath to which the image will be written
"""
filename = os.path.expanduser(filename)
libfn = utils.get_lib_fn('toFile%s'%self._libsuffix)
libfn(self.pointer, filename) | python | def to_file(self, filename):
"""
Write the ANTsImage to file
Args
----
filename : string
filepath to which the image will be written
"""
filename = os.path.expanduser(filename)
libfn = utils.get_lib_fn('toFile%s'%self._libsuffix)
libfn(self.pointer, filename) | [
"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
Args
----
filename : string
filepath to which the image will be written | [
"Write",
"the",
"ANTsImage",
"to",
"file"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L347-L358 | train | 232,054 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.apply | def apply(self, fn):
"""
Apply an arbitrary function to ANTsImage.
Args
----
fn : python function or lambda
function to apply to ENTIRE image at once
Returns
-------
ANTsImage
image with function applied to it
"""
this_array = self.numpy()
new_array = fn(this_array)
return self.new_image_like(new_array) | python | def apply(self, fn):
"""
Apply an arbitrary function to ANTsImage.
Args
----
fn : python function or lambda
function to apply to ENTIRE image at once
Returns
-------
ANTsImage
image with function applied to it
"""
this_array = self.numpy()
new_array = fn(this_array)
return self.new_image_like(new_array) | [
"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.
Args
----
fn : python function or lambda
function to apply to ENTIRE image at once
Returns
-------
ANTsImage
image with function applied to it | [
"Apply",
"an",
"arbitrary",
"function",
"to",
"ANTsImage",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L361-L377 | train | 232,055 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.sum | def sum(self, axis=None, keepdims=False):
""" Return sum along specified axis """
return self.numpy().sum(axis=axis, keepdims=keepdims) | python | def sum(self, axis=None, keepdims=False):
""" Return sum along specified axis """
return self.numpy().sum(axis=axis, keepdims=keepdims) | [
"def",
"sum",
"(",
"self",
",",
"axis",
"=",
"None",
",",
"keepdims",
"=",
"False",
")",
":",
"return",
"self",
".",
"numpy",
"(",
")",
".",
"sum",
"(",
"axis",
"=",
"axis",
",",
"keepdims",
"=",
"keepdims",
")"
] | Return sum along specified axis | [
"Return",
"sum",
"along",
"specified",
"axis"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L395-L397 | train | 232,056 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.range | def range(self, axis=None):
""" Return range tuple along specified axis """
return (self.min(axis=axis), self.max(axis=axis)) | python | def range(self, axis=None):
""" Return range tuple along specified axis """
return (self.min(axis=axis), self.max(axis=axis)) | [
"def",
"range",
"(",
"self",
",",
"axis",
"=",
"None",
")",
":",
"return",
"(",
"self",
".",
"min",
"(",
"axis",
"=",
"axis",
")",
",",
"self",
".",
"max",
"(",
"axis",
"=",
"axis",
")",
")"
] | Return range tuple along specified axis | [
"Return",
"range",
"tuple",
"along",
"specified",
"axis"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L404-L406 | train | 232,057 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.argrange | def argrange(self, axis=None):
""" Return argrange along specified axis """
amin = self.argmin(axis=axis)
amax = self.argmax(axis=axis)
if axis is None:
return (amin, amax)
else:
return np.stack([amin, amax]).T | python | def argrange(self, axis=None):
""" Return argrange along specified axis """
amin = self.argmin(axis=axis)
amax = self.argmax(axis=axis)
if axis is None:
return (amin, amax)
else:
return np.stack([amin, amax]).T | [
"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 | [
"Return",
"argrange",
"along",
"specified",
"axis"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L413-L420 | train | 232,058 |
ANTsX/ANTsPy | ants/core/ants_image.py | ANTsImage.unique | def unique(self, sort=False):
""" Return unique set of values in image """
unique_vals = np.unique(self.numpy())
if sort:
unique_vals = np.sort(unique_vals)
return unique_vals | python | def unique(self, sort=False):
""" Return unique set of values in image """
unique_vals = np.unique(self.numpy())
if sort:
unique_vals = np.sort(unique_vals)
return unique_vals | [
"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 | [
"Return",
"unique",
"set",
"of",
"values",
"in",
"image"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L427-L432 | train | 232,059 |
ANTsX/ANTsPy | ants/core/ants_image.py | LabelImage.uniquekeys | def uniquekeys(self, metakey=None):
"""
Get keys for a given metakey
"""
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] | python | def uniquekeys(self, metakey=None):
"""
Get keys for a given metakey
"""
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] | [
"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 | [
"Get",
"keys",
"for",
"a",
"given",
"metakey"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L731-L740 | train | 232,060 |
ANTsX/ANTsPy | ants/utils/label_clusters.py | label_clusters | def label_clusters(image, min_cluster_size=50, min_thresh=1e-6, max_thresh=1, fully_connected=False):
"""
This will give a unique ID to each connected
component 1 through N of size > min_cluster_size
ANTsR function: `labelClusters`
Arguments
---------
image : ANTsImage
input image e.g. a statistical map
min_cluster_size : integer
throw away clusters smaller than this value
min_thresh : scalar
threshold to a statistical map
max_thresh : scalar
threshold to a statistical map
fully_connected : boolean
boolean sets neighborhood connectivity pattern
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> timageFully = ants.label_clusters( image, 10, 128, 150, True )
>>> timageFace = ants.label_clusters( image, 10, 128, 150, 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_antsProcessArguments(args)
libfn = utils.get_lib_fn('LabelClustersUniquely')
libfn(processed_args)
return clust | python | def label_clusters(image, min_cluster_size=50, min_thresh=1e-6, max_thresh=1, fully_connected=False):
"""
This will give a unique ID to each connected
component 1 through N of size > min_cluster_size
ANTsR function: `labelClusters`
Arguments
---------
image : ANTsImage
input image e.g. a statistical map
min_cluster_size : integer
throw away clusters smaller than this value
min_thresh : scalar
threshold to a statistical map
max_thresh : scalar
threshold to a statistical map
fully_connected : boolean
boolean sets neighborhood connectivity pattern
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> timageFully = ants.label_clusters( image, 10, 128, 150, True )
>>> timageFace = ants.label_clusters( image, 10, 128, 150, 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_antsProcessArguments(args)
libfn = utils.get_lib_fn('LabelClustersUniquely')
libfn(processed_args)
return clust | [
"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_antsProcessArguments",
"(",
"args",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'LabelClustersUniquely'",
")",
"libfn",
"(",
"processed_args",
")",
"return",
"clust"
] | This will give a unique ID to each connected
component 1 through N of size > min_cluster_size
ANTsR function: `labelClusters`
Arguments
---------
image : ANTsImage
input image e.g. a statistical map
min_cluster_size : integer
throw away clusters smaller than this value
min_thresh : scalar
threshold to a statistical map
max_thresh : scalar
threshold to a statistical map
fully_connected : boolean
boolean sets neighborhood connectivity pattern
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read( ants.get_ants_data('r16') )
>>> timageFully = ants.label_clusters( image, 10, 128, 150, True )
>>> timageFace = ants.label_clusters( image, 10, 128, 150, False ) | [
"This",
"will",
"give",
"a",
"unique",
"ID",
"to",
"each",
"connected",
"component",
"1",
"through",
"N",
"of",
"size",
">",
"min_cluster_size"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/label_clusters.py#L11-L53 | train | 232,061 |
ANTsX/ANTsPy | ants/registration/make_points_image.py | make_points_image | def make_points_image(pts, mask, radius=5):
"""
Create label image from physical space points
Creates spherical points in the coordinate space of the target image based
on the n-dimensional matrix of points that the user supplies. The image
defines the dimensionality of the data so if the input image is 3D then
the input points should be 2D or 3D.
ANTsR function: `makePointsImage`
Arguments
---------
pts : numpy.ndarray
input powers points
mask : ANTsImage
mask defining target space
radius : integer
radius for the points
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> import pandas as pd
>>> mni = ants.image_read(ants.get_data('mni')).get_mask()
>>> powers_pts = pd.read_csv(ants.get_data('powers_mni_itk'))
>>> powers_labels = ants.make_points_image(powers_pts.iloc[:,:3].values, mni, radius=3)
"""
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, pt.tolist() ).astype(int)
in_image = (np.prod(idx <= mask.shape)==1) and (len(np.where(idx<0)[0])==0)
if ( in_image == True ):
if (dim == 3):
powers_lblimg[idx[0],idx[1],idx[2]] = r + 1
elif (dim == 2):
powers_lblimg[idx[0],idx[1]] = r + 1
return utils.morphology( powers_lblimg, 'dilate', radius, 'grayscale' ) | python | def make_points_image(pts, mask, radius=5):
"""
Create label image from physical space points
Creates spherical points in the coordinate space of the target image based
on the n-dimensional matrix of points that the user supplies. The image
defines the dimensionality of the data so if the input image is 3D then
the input points should be 2D or 3D.
ANTsR function: `makePointsImage`
Arguments
---------
pts : numpy.ndarray
input powers points
mask : ANTsImage
mask defining target space
radius : integer
radius for the points
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> import pandas as pd
>>> mni = ants.image_read(ants.get_data('mni')).get_mask()
>>> powers_pts = pd.read_csv(ants.get_data('powers_mni_itk'))
>>> powers_labels = ants.make_points_image(powers_pts.iloc[:,:3].values, mni, radius=3)
"""
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, pt.tolist() ).astype(int)
in_image = (np.prod(idx <= mask.shape)==1) and (len(np.where(idx<0)[0])==0)
if ( in_image == True ):
if (dim == 3):
powers_lblimg[idx[0],idx[1],idx[2]] = r + 1
elif (dim == 2):
powers_lblimg[idx[0],idx[1]] = r + 1
return utils.morphology( powers_lblimg, 'dilate', radius, 'grayscale' ) | [
"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",
",",
"pt",
".",
"tolist",
"(",
")",
")",
".",
"astype",
"(",
"int",
")",
"in_image",
"=",
"(",
"np",
".",
"prod",
"(",
"idx",
"<=",
"mask",
".",
"shape",
")",
"==",
"1",
")",
"and",
"(",
"len",
"(",
"np",
".",
"where",
"(",
"idx",
"<",
"0",
")",
"[",
"0",
"]",
")",
"==",
"0",
")",
"if",
"(",
"in_image",
"==",
"True",
")",
":",
"if",
"(",
"dim",
"==",
"3",
")",
":",
"powers_lblimg",
"[",
"idx",
"[",
"0",
"]",
",",
"idx",
"[",
"1",
"]",
",",
"idx",
"[",
"2",
"]",
"]",
"=",
"r",
"+",
"1",
"elif",
"(",
"dim",
"==",
"2",
")",
":",
"powers_lblimg",
"[",
"idx",
"[",
"0",
"]",
",",
"idx",
"[",
"1",
"]",
"]",
"=",
"r",
"+",
"1",
"return",
"utils",
".",
"morphology",
"(",
"powers_lblimg",
",",
"'dilate'",
",",
"radius",
",",
"'grayscale'",
")"
] | Create label image from physical space points
Creates spherical points in the coordinate space of the target image based
on the n-dimensional matrix of points that the user supplies. The image
defines the dimensionality of the data so if the input image is 3D then
the input points should be 2D or 3D.
ANTsR function: `makePointsImage`
Arguments
---------
pts : numpy.ndarray
input powers points
mask : ANTsImage
mask defining target space
radius : integer
radius for the points
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> import pandas as pd
>>> mni = ants.image_read(ants.get_data('mni')).get_mask()
>>> powers_pts = pd.read_csv(ants.get_data('powers_mni_itk'))
>>> powers_labels = ants.make_points_image(powers_pts.iloc[:,:3].values, mni, radius=3) | [
"Create",
"label",
"image",
"from",
"physical",
"space",
"points"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/make_points_image.py#L11-L60 | train | 232,062 |
ANTsX/ANTsPy | ants/utils/weingarten_image_curvature.py | weingarten_image_curvature | def weingarten_image_curvature(image, sigma=1.0, opt='mean'):
"""
Uses the weingarten map to estimate image mean or gaussian curvature
ANTsR function: `weingartenImageCurvature`
Arguments
---------
image : ANTsImage
image from which curvature is calculated
sigma : scalar
smoothing parameter
opt : string
mean by default, otherwise `gaussian` or `characterize`
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('mni')).resample_image((3,3,3))
>>> imagecurv = ants.weingarten_image_curvature(image)
"""
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[:d[0],:d[1],k] = voxvals
temp = core.from_numpy(temp)
myspc = image.spacing
myspc = list(myspc) + [min(myspc)]
temp.set_spacing(myspc)
temp = temp.clone('float')
else:
temp = image.clone('float')
optnum = 0
if opt == 'gaussian':
optnum = 6
if opt == 'characterize':
optnum = 5
libfn = utils.get_lib_fn('weingartenImageCurvature')
mykout = libfn(temp.pointer, sigma, optnum)
mykout = iio.ANTsImage(pixeltype=image.pixeltype, dimension=3,
components=image.components, pointer=mykout)
if image.dimension == 3:
return mykout
elif image.dimension == 2:
subarr = core.from_numpy(mykout.numpy()[:,:,4])
return core.copy_image_info(image, subarr) | python | def weingarten_image_curvature(image, sigma=1.0, opt='mean'):
"""
Uses the weingarten map to estimate image mean or gaussian curvature
ANTsR function: `weingartenImageCurvature`
Arguments
---------
image : ANTsImage
image from which curvature is calculated
sigma : scalar
smoothing parameter
opt : string
mean by default, otherwise `gaussian` or `characterize`
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('mni')).resample_image((3,3,3))
>>> imagecurv = ants.weingarten_image_curvature(image)
"""
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[:d[0],:d[1],k] = voxvals
temp = core.from_numpy(temp)
myspc = image.spacing
myspc = list(myspc) + [min(myspc)]
temp.set_spacing(myspc)
temp = temp.clone('float')
else:
temp = image.clone('float')
optnum = 0
if opt == 'gaussian':
optnum = 6
if opt == 'characterize':
optnum = 5
libfn = utils.get_lib_fn('weingartenImageCurvature')
mykout = libfn(temp.pointer, sigma, optnum)
mykout = iio.ANTsImage(pixeltype=image.pixeltype, dimension=3,
components=image.components, pointer=mykout)
if image.dimension == 3:
return mykout
elif image.dimension == 2:
subarr = core.from_numpy(mykout.numpy()[:,:,4])
return core.copy_image_info(image, subarr) | [
"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",
"[",
":",
"d",
"[",
"0",
"]",
",",
":",
"d",
"[",
"1",
"]",
",",
"k",
"]",
"=",
"voxvals",
"temp",
"=",
"core",
".",
"from_numpy",
"(",
"temp",
")",
"myspc",
"=",
"image",
".",
"spacing",
"myspc",
"=",
"list",
"(",
"myspc",
")",
"+",
"[",
"min",
"(",
"myspc",
")",
"]",
"temp",
".",
"set_spacing",
"(",
"myspc",
")",
"temp",
"=",
"temp",
".",
"clone",
"(",
"'float'",
")",
"else",
":",
"temp",
"=",
"image",
".",
"clone",
"(",
"'float'",
")",
"optnum",
"=",
"0",
"if",
"opt",
"==",
"'gaussian'",
":",
"optnum",
"=",
"6",
"if",
"opt",
"==",
"'characterize'",
":",
"optnum",
"=",
"5",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'weingartenImageCurvature'",
")",
"mykout",
"=",
"libfn",
"(",
"temp",
".",
"pointer",
",",
"sigma",
",",
"optnum",
")",
"mykout",
"=",
"iio",
".",
"ANTsImage",
"(",
"pixeltype",
"=",
"image",
".",
"pixeltype",
",",
"dimension",
"=",
"3",
",",
"components",
"=",
"image",
".",
"components",
",",
"pointer",
"=",
"mykout",
")",
"if",
"image",
".",
"dimension",
"==",
"3",
":",
"return",
"mykout",
"elif",
"image",
".",
"dimension",
"==",
"2",
":",
"subarr",
"=",
"core",
".",
"from_numpy",
"(",
"mykout",
".",
"numpy",
"(",
")",
"[",
":",
",",
":",
",",
"4",
"]",
")",
"return",
"core",
".",
"copy_image_info",
"(",
"image",
",",
"subarr",
")"
] | Uses the weingarten map to estimate image mean or gaussian curvature
ANTsR function: `weingartenImageCurvature`
Arguments
---------
image : ANTsImage
image from which curvature is calculated
sigma : scalar
smoothing parameter
opt : string
mean by default, otherwise `gaussian` or `characterize`
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('mni')).resample_image((3,3,3))
>>> imagecurv = ants.weingarten_image_curvature(image) | [
"Uses",
"the",
"weingarten",
"map",
"to",
"estimate",
"image",
"mean",
"or",
"gaussian",
"curvature"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/weingarten_image_curvature.py#L11-L69 | train | 232,063 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | from_numpy | def from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False):
"""
Create an ANTsImage object from a numpy array
ANTsR function: `as.antsImage`
Arguments
---------
data : ndarray
image data array
origin : tuple/list
image origin
spacing : tuple/list
image spacing
direction : list/ndarray
image direction
has_components : boolean
whether the image has components
Returns
-------
ANTsImage
image with given data and any given information
"""
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 | python | def from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False):
"""
Create an ANTsImage object from a numpy array
ANTsR function: `as.antsImage`
Arguments
---------
data : ndarray
image data array
origin : tuple/list
image origin
spacing : tuple/list
image spacing
direction : list/ndarray
image direction
has_components : boolean
whether the image has components
Returns
-------
ANTsImage
image with given data and any given information
"""
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 | [
"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
ANTsR function: `as.antsImage`
Arguments
---------
data : ndarray
image data array
origin : tuple/list
image origin
spacing : tuple/list
image spacing
direction : list/ndarray
image direction
has_components : boolean
whether the image has components
Returns
-------
ANTsImage
image with given data and any given information | [
"Create",
"an",
"ANTsImage",
"object",
"from",
"a",
"numpy",
"array"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L76-L106 | train | 232,064 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | _from_numpy | def _from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False):
"""
Internal function for creating an ANTsImage
"""
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 = tuple([0.]*ndim)
if spacing is None: spacing = tuple([1.]*ndim)
if direction is None: direction = np.eye(ndim)
libfn = utils.get_lib_fn('fromNumpy%s%i' % (_ntype_type_map[dtype], ndim))
if not has_components:
itk_image = libfn(data, data.shape[::-1])
ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=1, pointer=itk_image)
ants_image.set_origin(origin)
ants_image.set_spacing(spacing)
ants_image.set_direction(direction)
ants_image._ndarr = data
else:
arrays = [data[i,...].copy() for i in range(data.shape[0])]
data_shape = arrays[0].shape
ants_images = []
for i in range(len(arrays)):
tmp_ptr = libfn(arrays[i], data_shape[::-1])
tmp_img = iio.ANTsImage(pixeltype=ptype,
dimension=ndim,
components=1,
pointer=tmp_ptr)
tmp_img.set_origin(origin)
tmp_img.set_spacing(spacing)
tmp_img.set_direction(direction)
tmp_img._ndarr = arrays[i]
ants_images.append(tmp_img)
ants_image = utils.merge_channels(ants_images)
if is_rgb: ants_image = ants_image.vector_to_rgb()
return ants_image | python | def _from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False):
"""
Internal function for creating an ANTsImage
"""
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 = tuple([0.]*ndim)
if spacing is None: spacing = tuple([1.]*ndim)
if direction is None: direction = np.eye(ndim)
libfn = utils.get_lib_fn('fromNumpy%s%i' % (_ntype_type_map[dtype], ndim))
if not has_components:
itk_image = libfn(data, data.shape[::-1])
ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=1, pointer=itk_image)
ants_image.set_origin(origin)
ants_image.set_spacing(spacing)
ants_image.set_direction(direction)
ants_image._ndarr = data
else:
arrays = [data[i,...].copy() for i in range(data.shape[0])]
data_shape = arrays[0].shape
ants_images = []
for i in range(len(arrays)):
tmp_ptr = libfn(arrays[i], data_shape[::-1])
tmp_img = iio.ANTsImage(pixeltype=ptype,
dimension=ndim,
components=1,
pointer=tmp_ptr)
tmp_img.set_origin(origin)
tmp_img.set_spacing(spacing)
tmp_img.set_direction(direction)
tmp_img._ndarr = arrays[i]
ants_images.append(tmp_img)
ants_image = utils.merge_channels(ants_images)
if is_rgb: ants_image = ants_image.vector_to_rgb()
return ants_image | [
"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",
"=",
"tuple",
"(",
"[",
"0.",
"]",
"*",
"ndim",
")",
"if",
"spacing",
"is",
"None",
":",
"spacing",
"=",
"tuple",
"(",
"[",
"1.",
"]",
"*",
"ndim",
")",
"if",
"direction",
"is",
"None",
":",
"direction",
"=",
"np",
".",
"eye",
"(",
"ndim",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'fromNumpy%s%i'",
"%",
"(",
"_ntype_type_map",
"[",
"dtype",
"]",
",",
"ndim",
")",
")",
"if",
"not",
"has_components",
":",
"itk_image",
"=",
"libfn",
"(",
"data",
",",
"data",
".",
"shape",
"[",
":",
":",
"-",
"1",
"]",
")",
"ants_image",
"=",
"iio",
".",
"ANTsImage",
"(",
"pixeltype",
"=",
"ptype",
",",
"dimension",
"=",
"ndim",
",",
"components",
"=",
"1",
",",
"pointer",
"=",
"itk_image",
")",
"ants_image",
".",
"set_origin",
"(",
"origin",
")",
"ants_image",
".",
"set_spacing",
"(",
"spacing",
")",
"ants_image",
".",
"set_direction",
"(",
"direction",
")",
"ants_image",
".",
"_ndarr",
"=",
"data",
"else",
":",
"arrays",
"=",
"[",
"data",
"[",
"i",
",",
"...",
"]",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"data",
".",
"shape",
"[",
"0",
"]",
")",
"]",
"data_shape",
"=",
"arrays",
"[",
"0",
"]",
".",
"shape",
"ants_images",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arrays",
")",
")",
":",
"tmp_ptr",
"=",
"libfn",
"(",
"arrays",
"[",
"i",
"]",
",",
"data_shape",
"[",
":",
":",
"-",
"1",
"]",
")",
"tmp_img",
"=",
"iio",
".",
"ANTsImage",
"(",
"pixeltype",
"=",
"ptype",
",",
"dimension",
"=",
"ndim",
",",
"components",
"=",
"1",
",",
"pointer",
"=",
"tmp_ptr",
")",
"tmp_img",
".",
"set_origin",
"(",
"origin",
")",
"tmp_img",
".",
"set_spacing",
"(",
"spacing",
")",
"tmp_img",
".",
"set_direction",
"(",
"direction",
")",
"tmp_img",
".",
"_ndarr",
"=",
"arrays",
"[",
"i",
"]",
"ants_images",
".",
"append",
"(",
"tmp_img",
")",
"ants_image",
"=",
"utils",
".",
"merge_channels",
"(",
"ants_images",
")",
"if",
"is_rgb",
":",
"ants_image",
"=",
"ants_image",
".",
"vector_to_rgb",
"(",
")",
"return",
"ants_image"
] | Internal function for creating an ANTsImage | [
"Internal",
"function",
"for",
"creating",
"an",
"ANTsImage"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L109-L152 | train | 232,065 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | make_image | def make_image(imagesize, voxval=0, spacing=None, origin=None, direction=None, has_components=False, pixeltype='float'):
"""
Make an image with given size and voxel value or given a mask and vector
ANTsR function: `makeImage`
Arguments
---------
shape : tuple/ANTsImage
input image size or mask
voxval : scalar
input image value or vector, size of mask
spacing : tuple/list
image spatial resolution
origin : tuple/list
image spatial origin
direction : list/ndarray
direction matrix to convert from index to physical space
components : boolean
whether there are components per pixel or not
pixeltype : float
data type of image values
Returns
-------
ANTsImage
"""
if isinstance(imagesize, iio.ANTsImage):
img = imagesize.clone()
sel = imagesize > 0
if voxval.ndim > 1:
voxval = voxval.flatten()
if (len(voxval) == int((sel>0).sum())) or (len(voxval) == 0):
img[sel] = voxval
else:
raise ValueError('Num given voxels %i not same as num positive values %i in `imagesize`' % (len(voxval), int((sel>0).sum())))
return img
else:
if isinstance(voxval, (tuple,list,np.ndarray)):
array = np.asarray(voxval).astype('float32').reshape(imagesize)
else:
array = np.full(imagesize,voxval,dtype='float32')
image = from_numpy(array, origin=origin, spacing=spacing,
direction=direction, has_components=has_components)
return image.clone(pixeltype) | python | def make_image(imagesize, voxval=0, spacing=None, origin=None, direction=None, has_components=False, pixeltype='float'):
"""
Make an image with given size and voxel value or given a mask and vector
ANTsR function: `makeImage`
Arguments
---------
shape : tuple/ANTsImage
input image size or mask
voxval : scalar
input image value or vector, size of mask
spacing : tuple/list
image spatial resolution
origin : tuple/list
image spatial origin
direction : list/ndarray
direction matrix to convert from index to physical space
components : boolean
whether there are components per pixel or not
pixeltype : float
data type of image values
Returns
-------
ANTsImage
"""
if isinstance(imagesize, iio.ANTsImage):
img = imagesize.clone()
sel = imagesize > 0
if voxval.ndim > 1:
voxval = voxval.flatten()
if (len(voxval) == int((sel>0).sum())) or (len(voxval) == 0):
img[sel] = voxval
else:
raise ValueError('Num given voxels %i not same as num positive values %i in `imagesize`' % (len(voxval), int((sel>0).sum())))
return img
else:
if isinstance(voxval, (tuple,list,np.ndarray)):
array = np.asarray(voxval).astype('float32').reshape(imagesize)
else:
array = np.full(imagesize,voxval,dtype='float32')
image = from_numpy(array, origin=origin, spacing=spacing,
direction=direction, has_components=has_components)
return image.clone(pixeltype) | [
"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",
"(",
"(",
"sel",
">",
"0",
")",
".",
"sum",
"(",
")",
")",
")",
"or",
"(",
"len",
"(",
"voxval",
")",
"==",
"0",
")",
":",
"img",
"[",
"sel",
"]",
"=",
"voxval",
"else",
":",
"raise",
"ValueError",
"(",
"'Num given voxels %i not same as num positive values %i in `imagesize`'",
"%",
"(",
"len",
"(",
"voxval",
")",
",",
"int",
"(",
"(",
"sel",
">",
"0",
")",
".",
"sum",
"(",
")",
")",
")",
")",
"return",
"img",
"else",
":",
"if",
"isinstance",
"(",
"voxval",
",",
"(",
"tuple",
",",
"list",
",",
"np",
".",
"ndarray",
")",
")",
":",
"array",
"=",
"np",
".",
"asarray",
"(",
"voxval",
")",
".",
"astype",
"(",
"'float32'",
")",
".",
"reshape",
"(",
"imagesize",
")",
"else",
":",
"array",
"=",
"np",
".",
"full",
"(",
"imagesize",
",",
"voxval",
",",
"dtype",
"=",
"'float32'",
")",
"image",
"=",
"from_numpy",
"(",
"array",
",",
"origin",
"=",
"origin",
",",
"spacing",
"=",
"spacing",
",",
"direction",
"=",
"direction",
",",
"has_components",
"=",
"has_components",
")",
"return",
"image",
".",
"clone",
"(",
"pixeltype",
")"
] | Make an image with given size and voxel value or given a mask and vector
ANTsR function: `makeImage`
Arguments
---------
shape : tuple/ANTsImage
input image size or mask
voxval : scalar
input image value or vector, size of mask
spacing : tuple/list
image spatial resolution
origin : tuple/list
image spatial origin
direction : list/ndarray
direction matrix to convert from index to physical space
components : boolean
whether there are components per pixel or not
pixeltype : float
data type of image values
Returns
-------
ANTsImage | [
"Make",
"an",
"image",
"with",
"given",
"size",
"and",
"voxel",
"value",
"or",
"given",
"a",
"mask",
"and",
"vector"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L155-L205 | train | 232,066 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | matrix_to_images | def matrix_to_images(data_matrix, mask):
"""
Unmasks rows of a matrix and writes as images
ANTsR function: `matrixToImages`
Arguments
---------
data_matrix : numpy.ndarray
each row corresponds to an image
array should have number of columns equal to non-zero voxels in the mask
mask : ANTsImage
image containing a binary mask. Rows of the matrix are
unmasked and written as images. The mask defines the output image space
Returns
-------
list of ANTsImage types
"""
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 ValueError('Num masked voxels %i must match data matrix %i' % (numVoxelsInMask, numVoxelsInMatrix))
imagelist = []
for i in range(numimages):
img = mask.clone()
img[mask >= 0.5] = data_matrix[i,:]
imagelist.append(img)
return imagelist | python | def matrix_to_images(data_matrix, mask):
"""
Unmasks rows of a matrix and writes as images
ANTsR function: `matrixToImages`
Arguments
---------
data_matrix : numpy.ndarray
each row corresponds to an image
array should have number of columns equal to non-zero voxels in the mask
mask : ANTsImage
image containing a binary mask. Rows of the matrix are
unmasked and written as images. The mask defines the output image space
Returns
-------
list of ANTsImage types
"""
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 ValueError('Num masked voxels %i must match data matrix %i' % (numVoxelsInMask, numVoxelsInMatrix))
imagelist = []
for i in range(numimages):
img = mask.clone()
img[mask >= 0.5] = data_matrix[i,:]
imagelist.append(img)
return imagelist | [
"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",
"ValueError",
"(",
"'Num masked voxels %i must match data matrix %i'",
"%",
"(",
"numVoxelsInMask",
",",
"numVoxelsInMatrix",
")",
")",
"imagelist",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"numimages",
")",
":",
"img",
"=",
"mask",
".",
"clone",
"(",
")",
"img",
"[",
"mask",
">=",
"0.5",
"]",
"=",
"data_matrix",
"[",
"i",
",",
":",
"]",
"imagelist",
".",
"append",
"(",
"img",
")",
"return",
"imagelist"
] | Unmasks rows of a matrix and writes as images
ANTsR function: `matrixToImages`
Arguments
---------
data_matrix : numpy.ndarray
each row corresponds to an image
array should have number of columns equal to non-zero voxels in the mask
mask : ANTsImage
image containing a binary mask. Rows of the matrix are
unmasked and written as images. The mask defines the output image space
Returns
-------
list of ANTsImage types | [
"Unmasks",
"rows",
"of",
"a",
"matrix",
"and",
"writes",
"as",
"images"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L208-L243 | train | 232,067 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | images_to_matrix | def images_to_matrix(image_list, mask=None, sigma=None, epsilon=0.5 ):
"""
Read images into rows of a matrix, given a mask - much faster for
large datasets as it is based on C++ implementations.
ANTsR function: `imagesToMatrix`
Arguments
---------
image_list : list of ANTsImage types
images to convert to ndarray
mask : ANTsImage (optional)
image containing binary mask. voxels in the mask are placed in the matrix
sigma : scaler (optional)
smoothing factor
epsilon : scalar
threshold for mask
Returns
-------
ndarray
array with a row for each image
shape = (N_IMAGES, N_VOXELS)
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_ants_data('r16'))
>>> img2 = ants.image_read(ants.get_ants_data('r16'))
>>> img3 = ants.image_read(ants.get_ants_data('r16'))
>>> mat = ants.image_list_to_matrix([img,img2,img3])
"""
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_images = len(image_list)
mask_arr = mask.numpy() >= epsilon
num_voxels = np.sum(mask_arr)
data_matrix = np.empty((num_images, num_voxels))
do_smooth = sigma is not None
for i,img in enumerate(image_list):
if do_smooth:
data_matrix[i, :] = listfunc(utils.smooth_image(img, sigma, sigma_in_physical_coordinates=True))
else:
data_matrix[i,:] = listfunc(img)
return data_matrix | python | def images_to_matrix(image_list, mask=None, sigma=None, epsilon=0.5 ):
"""
Read images into rows of a matrix, given a mask - much faster for
large datasets as it is based on C++ implementations.
ANTsR function: `imagesToMatrix`
Arguments
---------
image_list : list of ANTsImage types
images to convert to ndarray
mask : ANTsImage (optional)
image containing binary mask. voxels in the mask are placed in the matrix
sigma : scaler (optional)
smoothing factor
epsilon : scalar
threshold for mask
Returns
-------
ndarray
array with a row for each image
shape = (N_IMAGES, N_VOXELS)
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_ants_data('r16'))
>>> img2 = ants.image_read(ants.get_ants_data('r16'))
>>> img3 = ants.image_read(ants.get_ants_data('r16'))
>>> mat = ants.image_list_to_matrix([img,img2,img3])
"""
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_images = len(image_list)
mask_arr = mask.numpy() >= epsilon
num_voxels = np.sum(mask_arr)
data_matrix = np.empty((num_images, num_voxels))
do_smooth = sigma is not None
for i,img in enumerate(image_list):
if do_smooth:
data_matrix[i, :] = listfunc(utils.smooth_image(img, sigma, sigma_in_physical_coordinates=True))
else:
data_matrix[i,:] = listfunc(img)
return data_matrix | [
"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_images",
"=",
"len",
"(",
"image_list",
")",
"mask_arr",
"=",
"mask",
".",
"numpy",
"(",
")",
">=",
"epsilon",
"num_voxels",
"=",
"np",
".",
"sum",
"(",
"mask_arr",
")",
"data_matrix",
"=",
"np",
".",
"empty",
"(",
"(",
"num_images",
",",
"num_voxels",
")",
")",
"do_smooth",
"=",
"sigma",
"is",
"not",
"None",
"for",
"i",
",",
"img",
"in",
"enumerate",
"(",
"image_list",
")",
":",
"if",
"do_smooth",
":",
"data_matrix",
"[",
"i",
",",
":",
"]",
"=",
"listfunc",
"(",
"utils",
".",
"smooth_image",
"(",
"img",
",",
"sigma",
",",
"sigma_in_physical_coordinates",
"=",
"True",
")",
")",
"else",
":",
"data_matrix",
"[",
"i",
",",
":",
"]",
"=",
"listfunc",
"(",
"img",
")",
"return",
"data_matrix"
] | Read images into rows of a matrix, given a mask - much faster for
large datasets as it is based on C++ implementations.
ANTsR function: `imagesToMatrix`
Arguments
---------
image_list : list of ANTsImage types
images to convert to ndarray
mask : ANTsImage (optional)
image containing binary mask. voxels in the mask are placed in the matrix
sigma : scaler (optional)
smoothing factor
epsilon : scalar
threshold for mask
Returns
-------
ndarray
array with a row for each image
shape = (N_IMAGES, N_VOXELS)
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_ants_data('r16'))
>>> img2 = ants.image_read(ants.get_ants_data('r16'))
>>> img3 = ants.image_read(ants.get_ants_data('r16'))
>>> mat = ants.image_list_to_matrix([img,img2,img3]) | [
"Read",
"images",
"into",
"rows",
"of",
"a",
"matrix",
"given",
"a",
"mask",
"-",
"much",
"faster",
"for",
"large",
"datasets",
"as",
"it",
"is",
"based",
"on",
"C",
"++",
"implementations",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L247-L301 | train | 232,068 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | timeseries_to_matrix | def timeseries_to_matrix( image, mask=None ):
"""
Convert a timeseries image into a matrix.
ANTsR function: `timeseries2matrix`
Arguments
---------
image : image whose slices we convert to a matrix. E.g. a 3D image of size
x by y by z will convert to a z by x*y sized matrix
mask : ANTsImage (optional)
image containing binary mask. voxels in the mask are placed in the matrix
Returns
-------
ndarray
array with a row for each image
shape = (N_IMAGES, N_VOXELS)
Example
-------
>>> import ants
>>> img = ants.make_image( (10,10,10,5 ) )
>>> mat = ants.timeseries_to_matrix( img )
"""
temp = utils.ndimage_to_list( image )
if mask is None:
mask = temp[0]*0 + 1
return image_list_to_matrix( temp, mask ) | python | def timeseries_to_matrix( image, mask=None ):
"""
Convert a timeseries image into a matrix.
ANTsR function: `timeseries2matrix`
Arguments
---------
image : image whose slices we convert to a matrix. E.g. a 3D image of size
x by y by z will convert to a z by x*y sized matrix
mask : ANTsImage (optional)
image containing binary mask. voxels in the mask are placed in the matrix
Returns
-------
ndarray
array with a row for each image
shape = (N_IMAGES, N_VOXELS)
Example
-------
>>> import ants
>>> img = ants.make_image( (10,10,10,5 ) )
>>> mat = ants.timeseries_to_matrix( img )
"""
temp = utils.ndimage_to_list( image )
if mask is None:
mask = temp[0]*0 + 1
return image_list_to_matrix( temp, mask ) | [
"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.
ANTsR function: `timeseries2matrix`
Arguments
---------
image : image whose slices we convert to a matrix. E.g. a 3D image of size
x by y by z will convert to a z by x*y sized matrix
mask : ANTsImage (optional)
image containing binary mask. voxels in the mask are placed in the matrix
Returns
-------
ndarray
array with a row for each image
shape = (N_IMAGES, N_VOXELS)
Example
-------
>>> import ants
>>> img = ants.make_image( (10,10,10,5 ) )
>>> mat = ants.timeseries_to_matrix( img ) | [
"Convert",
"a",
"timeseries",
"image",
"into",
"a",
"matrix",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L307-L336 | train | 232,069 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | matrix_to_timeseries | def matrix_to_timeseries( image, matrix, mask=None ):
"""
converts a matrix to a ND image.
ANTsR function: `matrix2timeseries`
Arguments
---------
image: reference ND image
matrix: matrix to convert to image
mask: mask image defining voxels of interest
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.make_image( (10,10,10,5 ) )
>>> mask = ants.ndimage_to_list( img )[0] * 0
>>> mask[ 4:8, 4:8, 4:8 ] = 1
>>> mat = ants.timeseries_to_matrix( img, mask = mask )
>>> img2 = ants.matrix_to_timeseries( img, mat, mask)
"""
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) | python | def matrix_to_timeseries( image, matrix, mask=None ):
"""
converts a matrix to a ND image.
ANTsR function: `matrix2timeseries`
Arguments
---------
image: reference ND image
matrix: matrix to convert to image
mask: mask image defining voxels of interest
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.make_image( (10,10,10,5 ) )
>>> mask = ants.ndimage_to_list( img )[0] * 0
>>> mask[ 4:8, 4:8, 4:8 ] = 1
>>> mat = ants.timeseries_to_matrix( img, mask = mask )
>>> img2 = ants.matrix_to_timeseries( img, mat, mask)
"""
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) | [
"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.
ANTsR function: `matrix2timeseries`
Arguments
---------
image: reference ND image
matrix: matrix to convert to image
mask: mask image defining voxels of interest
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.make_image( (10,10,10,5 ) )
>>> mask = ants.ndimage_to_list( img )[0] * 0
>>> mask[ 4:8, 4:8, 4:8 ] = 1
>>> mat = ants.timeseries_to_matrix( img, mask = mask )
>>> img2 = ants.matrix_to_timeseries( img, mat, mask) | [
"converts",
"a",
"matrix",
"to",
"a",
"ND",
"image",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L339-L374 | train | 232,070 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | image_header_info | def image_header_info(filename):
"""
Read file info from image header
ANTsR function: `antsImageHeaderInfo`
Arguments
---------
filename : string
name of image file from which info will be read
Returns
-------
dict
"""
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 in retval['origin']])
retval['spacing'] = tuple([round(s,4) for s in retval['spacing']])
retval['direction'] = np.round(retval['direction'],4)
return retval | python | def image_header_info(filename):
"""
Read file info from image header
ANTsR function: `antsImageHeaderInfo`
Arguments
---------
filename : string
name of image file from which info will be read
Returns
-------
dict
"""
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 in retval['origin']])
retval['spacing'] = tuple([round(s,4) for s in retval['spacing']])
retval['direction'] = np.round(retval['direction'],4)
return retval | [
"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",
"in",
"retval",
"[",
"'origin'",
"]",
"]",
")",
"retval",
"[",
"'spacing'",
"]",
"=",
"tuple",
"(",
"[",
"round",
"(",
"s",
",",
"4",
")",
"for",
"s",
"in",
"retval",
"[",
"'spacing'",
"]",
"]",
")",
"retval",
"[",
"'direction'",
"]",
"=",
"np",
".",
"round",
"(",
"retval",
"[",
"'direction'",
"]",
",",
"4",
")",
"return",
"retval"
] | Read file info from image header
ANTsR function: `antsImageHeaderInfo`
Arguments
---------
filename : string
name of image file from which info will be read
Returns
-------
dict | [
"Read",
"file",
"info",
"from",
"image",
"header"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L377-L401 | train | 232,071 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | image_read | def image_read(filename, dimension=None, pixeltype='float', reorient=False):
"""
Read an ANTsImage from file
ANTsR function: `antsImageRead`
Arguments
---------
filename : string
Name of the file to read the image from.
dimension : int
Number of dimensions of the image read. This need not be the same as
the dimensions of the image in the file. Allowed values: 2, 3, 4.
If not provided, the dimension is obtained from the image file
pixeltype : string
C++ datatype to be used to represent the pixels read. This datatype
need not be the same as the datatype used in the file.
Options: unsigned char, unsigned int, float, double
reorient : boolean | string
if True, the image will be reoriented to RPI if it is 3D
if False, nothing will happen
if string, this should be the 3-letter orientation to which the
input image will reoriented if 3D.
if the image is 2D, this argument is ignored
Returns
-------
ANTsImage
"""
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', '.json')) as json_data:
img_header = json.load(json_data)
ants_image = from_numpy(img_array,
origin=img_header.get('origin', None),
spacing=img_header.get('spacing', None),
direction=np.asarray(img_header.get('direction',None)),
has_components=img_header.get('components',1)>1)
else:
img_header = {}
ants_image = from_numpy(img_array)
else:
filename = os.path.expanduser(filename)
if not os.path.exists(filename):
raise ValueError('File %s does not exist!' % filename)
hinfo = image_header_info(filename)
ptype = hinfo['pixeltype']
pclass = hinfo['pixelclass']
ndim = hinfo['nDimensions']
ncomp = hinfo['nComponents']
is_rgb = True if pclass == 'rgb' else False
if dimension is not None:
ndim = dimension
# error handling on pixelclass
if pclass not in _supported_pclasses:
raise ValueError('Pixel class %s not supported!' % pclass)
# error handling on pixeltype
if ptype in _unsupported_ptypes:
ptype = _unsupported_ptype_map.get(ptype, 'unsupported')
if ptype == 'unsupported':
raise ValueError('Pixeltype %s not supported' % ptype)
# error handling on dimension
if (ndim < 2) or (ndim > 4):
raise ValueError('Found %i-dimensional image - not supported!' % ndim)
libfn = utils.get_lib_fn(_image_read_dict[pclass][ptype][ndim])
itk_pointer = libfn(filename)
ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=ncomp,
pointer=itk_pointer, is_rgb=is_rgb)
if pixeltype is not None:
ants_image = ants_image.clone(pixeltype)
if (reorient != False) and (ants_image.dimension == 3):
if reorient == True:
ants_image = ants_image.reorient_image2('RPI')
elif isinstance(reorient, str):
ants_image = ants_image.reorient_image2(reorient)
return ants_image | python | def image_read(filename, dimension=None, pixeltype='float', reorient=False):
"""
Read an ANTsImage from file
ANTsR function: `antsImageRead`
Arguments
---------
filename : string
Name of the file to read the image from.
dimension : int
Number of dimensions of the image read. This need not be the same as
the dimensions of the image in the file. Allowed values: 2, 3, 4.
If not provided, the dimension is obtained from the image file
pixeltype : string
C++ datatype to be used to represent the pixels read. This datatype
need not be the same as the datatype used in the file.
Options: unsigned char, unsigned int, float, double
reorient : boolean | string
if True, the image will be reoriented to RPI if it is 3D
if False, nothing will happen
if string, this should be the 3-letter orientation to which the
input image will reoriented if 3D.
if the image is 2D, this argument is ignored
Returns
-------
ANTsImage
"""
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', '.json')) as json_data:
img_header = json.load(json_data)
ants_image = from_numpy(img_array,
origin=img_header.get('origin', None),
spacing=img_header.get('spacing', None),
direction=np.asarray(img_header.get('direction',None)),
has_components=img_header.get('components',1)>1)
else:
img_header = {}
ants_image = from_numpy(img_array)
else:
filename = os.path.expanduser(filename)
if not os.path.exists(filename):
raise ValueError('File %s does not exist!' % filename)
hinfo = image_header_info(filename)
ptype = hinfo['pixeltype']
pclass = hinfo['pixelclass']
ndim = hinfo['nDimensions']
ncomp = hinfo['nComponents']
is_rgb = True if pclass == 'rgb' else False
if dimension is not None:
ndim = dimension
# error handling on pixelclass
if pclass not in _supported_pclasses:
raise ValueError('Pixel class %s not supported!' % pclass)
# error handling on pixeltype
if ptype in _unsupported_ptypes:
ptype = _unsupported_ptype_map.get(ptype, 'unsupported')
if ptype == 'unsupported':
raise ValueError('Pixeltype %s not supported' % ptype)
# error handling on dimension
if (ndim < 2) or (ndim > 4):
raise ValueError('Found %i-dimensional image - not supported!' % ndim)
libfn = utils.get_lib_fn(_image_read_dict[pclass][ptype][ndim])
itk_pointer = libfn(filename)
ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=ncomp,
pointer=itk_pointer, is_rgb=is_rgb)
if pixeltype is not None:
ants_image = ants_image.clone(pixeltype)
if (reorient != False) and (ants_image.dimension == 3):
if reorient == True:
ants_image = ants_image.reorient_image2('RPI')
elif isinstance(reorient, str):
ants_image = ants_image.reorient_image2(reorient)
return ants_image | [
"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'",
",",
"'.json'",
")",
")",
"as",
"json_data",
":",
"img_header",
"=",
"json",
".",
"load",
"(",
"json_data",
")",
"ants_image",
"=",
"from_numpy",
"(",
"img_array",
",",
"origin",
"=",
"img_header",
".",
"get",
"(",
"'origin'",
",",
"None",
")",
",",
"spacing",
"=",
"img_header",
".",
"get",
"(",
"'spacing'",
",",
"None",
")",
",",
"direction",
"=",
"np",
".",
"asarray",
"(",
"img_header",
".",
"get",
"(",
"'direction'",
",",
"None",
")",
")",
",",
"has_components",
"=",
"img_header",
".",
"get",
"(",
"'components'",
",",
"1",
")",
">",
"1",
")",
"else",
":",
"img_header",
"=",
"{",
"}",
"ants_image",
"=",
"from_numpy",
"(",
"img_array",
")",
"else",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"raise",
"ValueError",
"(",
"'File %s does not exist!'",
"%",
"filename",
")",
"hinfo",
"=",
"image_header_info",
"(",
"filename",
")",
"ptype",
"=",
"hinfo",
"[",
"'pixeltype'",
"]",
"pclass",
"=",
"hinfo",
"[",
"'pixelclass'",
"]",
"ndim",
"=",
"hinfo",
"[",
"'nDimensions'",
"]",
"ncomp",
"=",
"hinfo",
"[",
"'nComponents'",
"]",
"is_rgb",
"=",
"True",
"if",
"pclass",
"==",
"'rgb'",
"else",
"False",
"if",
"dimension",
"is",
"not",
"None",
":",
"ndim",
"=",
"dimension",
"# error handling on pixelclass",
"if",
"pclass",
"not",
"in",
"_supported_pclasses",
":",
"raise",
"ValueError",
"(",
"'Pixel class %s not supported!'",
"%",
"pclass",
")",
"# error handling on pixeltype",
"if",
"ptype",
"in",
"_unsupported_ptypes",
":",
"ptype",
"=",
"_unsupported_ptype_map",
".",
"get",
"(",
"ptype",
",",
"'unsupported'",
")",
"if",
"ptype",
"==",
"'unsupported'",
":",
"raise",
"ValueError",
"(",
"'Pixeltype %s not supported'",
"%",
"ptype",
")",
"# error handling on dimension",
"if",
"(",
"ndim",
"<",
"2",
")",
"or",
"(",
"ndim",
">",
"4",
")",
":",
"raise",
"ValueError",
"(",
"'Found %i-dimensional image - not supported!'",
"%",
"ndim",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"_image_read_dict",
"[",
"pclass",
"]",
"[",
"ptype",
"]",
"[",
"ndim",
"]",
")",
"itk_pointer",
"=",
"libfn",
"(",
"filename",
")",
"ants_image",
"=",
"iio",
".",
"ANTsImage",
"(",
"pixeltype",
"=",
"ptype",
",",
"dimension",
"=",
"ndim",
",",
"components",
"=",
"ncomp",
",",
"pointer",
"=",
"itk_pointer",
",",
"is_rgb",
"=",
"is_rgb",
")",
"if",
"pixeltype",
"is",
"not",
"None",
":",
"ants_image",
"=",
"ants_image",
".",
"clone",
"(",
"pixeltype",
")",
"if",
"(",
"reorient",
"!=",
"False",
")",
"and",
"(",
"ants_image",
".",
"dimension",
"==",
"3",
")",
":",
"if",
"reorient",
"==",
"True",
":",
"ants_image",
"=",
"ants_image",
".",
"reorient_image2",
"(",
"'RPI'",
")",
"elif",
"isinstance",
"(",
"reorient",
",",
"str",
")",
":",
"ants_image",
"=",
"ants_image",
".",
"reorient_image2",
"(",
"reorient",
")",
"return",
"ants_image"
] | Read an ANTsImage from file
ANTsR function: `antsImageRead`
Arguments
---------
filename : string
Name of the file to read the image from.
dimension : int
Number of dimensions of the image read. This need not be the same as
the dimensions of the image in the file. Allowed values: 2, 3, 4.
If not provided, the dimension is obtained from the image file
pixeltype : string
C++ datatype to be used to represent the pixels read. This datatype
need not be the same as the datatype used in the file.
Options: unsigned char, unsigned int, float, double
reorient : boolean | string
if True, the image will be reoriented to RPI if it is 3D
if False, nothing will happen
if string, this should be the 3-letter orientation to which the
input image will reoriented if 3D.
if the image is 2D, this argument is ignored
Returns
-------
ANTsImage | [
"Read",
"an",
"ANTsImage",
"from",
"file"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L425-L515 | train | 232,072 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | dicom_read | def dicom_read(directory, pixeltype='float'):
"""
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.
Arguments
---------
directory : string
folder in which all the dicom images exist
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.dicom_read('~/desktop/dicom-subject/')
"""
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
direction = tmp.direction
tmp = tmp.numpy()[:,:,0]
else:
tmp = image_read(os.path.join(directory,imgpath), dimension=2, pixeltype=pixeltype).numpy()
slices.append(tmp)
imgidx += 1
slices = np.stack(slices, axis=-1)
return from_numpy(slices, origin=origin, spacing=spacing, direction=direction) | python | def dicom_read(directory, pixeltype='float'):
"""
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.
Arguments
---------
directory : string
folder in which all the dicom images exist
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.dicom_read('~/desktop/dicom-subject/')
"""
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
direction = tmp.direction
tmp = tmp.numpy()[:,:,0]
else:
tmp = image_read(os.path.join(directory,imgpath), dimension=2, pixeltype=pixeltype).numpy()
slices.append(tmp)
imgidx += 1
slices = np.stack(slices, axis=-1)
return from_numpy(slices, origin=origin, spacing=spacing, direction=direction) | [
"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",
"direction",
"=",
"tmp",
".",
"direction",
"tmp",
"=",
"tmp",
".",
"numpy",
"(",
")",
"[",
":",
",",
":",
",",
"0",
"]",
"else",
":",
"tmp",
"=",
"image_read",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"imgpath",
")",
",",
"dimension",
"=",
"2",
",",
"pixeltype",
"=",
"pixeltype",
")",
".",
"numpy",
"(",
")",
"slices",
".",
"append",
"(",
"tmp",
")",
"imgidx",
"+=",
"1",
"slices",
"=",
"np",
".",
"stack",
"(",
"slices",
",",
"axis",
"=",
"-",
"1",
")",
"return",
"from_numpy",
"(",
"slices",
",",
"origin",
"=",
"origin",
",",
"spacing",
"=",
"spacing",
",",
"direction",
"=",
"direction",
")"
] | 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.
Arguments
---------
directory : string
folder in which all the dicom images exist
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.dicom_read('~/desktop/dicom-subject/') | [
"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",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L518-L555 | train | 232,073 |
ANTsX/ANTsPy | ants/core/ants_image_io.py | image_write | def image_write(image, filename, ri=False):
"""
Write an ANTsImage to file
ANTsR function: `antsImageWrite`
Arguments
---------
image : ANTsImage
image to save to file
filename : string
name of file to which image will be saved
ri : boolean
if True, return image. This allows for using this function in a pipeline:
>>> img2 = img.smooth_image(2.).image_write(file1, ri=True).threshold_image(0,20).image_write(file2, ri=True)
if False, do not return image
"""
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(filename.replace('.npy','.json'), 'w') as outfile:
json.dump(img_header, outfile)
else:
image.to_file(filename)
if ri:
return image | python | def image_write(image, filename, ri=False):
"""
Write an ANTsImage to file
ANTsR function: `antsImageWrite`
Arguments
---------
image : ANTsImage
image to save to file
filename : string
name of file to which image will be saved
ri : boolean
if True, return image. This allows for using this function in a pipeline:
>>> img2 = img.smooth_image(2.).image_write(file1, ri=True).threshold_image(0,20).image_write(file2, ri=True)
if False, do not return image
"""
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(filename.replace('.npy','.json'), 'w') as outfile:
json.dump(img_header, outfile)
else:
image.to_file(filename)
if ri:
return image | [
"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",
"(",
"filename",
".",
"replace",
"(",
"'.npy'",
",",
"'.json'",
")",
",",
"'w'",
")",
"as",
"outfile",
":",
"json",
".",
"dump",
"(",
"img_header",
",",
"outfile",
")",
"else",
":",
"image",
".",
"to_file",
"(",
"filename",
")",
"if",
"ri",
":",
"return",
"image"
] | Write an ANTsImage to file
ANTsR function: `antsImageWrite`
Arguments
---------
image : ANTsImage
image to save to file
filename : string
name of file to which image will be saved
ri : boolean
if True, return image. This allows for using this function in a pipeline:
>>> img2 = img.smooth_image(2.).image_write(file1, ri=True).threshold_image(0,20).image_write(file2, ri=True)
if False, do not return image | [
"Write",
"an",
"ANTsImage",
"to",
"file"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L558-L589 | train | 232,074 |
ANTsX/ANTsPy | ants/segmentation/otsu.py | otsu_segmentation | def otsu_segmentation(image, k, mask=None):
"""
Otsu image segmentation
This is a very fast segmentation algorithm good for quick explortation,
but does not return probability maps.
ANTsR function: `thresholdImage(image, 'Otsu', k)`
Arguments
---------
image : ANTsImage
input image
k : integer
integer number of classes. Note that a background class will
be added to this, so the resulting segmentation will
have k+1 unique values.
mask : ANTsImage
segment inside this mask
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> seg = mni.otsu_segmentation(k=3) #0=bg,1=csf,2=gm,3=wm
"""
if mask is not None:
image = image.mask_image(mask)
seg = image.threshold_image('Otsu', k)
return seg | python | def otsu_segmentation(image, k, mask=None):
"""
Otsu image segmentation
This is a very fast segmentation algorithm good for quick explortation,
but does not return probability maps.
ANTsR function: `thresholdImage(image, 'Otsu', k)`
Arguments
---------
image : ANTsImage
input image
k : integer
integer number of classes. Note that a background class will
be added to this, so the resulting segmentation will
have k+1 unique values.
mask : ANTsImage
segment inside this mask
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> seg = mni.otsu_segmentation(k=3) #0=bg,1=csf,2=gm,3=wm
"""
if mask is not None:
image = image.mask_image(mask)
seg = image.threshold_image('Otsu', k)
return seg | [
"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
This is a very fast segmentation algorithm good for quick explortation,
but does not return probability maps.
ANTsR function: `thresholdImage(image, 'Otsu', k)`
Arguments
---------
image : ANTsImage
input image
k : integer
integer number of classes. Note that a background class will
be added to this, so the resulting segmentation will
have k+1 unique values.
mask : ANTsImage
segment inside this mask
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> seg = mni.otsu_segmentation(k=3) #0=bg,1=csf,2=gm,3=wm | [
"Otsu",
"image",
"segmentation"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/segmentation/otsu.py#L7-L43 | train | 232,075 |
ANTsX/ANTsPy | ants/utils/crop_image.py | crop_image | def crop_image(image, label_image=None, label=1):
"""
Use a label image to crop a smaller ANTsImage from within a larger ANTsImage
ANTsR function: `cropImage`
Arguments
---------
image : ANTsImage
image to crop
label_image : ANTsImage
image with label values. If not supplied, estimated from data.
label : integer
the label value to use
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') )
>>> cropped = ants.crop_image(fi)
>>> cropped = ants.crop_image(fi, fi, 100 )
"""
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('float')
libfn = utils.get_lib_fn('cropImageF%i' % ndim)
itkimage = libfn(image.pointer, label_image.pointer, label, 0, [], [])
return iio.ANTsImage(pixeltype='float', dimension=ndim,
components=image.components, pointer=itkimage).clone(inpixeltype) | python | def crop_image(image, label_image=None, label=1):
"""
Use a label image to crop a smaller ANTsImage from within a larger ANTsImage
ANTsR function: `cropImage`
Arguments
---------
image : ANTsImage
image to crop
label_image : ANTsImage
image with label values. If not supplied, estimated from data.
label : integer
the label value to use
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') )
>>> cropped = ants.crop_image(fi)
>>> cropped = ants.crop_image(fi, fi, 100 )
"""
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('float')
libfn = utils.get_lib_fn('cropImageF%i' % ndim)
itkimage = libfn(image.pointer, label_image.pointer, label, 0, [], [])
return iio.ANTsImage(pixeltype='float', dimension=ndim,
components=image.components, pointer=itkimage).clone(inpixeltype) | [
"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",
"(",
"'float'",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'cropImageF%i'",
"%",
"ndim",
")",
"itkimage",
"=",
"libfn",
"(",
"image",
".",
"pointer",
",",
"label_image",
".",
"pointer",
",",
"label",
",",
"0",
",",
"[",
"]",
",",
"[",
"]",
")",
"return",
"iio",
".",
"ANTsImage",
"(",
"pixeltype",
"=",
"'float'",
",",
"dimension",
"=",
"ndim",
",",
"components",
"=",
"image",
".",
"components",
",",
"pointer",
"=",
"itkimage",
")",
".",
"clone",
"(",
"inpixeltype",
")"
] | Use a label image to crop a smaller ANTsImage from within a larger ANTsImage
ANTsR function: `cropImage`
Arguments
---------
image : ANTsImage
image to crop
label_image : ANTsImage
image with label values. If not supplied, estimated from data.
label : integer
the label value to use
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16') )
>>> cropped = ants.crop_image(fi)
>>> cropped = ants.crop_image(fi, fi, 100 ) | [
"Use",
"a",
"label",
"image",
"to",
"crop",
"a",
"smaller",
"ANTsImage",
"from",
"within",
"a",
"larger",
"ANTsImage"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/crop_image.py#L14-L56 | train | 232,076 |
ANTsX/ANTsPy | ants/utils/crop_image.py | decrop_image | def decrop_image(cropped_image, full_image):
"""
The inverse function for `ants.crop_image`
ANTsR function: `decropImage`
Arguments
---------
cropped_image : ANTsImage
cropped image
full_image : ANTsImage
image in which the cropped image will be put back
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> mask = ants.get_mask(fi)
>>> cropped = ants.crop_image(fi, mask, 1)
>>> cropped = ants.smooth_image(cropped, 1)
>>> decropped = ants.decrop_image(cropped, fi)
"""
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('cropImageF%i' % cropped_image.dimension)
itkimage = libfn(cropped_image.pointer, full_image.pointer, 1, 1, [], [])
ants_image = iio.ANTsImage(pixeltype='float', dimension=cropped_image.dimension,
components=cropped_image.components, pointer=itkimage)
if inpixeltype != 'float':
ants_image = ants_image.clone(inpixeltype)
return ants_image | python | def decrop_image(cropped_image, full_image):
"""
The inverse function for `ants.crop_image`
ANTsR function: `decropImage`
Arguments
---------
cropped_image : ANTsImage
cropped image
full_image : ANTsImage
image in which the cropped image will be put back
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> mask = ants.get_mask(fi)
>>> cropped = ants.crop_image(fi, mask, 1)
>>> cropped = ants.smooth_image(cropped, 1)
>>> decropped = ants.decrop_image(cropped, fi)
"""
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('cropImageF%i' % cropped_image.dimension)
itkimage = libfn(cropped_image.pointer, full_image.pointer, 1, 1, [], [])
ants_image = iio.ANTsImage(pixeltype='float', dimension=cropped_image.dimension,
components=cropped_image.components, pointer=itkimage)
if inpixeltype != 'float':
ants_image = ants_image.clone(inpixeltype)
return ants_image | [
"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",
"(",
"'cropImageF%i'",
"%",
"cropped_image",
".",
"dimension",
")",
"itkimage",
"=",
"libfn",
"(",
"cropped_image",
".",
"pointer",
",",
"full_image",
".",
"pointer",
",",
"1",
",",
"1",
",",
"[",
"]",
",",
"[",
"]",
")",
"ants_image",
"=",
"iio",
".",
"ANTsImage",
"(",
"pixeltype",
"=",
"'float'",
",",
"dimension",
"=",
"cropped_image",
".",
"dimension",
",",
"components",
"=",
"cropped_image",
".",
"components",
",",
"pointer",
"=",
"itkimage",
")",
"if",
"inpixeltype",
"!=",
"'float'",
":",
"ants_image",
"=",
"ants_image",
".",
"clone",
"(",
"inpixeltype",
")",
"return",
"ants_image"
] | The inverse function for `ants.crop_image`
ANTsR function: `decropImage`
Arguments
---------
cropped_image : ANTsImage
cropped image
full_image : ANTsImage
image in which the cropped image will be put back
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'))
>>> mask = ants.get_mask(fi)
>>> cropped = ants.crop_image(fi, mask, 1)
>>> cropped = ants.smooth_image(cropped, 1)
>>> decropped = ants.decrop_image(cropped, fi) | [
"The",
"inverse",
"function",
"for",
"ants",
".",
"crop_image"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/crop_image.py#L108-L149 | train | 232,077 |
ANTsX/ANTsPy | ants/segmentation/kmeans.py | kmeans_segmentation | def kmeans_segmentation(image, k, kmask=None, mrf=0.1):
"""
K-means image segmentation that is a wrapper around `ants.atropos`
ANTsR function: `kmeansSegmentation`
Arguments
---------
image : ANTsImage
input image
k : integer
integer number of classes
kmask : ANTsImage (optional)
segment inside this mask
mrf : scalar
smoothness, higher is smoother
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'), 'float')
>>> fi = ants.n3_bias_field_correction(fi, 2)
>>> seg = ants.kmeans_segmentation(fi, 3)
"""
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']*dim)
mrf = '[%s,%s]' % (str(mrf), nhood)
kmimage = atropos(a = kmimage, m = mrf, c = '[5,0]', i = 'kmeans[%s]'%(str(k)), x = kmask)
kmimage['segmentation'] = kmimage['segmentation'].clone(image.pixeltype)
return kmimage | python | def kmeans_segmentation(image, k, kmask=None, mrf=0.1):
"""
K-means image segmentation that is a wrapper around `ants.atropos`
ANTsR function: `kmeansSegmentation`
Arguments
---------
image : ANTsImage
input image
k : integer
integer number of classes
kmask : ANTsImage (optional)
segment inside this mask
mrf : scalar
smoothness, higher is smoother
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'), 'float')
>>> fi = ants.n3_bias_field_correction(fi, 2)
>>> seg = ants.kmeans_segmentation(fi, 3)
"""
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']*dim)
mrf = '[%s,%s]' % (str(mrf), nhood)
kmimage = atropos(a = kmimage, m = mrf, c = '[5,0]', i = 'kmeans[%s]'%(str(k)), x = kmask)
kmimage['segmentation'] = kmimage['segmentation'].clone(image.pixeltype)
return kmimage | [
"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'",
"]",
"*",
"dim",
")",
"mrf",
"=",
"'[%s,%s]'",
"%",
"(",
"str",
"(",
"mrf",
")",
",",
"nhood",
")",
"kmimage",
"=",
"atropos",
"(",
"a",
"=",
"kmimage",
",",
"m",
"=",
"mrf",
",",
"c",
"=",
"'[5,0]'",
",",
"i",
"=",
"'kmeans[%s]'",
"%",
"(",
"str",
"(",
"k",
")",
")",
",",
"x",
"=",
"kmask",
")",
"kmimage",
"[",
"'segmentation'",
"]",
"=",
"kmimage",
"[",
"'segmentation'",
"]",
".",
"clone",
"(",
"image",
".",
"pixeltype",
")",
"return",
"kmimage"
] | K-means image segmentation that is a wrapper around `ants.atropos`
ANTsR function: `kmeansSegmentation`
Arguments
---------
image : ANTsImage
input image
k : integer
integer number of classes
kmask : ANTsImage (optional)
segment inside this mask
mrf : scalar
smoothness, higher is smoother
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read(ants.get_ants_data('r16'), 'float')
>>> fi = ants.n3_bias_field_correction(fi, 2)
>>> seg = ants.kmeans_segmentation(fi, 3) | [
"K",
"-",
"means",
"image",
"segmentation",
"that",
"is",
"a",
"wrapper",
"around",
"ants",
".",
"atropos"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/segmentation/kmeans.py#L9-L49 | train | 232,078 |
ANTsX/ANTsPy | ants/registration/reorient_image.py | reorient_image2 | def reorient_image2(image, orientation='RAS'):
"""
Reorient an image.
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = mni.reorient_image2()
"""
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 = libfn(image.pointer, orientation)
new_img = iio.ANTsImage(pixeltype='float', dimension=ndim,
components=image.components, pointer=itkimage)#.clone(inpixeltype)
if inpixeltype != 'float':
new_img = new_img.clone(inpixeltype)
return new_img | python | def reorient_image2(image, orientation='RAS'):
"""
Reorient an image.
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = mni.reorient_image2()
"""
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 = libfn(image.pointer, orientation)
new_img = iio.ANTsImage(pixeltype='float', dimension=ndim,
components=image.components, pointer=itkimage)#.clone(inpixeltype)
if inpixeltype != 'float':
new_img = new_img.clone(inpixeltype)
return new_img | [
"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",
"=",
"libfn",
"(",
"image",
".",
"pointer",
",",
"orientation",
")",
"new_img",
"=",
"iio",
".",
"ANTsImage",
"(",
"pixeltype",
"=",
"'float'",
",",
"dimension",
"=",
"ndim",
",",
"components",
"=",
"image",
".",
"components",
",",
"pointer",
"=",
"itkimage",
")",
"#.clone(inpixeltype)",
"if",
"inpixeltype",
"!=",
"'float'",
":",
"new_img",
"=",
"new_img",
".",
"clone",
"(",
"inpixeltype",
")",
"return",
"new_img"
] | Reorient an image.
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = mni.reorient_image2() | [
"Reorient",
"an",
"image",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/reorient_image.py#L56-L82 | train | 232,079 |
ANTsX/ANTsPy | ants/registration/reorient_image.py | reorient_image | def reorient_image(image, axis1, axis2=None, doreflection=False, doscale=0, txfn=None):
"""
Align image along a specified axis
ANTsR function: `reorientImage`
Arguments
---------
image : ANTsImage
image to reorient
axis1 : list/tuple of integers
vector of size dim, might need to play w/axis sign
axis2 : list/tuple of integers
vector of size dim for 3D
doreflection : boolean
whether to reflect
doscale : scalar value
1 allows automated estimate of scaling
txfn : string
file name for transformation
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> ants.reorient_image(image, (1,0))
"""
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(axis1)
axis2 = np.array(axis2)
axis1 = axis1 / np.sqrt(np.sum(axis1*axis1)) * (-1)
axis1 = axis1.astype('int')
if not axis_was_none:
axis2 = axis2 / np.sqrt(np.sum(axis2*axis2)) * (-1)
axis2 = axis2.astype('int')
else:
axis2 = np.array([0]*image.dimension).astype('int')
if txfn is None:
txfn = mktemp(suffix='.mat')
if isinstance(doreflection, tuple):
doreflection = list(doreflection)
if not isinstance(doreflection, list):
doreflection = [doreflection]
if isinstance(doscale, tuple):
doscale = list(doscale)
if not isinstance(doscale, list):
doscale = [doscale]
if len(doreflection) == 1:
doreflection = [doreflection[0]]*image.dimension
if len(doscale) == 1:
doscale = [doscale[0]]*image.dimension
libfn = utils.get_lib_fn('reorientImage%s' % image._libsuffix)
libfn(image.pointer, txfn, axis1.tolist(), axis2.tolist(), doreflection, doscale)
image2 = apply_transforms(image, image, transformlist=[txfn])
if image.pixeltype != inpixeltype:
image2 = image2.clone(inpixeltype)
return {'reoimage':image2,
'txfn':txfn} | python | def reorient_image(image, axis1, axis2=None, doreflection=False, doscale=0, txfn=None):
"""
Align image along a specified axis
ANTsR function: `reorientImage`
Arguments
---------
image : ANTsImage
image to reorient
axis1 : list/tuple of integers
vector of size dim, might need to play w/axis sign
axis2 : list/tuple of integers
vector of size dim for 3D
doreflection : boolean
whether to reflect
doscale : scalar value
1 allows automated estimate of scaling
txfn : string
file name for transformation
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> ants.reorient_image(image, (1,0))
"""
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(axis1)
axis2 = np.array(axis2)
axis1 = axis1 / np.sqrt(np.sum(axis1*axis1)) * (-1)
axis1 = axis1.astype('int')
if not axis_was_none:
axis2 = axis2 / np.sqrt(np.sum(axis2*axis2)) * (-1)
axis2 = axis2.astype('int')
else:
axis2 = np.array([0]*image.dimension).astype('int')
if txfn is None:
txfn = mktemp(suffix='.mat')
if isinstance(doreflection, tuple):
doreflection = list(doreflection)
if not isinstance(doreflection, list):
doreflection = [doreflection]
if isinstance(doscale, tuple):
doscale = list(doscale)
if not isinstance(doscale, list):
doscale = [doscale]
if len(doreflection) == 1:
doreflection = [doreflection[0]]*image.dimension
if len(doscale) == 1:
doscale = [doscale[0]]*image.dimension
libfn = utils.get_lib_fn('reorientImage%s' % image._libsuffix)
libfn(image.pointer, txfn, axis1.tolist(), axis2.tolist(), doreflection, doscale)
image2 = apply_transforms(image, image, transformlist=[txfn])
if image.pixeltype != inpixeltype:
image2 = image2.clone(inpixeltype)
return {'reoimage':image2,
'txfn':txfn} | [
"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",
"(",
"axis1",
")",
"axis2",
"=",
"np",
".",
"array",
"(",
"axis2",
")",
"axis1",
"=",
"axis1",
"/",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"axis1",
"*",
"axis1",
")",
")",
"*",
"(",
"-",
"1",
")",
"axis1",
"=",
"axis1",
".",
"astype",
"(",
"'int'",
")",
"if",
"not",
"axis_was_none",
":",
"axis2",
"=",
"axis2",
"/",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"axis2",
"*",
"axis2",
")",
")",
"*",
"(",
"-",
"1",
")",
"axis2",
"=",
"axis2",
".",
"astype",
"(",
"'int'",
")",
"else",
":",
"axis2",
"=",
"np",
".",
"array",
"(",
"[",
"0",
"]",
"*",
"image",
".",
"dimension",
")",
".",
"astype",
"(",
"'int'",
")",
"if",
"txfn",
"is",
"None",
":",
"txfn",
"=",
"mktemp",
"(",
"suffix",
"=",
"'.mat'",
")",
"if",
"isinstance",
"(",
"doreflection",
",",
"tuple",
")",
":",
"doreflection",
"=",
"list",
"(",
"doreflection",
")",
"if",
"not",
"isinstance",
"(",
"doreflection",
",",
"list",
")",
":",
"doreflection",
"=",
"[",
"doreflection",
"]",
"if",
"isinstance",
"(",
"doscale",
",",
"tuple",
")",
":",
"doscale",
"=",
"list",
"(",
"doscale",
")",
"if",
"not",
"isinstance",
"(",
"doscale",
",",
"list",
")",
":",
"doscale",
"=",
"[",
"doscale",
"]",
"if",
"len",
"(",
"doreflection",
")",
"==",
"1",
":",
"doreflection",
"=",
"[",
"doreflection",
"[",
"0",
"]",
"]",
"*",
"image",
".",
"dimension",
"if",
"len",
"(",
"doscale",
")",
"==",
"1",
":",
"doscale",
"=",
"[",
"doscale",
"[",
"0",
"]",
"]",
"*",
"image",
".",
"dimension",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'reorientImage%s'",
"%",
"image",
".",
"_libsuffix",
")",
"libfn",
"(",
"image",
".",
"pointer",
",",
"txfn",
",",
"axis1",
".",
"tolist",
"(",
")",
",",
"axis2",
".",
"tolist",
"(",
")",
",",
"doreflection",
",",
"doscale",
")",
"image2",
"=",
"apply_transforms",
"(",
"image",
",",
"image",
",",
"transformlist",
"=",
"[",
"txfn",
"]",
")",
"if",
"image",
".",
"pixeltype",
"!=",
"inpixeltype",
":",
"image2",
"=",
"image2",
".",
"clone",
"(",
"inpixeltype",
")",
"return",
"{",
"'reoimage'",
":",
"image2",
",",
"'txfn'",
":",
"txfn",
"}"
] | Align image along a specified axis
ANTsR function: `reorientImage`
Arguments
---------
image : ANTsImage
image to reorient
axis1 : list/tuple of integers
vector of size dim, might need to play w/axis sign
axis2 : list/tuple of integers
vector of size dim for 3D
doreflection : boolean
whether to reflect
doscale : scalar value
1 allows automated estimate of scaling
txfn : string
file name for transformation
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> image = ants.image_read(ants.get_ants_data('r16'))
>>> ants.reorient_image(image, (1,0)) | [
"Align",
"image",
"along",
"a",
"specified",
"axis"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/reorient_image.py#L85-L168 | train | 232,080 |
ANTsX/ANTsPy | ants/registration/reorient_image.py | get_center_of_mass | def get_center_of_mass(image):
"""
Compute an image center of mass in physical space which is defined
as the mean of the intensity weighted voxel coordinate system.
ANTsR function: `getCenterOfMass`
Arguments
---------
image : ANTsImage
image from which center of mass will be computed
Returns
-------
scalar
Example
-------
>>> fi = ants.image_read( ants.get_ants_data("r16"))
>>> com1 = ants.get_center_of_mass( fi )
>>> fi = ants.image_read( ants.get_ants_data("r64"))
>>> com2 = ants.get_center_of_mass( fi )
"""
if image.pixeltype != 'float':
image = image.clone('float')
libfn = utils.get_lib_fn('centerOfMass%s' % image._libsuffix)
com = libfn(image.pointer)
return tuple(com) | python | def get_center_of_mass(image):
"""
Compute an image center of mass in physical space which is defined
as the mean of the intensity weighted voxel coordinate system.
ANTsR function: `getCenterOfMass`
Arguments
---------
image : ANTsImage
image from which center of mass will be computed
Returns
-------
scalar
Example
-------
>>> fi = ants.image_read( ants.get_ants_data("r16"))
>>> com1 = ants.get_center_of_mass( fi )
>>> fi = ants.image_read( ants.get_ants_data("r64"))
>>> com2 = ants.get_center_of_mass( fi )
"""
if image.pixeltype != 'float':
image = image.clone('float')
libfn = utils.get_lib_fn('centerOfMass%s' % image._libsuffix)
com = libfn(image.pointer)
return tuple(com) | [
"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.
ANTsR function: `getCenterOfMass`
Arguments
---------
image : ANTsImage
image from which center of mass will be computed
Returns
-------
scalar
Example
-------
>>> fi = ants.image_read( ants.get_ants_data("r16"))
>>> com1 = ants.get_center_of_mass( fi )
>>> fi = ants.image_read( ants.get_ants_data("r64"))
>>> com2 = ants.get_center_of_mass( fi ) | [
"Compute",
"an",
"image",
"center",
"of",
"mass",
"in",
"physical",
"space",
"which",
"is",
"defined",
"as",
"the",
"mean",
"of",
"the",
"intensity",
"weighted",
"voxel",
"coordinate",
"system",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/reorient_image.py#L171-L200 | train | 232,081 |
ANTsX/ANTsPy | ants/utils/convert_nibabel.py | to_nibabel | def to_nibabel(image):
"""
Convert an ANTsImage to a 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([affine, np.array([0,0,0,1.])])
affine[:2,:] *= -1
new_img = nib.Nifti1Image(array_data, affine)
return new_img | python | def to_nibabel(image):
"""
Convert an ANTsImage to a 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([affine, np.array([0,0,0,1.])])
affine[:2,:] *= -1
new_img = nib.Nifti1Image(array_data, affine)
return new_img | [
"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",
"(",
"[",
"affine",
",",
"np",
".",
"array",
"(",
"[",
"0",
",",
"0",
",",
"0",
",",
"1.",
"]",
")",
"]",
")",
"affine",
"[",
":",
"2",
",",
":",
"]",
"*=",
"-",
"1",
"new_img",
"=",
"nib",
".",
"Nifti1Image",
"(",
"array_data",
",",
"affine",
")",
"return",
"new_img"
] | Convert an ANTsImage to a Nibabel image | [
"Convert",
"an",
"ANTsImage",
"to",
"a",
"Nibabel",
"image"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/convert_nibabel.py#L10-L23 | train | 232,082 |
ANTsX/ANTsPy | ants/utils/convert_nibabel.py | from_nibabel | def from_nibabel(nib_image):
"""
Convert a nibabel image to an ANTsImage
"""
tmpfile = mktemp(suffix='.nii.gz')
nib_image.to_filename(tmpfile)
new_img = iio2.image_read(tmpfile)
os.remove(tmpfile)
return new_img | python | def from_nibabel(nib_image):
"""
Convert a nibabel image to an ANTsImage
"""
tmpfile = mktemp(suffix='.nii.gz')
nib_image.to_filename(tmpfile)
new_img = iio2.image_read(tmpfile)
os.remove(tmpfile)
return new_img | [
"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 | [
"Convert",
"a",
"nibabel",
"image",
"to",
"an",
"ANTsImage"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/convert_nibabel.py#L26-L34 | train | 232,083 |
ANTsX/ANTsPy | ants/contrib/sampling/affine3d.py | RandomShear3D.transform | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
shear parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('ch2'))
>>> tx = ants.contrib.RandomShear3D(shear_range=(-10,10))
>>> img2 = tx.transform(img)
"""
# random draw in shear range
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, shear_y, shear_z)
tx = Shear3D((shear_x, shear_y, shear_z),
reference=self.reference,
lazy=self.lazy)
return tx.transform(X,y) | python | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
shear parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('ch2'))
>>> tx = ants.contrib.RandomShear3D(shear_range=(-10,10))
>>> img2 = tx.transform(img)
"""
# random draw in shear range
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, shear_y, shear_z)
tx = Shear3D((shear_x, shear_y, shear_z),
reference=self.reference,
lazy=self.lazy)
return tx.transform(X,y) | [
"def",
"transform",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"# random draw in shear range",
"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",
",",
"shear_y",
",",
"shear_z",
")",
"tx",
"=",
"Shear3D",
"(",
"(",
"shear_x",
",",
"shear_y",
",",
"shear_z",
")",
",",
"reference",
"=",
"self",
".",
"reference",
",",
"lazy",
"=",
"self",
".",
"lazy",
")",
"return",
"tx",
".",
"transform",
"(",
"X",
",",
"y",
")"
] | Transform an image using an Affine transform with
shear parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('ch2'))
>>> tx = ants.contrib.RandomShear3D(shear_range=(-10,10))
>>> img2 = tx.transform(img) | [
"Transform",
"an",
"image",
"using",
"an",
"Affine",
"transform",
"with",
"shear",
"parameters",
"randomly",
"generated",
"from",
"the",
"user",
"-",
"specified",
"range",
".",
"Return",
"the",
"transform",
"if",
"X",
"=",
"None",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine3d.py#L304-L339 | train | 232,084 |
ANTsX/ANTsPy | ants/contrib/sampling/affine3d.py | RandomZoom3D.transform | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
zoom parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('ch2'))
>>> tx = ants.contrib.RandomZoom3D(zoom_range=(0.8,0.9))
>>> img2 = tx.transform(img)
"""
# random draw in zoom range
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.log( self.zoom_range[0] ),
np.log( self.zoom_range[1] ) ) )
self.params = (zoom_x, zoom_y, zoom_z)
tx = Zoom3D((zoom_x,zoom_y,zoom_z),
reference=self.reference,
lazy=self.lazy)
return tx.transform(X,y) | python | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
zoom parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('ch2'))
>>> tx = ants.contrib.RandomZoom3D(zoom_range=(0.8,0.9))
>>> img2 = tx.transform(img)
"""
# random draw in zoom range
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.log( self.zoom_range[0] ),
np.log( self.zoom_range[1] ) ) )
self.params = (zoom_x, zoom_y, zoom_z)
tx = Zoom3D((zoom_x,zoom_y,zoom_z),
reference=self.reference,
lazy=self.lazy)
return tx.transform(X,y) | [
"def",
"transform",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"# random draw in zoom range",
"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",
".",
"log",
"(",
"self",
".",
"zoom_range",
"[",
"0",
"]",
")",
",",
"np",
".",
"log",
"(",
"self",
".",
"zoom_range",
"[",
"1",
"]",
")",
")",
")",
"self",
".",
"params",
"=",
"(",
"zoom_x",
",",
"zoom_y",
",",
"zoom_z",
")",
"tx",
"=",
"Zoom3D",
"(",
"(",
"zoom_x",
",",
"zoom_y",
",",
"zoom_z",
")",
",",
"reference",
"=",
"self",
".",
"reference",
",",
"lazy",
"=",
"self",
".",
"lazy",
")",
"return",
"tx",
".",
"transform",
"(",
"X",
",",
"y",
")"
] | Transform an image using an Affine transform with
zoom parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('ch2'))
>>> tx = ants.contrib.RandomZoom3D(zoom_range=(0.8,0.9))
>>> img2 = tx.transform(img) | [
"Transform",
"an",
"image",
"using",
"an",
"Affine",
"transform",
"with",
"zoom",
"parameters",
"randomly",
"generated",
"from",
"the",
"user",
"-",
"specified",
"range",
".",
"Return",
"the",
"transform",
"if",
"X",
"=",
"None",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine3d.py#L629-L670 | train | 232,085 |
ANTsX/ANTsPy | ants/contrib/sampling/affine2d.py | Translate2D.transform | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
translation parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Translate2D(translation=(10,0))
>>> img2_x = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(-10,0)) # other direction
>>> img2_x = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(0,10))
>>> img2_z = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(10,10))
>>> img2 = tx.transform(img)
"""
# convert to radians and unpack
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_to_image(X, reference=self.reference) | python | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
translation parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Translate2D(translation=(10,0))
>>> img2_x = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(-10,0)) # other direction
>>> img2_x = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(0,10))
>>> img2_z = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(10,10))
>>> img2 = tx.transform(img)
"""
# convert to radians and unpack
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_to_image(X, reference=self.reference) | [
"def",
"transform",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"# convert to radians and unpack",
"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_to_image",
"(",
"X",
",",
"reference",
"=",
"self",
".",
"reference",
")"
] | Transform an image using an Affine transform with the given
translation parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Translate2D(translation=(10,0))
>>> img2_x = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(-10,0)) # other direction
>>> img2_x = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(0,10))
>>> img2_z = tx.transform(img)
>>> tx = ants.contrib.Translate2D(translation=(10,10))
>>> img2 = tx.transform(img) | [
"Transform",
"an",
"image",
"using",
"an",
"Affine",
"transform",
"with",
"the",
"given",
"translation",
"parameters",
".",
"Return",
"the",
"transform",
"if",
"X",
"=",
"None",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine2d.py#L62-L101 | train | 232,086 |
ANTsX/ANTsPy | ants/contrib/sampling/affine2d.py | RandomTranslate2D.transform | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
translation parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.RandomShear2D(translation_range=(-10,10))
>>> img2 = tx.transform(img)
"""
# random draw in translation range
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((translation_x, translation_y),
reference=self.reference,
lazy=self.lazy)
return tx.transform(X,y) | python | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with
translation parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.RandomShear2D(translation_range=(-10,10))
>>> img2 = tx.transform(img)
"""
# random draw in translation range
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((translation_x, translation_y),
reference=self.reference,
lazy=self.lazy)
return tx.transform(X,y) | [
"def",
"transform",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"# random draw in translation range",
"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",
"(",
"(",
"translation_x",
",",
"translation_y",
")",
",",
"reference",
"=",
"self",
".",
"reference",
",",
"lazy",
"=",
"self",
".",
"lazy",
")",
"return",
"tx",
".",
"transform",
"(",
"X",
",",
"y",
")"
] | Transform an image using an Affine transform with
translation parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.RandomShear2D(translation_range=(-10,10))
>>> img2 = tx.transform(img) | [
"Transform",
"an",
"image",
"using",
"an",
"Affine",
"transform",
"with",
"translation",
"parameters",
"randomly",
"generated",
"from",
"the",
"user",
"-",
"specified",
"range",
".",
"Return",
"the",
"transform",
"if",
"X",
"=",
"None",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine2d.py#L141-L175 | train | 232,087 |
ANTsX/ANTsPy | ants/contrib/sampling/affine2d.py | Shear2D.transform | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
shear parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Shear2D(shear=(10,0,0))
>>> img2_x = tx.transform(img)# x axis stays same
>>> tx = ants.contrib.Shear2D(shear=(-10,0,0)) # other direction
>>> img2_x = tx.transform(img)# x axis stays same
>>> tx = ants.contrib.Shear2D(shear=(0,10,0))
>>> img2_y = tx.transform(img) # y axis stays same
>>> tx = ants.contrib.Shear2D(shear=(0,0,10))
>>> img2_z = tx.transform(img) # z axis stays same
>>> tx = ants.contrib.Shear2D(shear=(10,10,10))
>>> img2 = tx.transform(img)
"""
# convert to radians and unpack
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.apply_to_image(X, reference=self.reference) | python | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
shear parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Shear2D(shear=(10,0,0))
>>> img2_x = tx.transform(img)# x axis stays same
>>> tx = ants.contrib.Shear2D(shear=(-10,0,0)) # other direction
>>> img2_x = tx.transform(img)# x axis stays same
>>> tx = ants.contrib.Shear2D(shear=(0,10,0))
>>> img2_y = tx.transform(img) # y axis stays same
>>> tx = ants.contrib.Shear2D(shear=(0,0,10))
>>> img2_z = tx.transform(img) # z axis stays same
>>> tx = ants.contrib.Shear2D(shear=(10,10,10))
>>> img2 = tx.transform(img)
"""
# convert to radians and unpack
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.apply_to_image(X, reference=self.reference) | [
"def",
"transform",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"# convert to radians and unpack",
"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",
".",
"apply_to_image",
"(",
"X",
",",
"reference",
"=",
"self",
".",
"reference",
")"
] | Transform an image using an Affine transform with the given
shear parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Shear2D(shear=(10,0,0))
>>> img2_x = tx.transform(img)# x axis stays same
>>> tx = ants.contrib.Shear2D(shear=(-10,0,0)) # other direction
>>> img2_x = tx.transform(img)# x axis stays same
>>> tx = ants.contrib.Shear2D(shear=(0,10,0))
>>> img2_y = tx.transform(img) # y axis stays same
>>> tx = ants.contrib.Shear2D(shear=(0,0,10))
>>> img2_z = tx.transform(img) # z axis stays same
>>> tx = ants.contrib.Shear2D(shear=(10,10,10))
>>> img2 = tx.transform(img) | [
"Transform",
"an",
"image",
"using",
"an",
"Affine",
"transform",
"with",
"the",
"given",
"shear",
"parameters",
".",
"Return",
"the",
"transform",
"if",
"X",
"=",
"None",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine2d.py#L217-L259 | train | 232,088 |
ANTsX/ANTsPy | ants/contrib/sampling/affine2d.py | Zoom2D.transform | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
zoom parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Zoom2D(zoom=(0.8,0.8,0.8))
>>> img2 = tx.transform(img)
"""
# unpack zoom range
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, reference=self.reference) | python | def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
zoom parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Zoom2D(zoom=(0.8,0.8,0.8))
>>> img2 = tx.transform(img)
"""
# unpack zoom range
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, reference=self.reference) | [
"def",
"transform",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"# unpack zoom range",
"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",
",",
"reference",
"=",
"self",
".",
"reference",
")"
] | Transform an image using an Affine transform with the given
zoom parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image to transform
Returns
-------
ANTsImage if y is None, else a tuple of ANTsImage types
Examples
--------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> tx = ants.contrib.Zoom2D(zoom=(0.8,0.8,0.8))
>>> img2 = tx.transform(img) | [
"Transform",
"an",
"image",
"using",
"an",
"Affine",
"transform",
"with",
"the",
"given",
"zoom",
"parameters",
".",
"Return",
"the",
"transform",
"if",
"X",
"=",
"None",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine2d.py#L526-L560 | train | 232,089 |
ANTsX/ANTsPy | ants/segmentation/kelly_kapowski.py | kelly_kapowski | def kelly_kapowski(s, g, w, its=50, r=0.025, m=1.5, **kwargs):
"""
Compute cortical thickness using the DiReCT algorithm.
Diffeomorphic registration-based cortical thickness based on probabilistic
segmentation of an image. This is an optimization algorithm.
Arguments
---------
s : ANTsimage
segmentation image
g : ANTsImage
gray matter probability image
w : ANTsImage
white matter probability image
its : integer
convergence params - controls iterations
r : scalar
gradient descent update parameter
m : scalar
gradient field smoothing parameter
kwargs : keyword arguments
anything else, see KellyKapowski help in ANTs
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.image_read( ants.get_ants_data('r16') ,2)
>>> img = ants.resample_image(img, (64,64),1,0)
>>> mask = ants.get_mask( img )
>>> segs = ants.kmeans_segmentation( img, k=3, kmask = mask)
>>> thick = ants.kelly_kapowski(s=segs['segmentation'], g=segs['probabilityimages'][1],
w=segs['probabilityimages'][2], its=45,
r=0.5, m=1)
"""
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.items():
kellargs[k] = v
processed_kellargs = utils._int_antsProcessArguments(kellargs)
libfn = utils.get_lib_fn('KellyKapowski')
libfn(processed_kellargs)
return outimg | python | def kelly_kapowski(s, g, w, its=50, r=0.025, m=1.5, **kwargs):
"""
Compute cortical thickness using the DiReCT algorithm.
Diffeomorphic registration-based cortical thickness based on probabilistic
segmentation of an image. This is an optimization algorithm.
Arguments
---------
s : ANTsimage
segmentation image
g : ANTsImage
gray matter probability image
w : ANTsImage
white matter probability image
its : integer
convergence params - controls iterations
r : scalar
gradient descent update parameter
m : scalar
gradient field smoothing parameter
kwargs : keyword arguments
anything else, see KellyKapowski help in ANTs
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.image_read( ants.get_ants_data('r16') ,2)
>>> img = ants.resample_image(img, (64,64),1,0)
>>> mask = ants.get_mask( img )
>>> segs = ants.kmeans_segmentation( img, k=3, kmask = mask)
>>> thick = ants.kelly_kapowski(s=segs['segmentation'], g=segs['probabilityimages'][1],
w=segs['probabilityimages'][2], its=45,
r=0.5, m=1)
"""
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.items():
kellargs[k] = v
processed_kellargs = utils._int_antsProcessArguments(kellargs)
libfn = utils.get_lib_fn('KellyKapowski')
libfn(processed_kellargs)
return outimg | [
"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",
".",
"items",
"(",
")",
":",
"kellargs",
"[",
"k",
"]",
"=",
"v",
"processed_kellargs",
"=",
"utils",
".",
"_int_antsProcessArguments",
"(",
"kellargs",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'KellyKapowski'",
")",
"libfn",
"(",
"processed_kellargs",
")",
"return",
"outimg"
] | Compute cortical thickness using the DiReCT algorithm.
Diffeomorphic registration-based cortical thickness based on probabilistic
segmentation of an image. This is an optimization algorithm.
Arguments
---------
s : ANTsimage
segmentation image
g : ANTsImage
gray matter probability image
w : ANTsImage
white matter probability image
its : integer
convergence params - controls iterations
r : scalar
gradient descent update parameter
m : scalar
gradient field smoothing parameter
kwargs : keyword arguments
anything else, see KellyKapowski help in ANTs
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.image_read( ants.get_ants_data('r16') ,2)
>>> img = ants.resample_image(img, (64,64),1,0)
>>> mask = ants.get_mask( img )
>>> segs = ants.kmeans_segmentation( img, k=3, kmask = mask)
>>> thick = ants.kelly_kapowski(s=segs['segmentation'], g=segs['probabilityimages'][1],
w=segs['probabilityimages'][2], its=45,
r=0.5, m=1) | [
"Compute",
"cortical",
"thickness",
"using",
"the",
"DiReCT",
"algorithm",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/segmentation/kelly_kapowski.py#L11-L77 | train | 232,090 |
ANTsX/ANTsPy | ants/core/ants_transform_io.py | new_ants_transform | def new_ants_transform(precision='float', dimension=3, transform_type='AffineTransform', parameters=None):
"""
Create a new ANTsTransform
ANTsR function: None
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform()
"""
libfn = utils.get_lib_fn('newAntsTransform%s%i' % (utils.short_ptype(precision), dimension))
itk_tx = libfn(precision, dimension, transform_type)
ants_tx = tio.ANTsTransform(precision=precision, dimension=dimension,
transform_type=transform_type, pointer=itk_tx)
if parameters is not None:
ants_tx.set_parameters(parameters)
return ants_tx | python | def new_ants_transform(precision='float', dimension=3, transform_type='AffineTransform', parameters=None):
"""
Create a new ANTsTransform
ANTsR function: None
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform()
"""
libfn = utils.get_lib_fn('newAntsTransform%s%i' % (utils.short_ptype(precision), dimension))
itk_tx = libfn(precision, dimension, transform_type)
ants_tx = tio.ANTsTransform(precision=precision, dimension=dimension,
transform_type=transform_type, pointer=itk_tx)
if parameters is not None:
ants_tx.set_parameters(parameters)
return ants_tx | [
"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",
"(",
"precision",
"=",
"precision",
",",
"dimension",
"=",
"dimension",
",",
"transform_type",
"=",
"transform_type",
",",
"pointer",
"=",
"itk_tx",
")",
"if",
"parameters",
"is",
"not",
"None",
":",
"ants_tx",
".",
"set_parameters",
"(",
"parameters",
")",
"return",
"ants_tx"
] | Create a new ANTsTransform
ANTsR function: None
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform() | [
"Create",
"a",
"new",
"ANTsTransform"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform_io.py#L16-L35 | train | 232,091 |
ANTsX/ANTsPy | ants/core/ants_transform_io.py | create_ants_transform | 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):
"""
Create and initialize an ANTsTransform
ANTsR function: `createAntsrTransform`
Arguments
---------
transform_type : string
type of transform(s)
precision : string
numerical precision
dimension : integer
spatial dimension of transform
matrix : ndarray
matrix for linear transforms
offset : tuple/list
offset for linear transforms
center : tuple/list
center for linear transforms
translation : tuple/list
translation for linear transforms
parameters : ndarray/list
array of parameters
fixed_parameters : ndarray/list
array of fixed parameters
displacement_field : ANTsImage
multichannel ANTsImage for non-linear transform
supported_types : boolean
flag that returns array of possible transforms types
Returns
-------
ANTsTransform or list of ANTsTransform types
Example
-------
>>> import ants
>>> translation = (3,4,5)
>>> tx = ants.create_ants_transform( type='Euler3DTransform', translation=translation )
"""
def _check_arg(arg, dim=1):
if arg is None:
if dim == 1:
return []
elif dim == 2:
return [[]]
elif isinstance(arg, np.ndarray):
return arg.tolist()
elif isinstance(arg, (tuple, list)):
return list(arg)
else:
raise ValueError('Incompatible input argument')
matrix = _check_arg(matrix, dim=2)
offset = _check_arg(offset)
center = _check_arg(center)
translation = _check_arg(translation)
parameters = _check_arg(parameters)
fixed_parameters = _check_arg(fixed_parameters)
matrix_offset_types = {'AffineTransform', 'CenteredAffineTransform',
'Euler2DTransform', 'Euler3DTransform', 'Rigid3DTransform',
'Rigid2DTransform', 'QuaternionRigidTransform',
'Similarity2DTransform', 'CenteredSimilarity2DTransform',
'Similarity3DTransform', 'CenteredRigid2DTransform',
'CenteredEuler3DTransform'}
#user_matrix_types = {'Affine','CenteredAffine',
# 'Euler', 'CenteredEuler',
# 'Rigid', 'CenteredRigid', 'QuaternionRigid',
# 'Similarity', 'CenteredSimilarity'}
if supported_types:
return set(list(matrix_offset_types) + ['DisplacementFieldTransform'])
# Check for valid dimension
if (dimension < 2) or (dimension > 4):
raise ValueError('Unsupported dimension: %i' % dimension)
# Check for valid precision
precision_types = ('float', 'double')
if precision not in precision_types:
raise ValueError('Unsupported Precision %s' % str(precision))
# Check for supported transform type
if (transform_type not in matrix_offset_types) and (transform_type != 'DisplacementFieldTransform'):
raise ValueError('Unsupported type %s' % str(transform_type))
# Check parameters with type
if (transform_type=='Euler3DTransform'):
dimension = 3
elif (transform_type=='Euler2DTransform'):
dimension = 2
elif (transform_type=='Rigid3DTransform'):
dimension = 3
elif (transform_type=='QuaternionRigidTransform'):
dimension = 3
elif (transform_type=='Rigid2DTransform'):
dimension = 2
elif (transform_type=='CenteredRigid2DTransform'):
dimension = 2
elif (transform_type=='CenteredEuler3DTransform'):
dimension = 3
elif (transform_type=='Similarity3DTransform'):
dimension = 3
elif (transform_type=='Similarity2DTransform'):
dimension = 2
elif (transform_type=='CenteredSimilarity2DTransform'):
dimension = 2
# If displacement field
if displacement_field is not None:
raise ValueError('Displacement field transform not currently supported')
# itk_tx = transform_from_displacement_field(displacement_field)
# return tio.ants_transform(itk_tx)
# Transforms that derive from itk::MatrixOffsetTransformBase
libfn = utils.get_lib_fn('matrixOffset%s%i' % (utils.short_ptype(precision), dimension))
itk_tx = libfn(transform_type,
precision,
dimension,
matrix,
offset,
center,
translation,
parameters,
fixed_parameters)
return tio.ANTsTransform(precision=precision, dimension=dimension,
transform_type=transform_type, pointer=itk_tx) | python | 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):
"""
Create and initialize an ANTsTransform
ANTsR function: `createAntsrTransform`
Arguments
---------
transform_type : string
type of transform(s)
precision : string
numerical precision
dimension : integer
spatial dimension of transform
matrix : ndarray
matrix for linear transforms
offset : tuple/list
offset for linear transforms
center : tuple/list
center for linear transforms
translation : tuple/list
translation for linear transforms
parameters : ndarray/list
array of parameters
fixed_parameters : ndarray/list
array of fixed parameters
displacement_field : ANTsImage
multichannel ANTsImage for non-linear transform
supported_types : boolean
flag that returns array of possible transforms types
Returns
-------
ANTsTransform or list of ANTsTransform types
Example
-------
>>> import ants
>>> translation = (3,4,5)
>>> tx = ants.create_ants_transform( type='Euler3DTransform', translation=translation )
"""
def _check_arg(arg, dim=1):
if arg is None:
if dim == 1:
return []
elif dim == 2:
return [[]]
elif isinstance(arg, np.ndarray):
return arg.tolist()
elif isinstance(arg, (tuple, list)):
return list(arg)
else:
raise ValueError('Incompatible input argument')
matrix = _check_arg(matrix, dim=2)
offset = _check_arg(offset)
center = _check_arg(center)
translation = _check_arg(translation)
parameters = _check_arg(parameters)
fixed_parameters = _check_arg(fixed_parameters)
matrix_offset_types = {'AffineTransform', 'CenteredAffineTransform',
'Euler2DTransform', 'Euler3DTransform', 'Rigid3DTransform',
'Rigid2DTransform', 'QuaternionRigidTransform',
'Similarity2DTransform', 'CenteredSimilarity2DTransform',
'Similarity3DTransform', 'CenteredRigid2DTransform',
'CenteredEuler3DTransform'}
#user_matrix_types = {'Affine','CenteredAffine',
# 'Euler', 'CenteredEuler',
# 'Rigid', 'CenteredRigid', 'QuaternionRigid',
# 'Similarity', 'CenteredSimilarity'}
if supported_types:
return set(list(matrix_offset_types) + ['DisplacementFieldTransform'])
# Check for valid dimension
if (dimension < 2) or (dimension > 4):
raise ValueError('Unsupported dimension: %i' % dimension)
# Check for valid precision
precision_types = ('float', 'double')
if precision not in precision_types:
raise ValueError('Unsupported Precision %s' % str(precision))
# Check for supported transform type
if (transform_type not in matrix_offset_types) and (transform_type != 'DisplacementFieldTransform'):
raise ValueError('Unsupported type %s' % str(transform_type))
# Check parameters with type
if (transform_type=='Euler3DTransform'):
dimension = 3
elif (transform_type=='Euler2DTransform'):
dimension = 2
elif (transform_type=='Rigid3DTransform'):
dimension = 3
elif (transform_type=='QuaternionRigidTransform'):
dimension = 3
elif (transform_type=='Rigid2DTransform'):
dimension = 2
elif (transform_type=='CenteredRigid2DTransform'):
dimension = 2
elif (transform_type=='CenteredEuler3DTransform'):
dimension = 3
elif (transform_type=='Similarity3DTransform'):
dimension = 3
elif (transform_type=='Similarity2DTransform'):
dimension = 2
elif (transform_type=='CenteredSimilarity2DTransform'):
dimension = 2
# If displacement field
if displacement_field is not None:
raise ValueError('Displacement field transform not currently supported')
# itk_tx = transform_from_displacement_field(displacement_field)
# return tio.ants_transform(itk_tx)
# Transforms that derive from itk::MatrixOffsetTransformBase
libfn = utils.get_lib_fn('matrixOffset%s%i' % (utils.short_ptype(precision), dimension))
itk_tx = libfn(transform_type,
precision,
dimension,
matrix,
offset,
center,
translation,
parameters,
fixed_parameters)
return tio.ANTsTransform(precision=precision, dimension=dimension,
transform_type=transform_type, pointer=itk_tx) | [
"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",
"None",
":",
"if",
"dim",
"==",
"1",
":",
"return",
"[",
"]",
"elif",
"dim",
"==",
"2",
":",
"return",
"[",
"[",
"]",
"]",
"elif",
"isinstance",
"(",
"arg",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"arg",
".",
"tolist",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"list",
"(",
"arg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Incompatible input argument'",
")",
"matrix",
"=",
"_check_arg",
"(",
"matrix",
",",
"dim",
"=",
"2",
")",
"offset",
"=",
"_check_arg",
"(",
"offset",
")",
"center",
"=",
"_check_arg",
"(",
"center",
")",
"translation",
"=",
"_check_arg",
"(",
"translation",
")",
"parameters",
"=",
"_check_arg",
"(",
"parameters",
")",
"fixed_parameters",
"=",
"_check_arg",
"(",
"fixed_parameters",
")",
"matrix_offset_types",
"=",
"{",
"'AffineTransform'",
",",
"'CenteredAffineTransform'",
",",
"'Euler2DTransform'",
",",
"'Euler3DTransform'",
",",
"'Rigid3DTransform'",
",",
"'Rigid2DTransform'",
",",
"'QuaternionRigidTransform'",
",",
"'Similarity2DTransform'",
",",
"'CenteredSimilarity2DTransform'",
",",
"'Similarity3DTransform'",
",",
"'CenteredRigid2DTransform'",
",",
"'CenteredEuler3DTransform'",
"}",
"#user_matrix_types = {'Affine','CenteredAffine', ",
"# 'Euler', 'CenteredEuler',",
"# 'Rigid', 'CenteredRigid', 'QuaternionRigid',",
"# 'Similarity', 'CenteredSimilarity'}",
"if",
"supported_types",
":",
"return",
"set",
"(",
"list",
"(",
"matrix_offset_types",
")",
"+",
"[",
"'DisplacementFieldTransform'",
"]",
")",
"# Check for valid dimension",
"if",
"(",
"dimension",
"<",
"2",
")",
"or",
"(",
"dimension",
">",
"4",
")",
":",
"raise",
"ValueError",
"(",
"'Unsupported dimension: %i'",
"%",
"dimension",
")",
"# Check for valid precision",
"precision_types",
"=",
"(",
"'float'",
",",
"'double'",
")",
"if",
"precision",
"not",
"in",
"precision_types",
":",
"raise",
"ValueError",
"(",
"'Unsupported Precision %s'",
"%",
"str",
"(",
"precision",
")",
")",
"# Check for supported transform type",
"if",
"(",
"transform_type",
"not",
"in",
"matrix_offset_types",
")",
"and",
"(",
"transform_type",
"!=",
"'DisplacementFieldTransform'",
")",
":",
"raise",
"ValueError",
"(",
"'Unsupported type %s'",
"%",
"str",
"(",
"transform_type",
")",
")",
"# Check parameters with type",
"if",
"(",
"transform_type",
"==",
"'Euler3DTransform'",
")",
":",
"dimension",
"=",
"3",
"elif",
"(",
"transform_type",
"==",
"'Euler2DTransform'",
")",
":",
"dimension",
"=",
"2",
"elif",
"(",
"transform_type",
"==",
"'Rigid3DTransform'",
")",
":",
"dimension",
"=",
"3",
"elif",
"(",
"transform_type",
"==",
"'QuaternionRigidTransform'",
")",
":",
"dimension",
"=",
"3",
"elif",
"(",
"transform_type",
"==",
"'Rigid2DTransform'",
")",
":",
"dimension",
"=",
"2",
"elif",
"(",
"transform_type",
"==",
"'CenteredRigid2DTransform'",
")",
":",
"dimension",
"=",
"2",
"elif",
"(",
"transform_type",
"==",
"'CenteredEuler3DTransform'",
")",
":",
"dimension",
"=",
"3",
"elif",
"(",
"transform_type",
"==",
"'Similarity3DTransform'",
")",
":",
"dimension",
"=",
"3",
"elif",
"(",
"transform_type",
"==",
"'Similarity2DTransform'",
")",
":",
"dimension",
"=",
"2",
"elif",
"(",
"transform_type",
"==",
"'CenteredSimilarity2DTransform'",
")",
":",
"dimension",
"=",
"2",
"# If displacement field",
"if",
"displacement_field",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Displacement field transform not currently supported'",
")",
"# itk_tx = transform_from_displacement_field(displacement_field)",
"# return tio.ants_transform(itk_tx)",
"# Transforms that derive from itk::MatrixOffsetTransformBase",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'matrixOffset%s%i'",
"%",
"(",
"utils",
".",
"short_ptype",
"(",
"precision",
")",
",",
"dimension",
")",
")",
"itk_tx",
"=",
"libfn",
"(",
"transform_type",
",",
"precision",
",",
"dimension",
",",
"matrix",
",",
"offset",
",",
"center",
",",
"translation",
",",
"parameters",
",",
"fixed_parameters",
")",
"return",
"tio",
".",
"ANTsTransform",
"(",
"precision",
"=",
"precision",
",",
"dimension",
"=",
"dimension",
",",
"transform_type",
"=",
"transform_type",
",",
"pointer",
"=",
"itk_tx",
")"
] | Create and initialize an ANTsTransform
ANTsR function: `createAntsrTransform`
Arguments
---------
transform_type : string
type of transform(s)
precision : string
numerical precision
dimension : integer
spatial dimension of transform
matrix : ndarray
matrix for linear transforms
offset : tuple/list
offset for linear transforms
center : tuple/list
center for linear transforms
translation : tuple/list
translation for linear transforms
parameters : ndarray/list
array of parameters
fixed_parameters : ndarray/list
array of fixed parameters
displacement_field : ANTsImage
multichannel ANTsImage for non-linear transform
supported_types : boolean
flag that returns array of possible transforms types
Returns
-------
ANTsTransform or list of ANTsTransform types
Example
-------
>>> import ants
>>> translation = (3,4,5)
>>> tx = ants.create_ants_transform( type='Euler3DTransform', translation=translation ) | [
"Create",
"and",
"initialize",
"an",
"ANTsTransform"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform_io.py#L38-L187 | train | 232,092 |
ANTsX/ANTsPy | ants/core/ants_transform_io.py | read_transform | def read_transform(filename, dimension=2, precision='float'):
"""
Read a transform from file
ANTsR function: `readAntsrTransform`
Arguments
---------
filename : string
filename of transform
dimension : integer
spatial dimension of transform
precision : string
numerical precision of transform
Returns
-------
ANTsTransform
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform(dimension=2)
>>> tx.set_parameters((0.9,0,0,1.1,10,11))
>>> ants.write_transform(tx, '~/desktop/tx.mat')
>>> tx2 = ants.read_transform('~/desktop/tx.mat')
"""
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.get_lib_fn('getTransformNameFromFile')
transform_type = libfn2(filename)
libfn3 = utils.get_lib_fn('readTransform%s%i' % (utils.short_ptype(precision), dimension))
itk_tx = libfn3(filename, dimension, precision)
return tio.ANTsTransform(precision=precision, dimension=dimension,
transform_type=transform_type, pointer=itk_tx) | python | def read_transform(filename, dimension=2, precision='float'):
"""
Read a transform from file
ANTsR function: `readAntsrTransform`
Arguments
---------
filename : string
filename of transform
dimension : integer
spatial dimension of transform
precision : string
numerical precision of transform
Returns
-------
ANTsTransform
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform(dimension=2)
>>> tx.set_parameters((0.9,0,0,1.1,10,11))
>>> ants.write_transform(tx, '~/desktop/tx.mat')
>>> tx2 = ants.read_transform('~/desktop/tx.mat')
"""
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.get_lib_fn('getTransformNameFromFile')
transform_type = libfn2(filename)
libfn3 = utils.get_lib_fn('readTransform%s%i' % (utils.short_ptype(precision), dimension))
itk_tx = libfn3(filename, dimension, precision)
return tio.ANTsTransform(precision=precision, dimension=dimension,
transform_type=transform_type, pointer=itk_tx) | [
"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",
".",
"get_lib_fn",
"(",
"'getTransformNameFromFile'",
")",
"transform_type",
"=",
"libfn2",
"(",
"filename",
")",
"libfn3",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'readTransform%s%i'",
"%",
"(",
"utils",
".",
"short_ptype",
"(",
"precision",
")",
",",
"dimension",
")",
")",
"itk_tx",
"=",
"libfn3",
"(",
"filename",
",",
"dimension",
",",
"precision",
")",
"return",
"tio",
".",
"ANTsTransform",
"(",
"precision",
"=",
"precision",
",",
"dimension",
"=",
"dimension",
",",
"transform_type",
"=",
"transform_type",
",",
"pointer",
"=",
"itk_tx",
")"
] | Read a transform from file
ANTsR function: `readAntsrTransform`
Arguments
---------
filename : string
filename of transform
dimension : integer
spatial dimension of transform
precision : string
numerical precision of transform
Returns
-------
ANTsTransform
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform(dimension=2)
>>> tx.set_parameters((0.9,0,0,1.1,10,11))
>>> ants.write_transform(tx, '~/desktop/tx.mat')
>>> tx2 = ants.read_transform('~/desktop/tx.mat') | [
"Read",
"a",
"transform",
"from",
"file"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform_io.py#L223-L266 | train | 232,093 |
ANTsX/ANTsPy | ants/core/ants_transform_io.py | write_transform | def write_transform(transform, filename):
"""
Write ANTsTransform to file
ANTsR function: `writeAntsrTransform`
Arguments
---------
transform : ANTsTransform
transform to save
filename : string
filename of transform (file extension is ".mat" for affine transforms)
Returns
-------
N/A
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform(dimension=2)
>>> tx.set_parameters((0.9,0,0,1.1,10,11))
>>> ants.write_transform(tx, '~/desktop/tx.mat')
>>> tx2 = ants.read_transform('~/desktop/tx.mat')
"""
filename = os.path.expanduser(filename)
libfn = utils.get_lib_fn('writeTransform%s' % (transform._libsuffix))
libfn(transform.pointer, filename) | python | def write_transform(transform, filename):
"""
Write ANTsTransform to file
ANTsR function: `writeAntsrTransform`
Arguments
---------
transform : ANTsTransform
transform to save
filename : string
filename of transform (file extension is ".mat" for affine transforms)
Returns
-------
N/A
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform(dimension=2)
>>> tx.set_parameters((0.9,0,0,1.1,10,11))
>>> ants.write_transform(tx, '~/desktop/tx.mat')
>>> tx2 = ants.read_transform('~/desktop/tx.mat')
"""
filename = os.path.expanduser(filename)
libfn = utils.get_lib_fn('writeTransform%s' % (transform._libsuffix))
libfn(transform.pointer, filename) | [
"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
ANTsR function: `writeAntsrTransform`
Arguments
---------
transform : ANTsTransform
transform to save
filename : string
filename of transform (file extension is ".mat" for affine transforms)
Returns
-------
N/A
Example
-------
>>> import ants
>>> tx = ants.new_ants_transform(dimension=2)
>>> tx.set_parameters((0.9,0,0,1.1,10,11))
>>> ants.write_transform(tx, '~/desktop/tx.mat')
>>> tx2 = ants.read_transform('~/desktop/tx.mat') | [
"Write",
"ANTsTransform",
"to",
"file"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform_io.py#L269-L297 | train | 232,094 |
ANTsX/ANTsPy | ants/registration/reflect_image.py | reflect_image | def reflect_image(image, axis=None, tx=None, metric='mattes'):
"""
Reflect an image along an axis
ANTsR function: `reflectImage`
Arguments
---------
image : ANTsImage
image to reflect
axis : integer (optional)
which dimension to reflect across, numbered from 0 to imageDimension-1
tx : string (optional)
transformation type to estimate after reflection
metric : string
similarity metric for image registration. see antsRegistration.
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16'), 'float' )
>>> axis = 2
>>> asym = ants.reflect_image(fi, axis, 'Affine')['warpedmovout']
>>> asym = asym - fi
"""
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(image.pointer, axis, rflct)
if tx is not None:
rfi = registration(image, image, type_of_transform=tx,
syn_metric=metric, outprefix=mktemp(),
initial_transform=rflct)
return rfi
else:
return apply_transforms(image, image, rflct) | python | def reflect_image(image, axis=None, tx=None, metric='mattes'):
"""
Reflect an image along an axis
ANTsR function: `reflectImage`
Arguments
---------
image : ANTsImage
image to reflect
axis : integer (optional)
which dimension to reflect across, numbered from 0 to imageDimension-1
tx : string (optional)
transformation type to estimate after reflection
metric : string
similarity metric for image registration. see antsRegistration.
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16'), 'float' )
>>> axis = 2
>>> asym = ants.reflect_image(fi, axis, 'Affine')['warpedmovout']
>>> asym = asym - fi
"""
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(image.pointer, axis, rflct)
if tx is not None:
rfi = registration(image, image, type_of_transform=tx,
syn_metric=metric, outprefix=mktemp(),
initial_transform=rflct)
return rfi
else:
return apply_transforms(image, image, rflct) | [
"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",
"(",
"image",
".",
"pointer",
",",
"axis",
",",
"rflct",
")",
"if",
"tx",
"is",
"not",
"None",
":",
"rfi",
"=",
"registration",
"(",
"image",
",",
"image",
",",
"type_of_transform",
"=",
"tx",
",",
"syn_metric",
"=",
"metric",
",",
"outprefix",
"=",
"mktemp",
"(",
")",
",",
"initial_transform",
"=",
"rflct",
")",
"return",
"rfi",
"else",
":",
"return",
"apply_transforms",
"(",
"image",
",",
"image",
",",
"rflct",
")"
] | Reflect an image along an axis
ANTsR function: `reflectImage`
Arguments
---------
image : ANTsImage
image to reflect
axis : integer (optional)
which dimension to reflect across, numbered from 0 to imageDimension-1
tx : string (optional)
transformation type to estimate after reflection
metric : string
similarity metric for image registration. see antsRegistration.
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> fi = ants.image_read( ants.get_ants_data('r16'), 'float' )
>>> axis = 2
>>> asym = ants.reflect_image(fi, axis, 'Affine')['warpedmovout']
>>> asym = asym - fi | [
"Reflect",
"an",
"image",
"along",
"an",
"axis"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/reflect_image.py#L12-L61 | train | 232,095 |
ANTsX/ANTsPy | ants/contrib/bids/cohort.py | BIDSCohort.create_sampler | 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):
"""
Create a BIDSSampler that can be used to generate infinite augmented samples
"""
pass | python | 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):
"""
Create a BIDSSampler that can be used to generate infinite augmented samples
"""
pass | [
"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 | [
"Create",
"a",
"BIDSSampler",
"that",
"can",
"be",
"used",
"to",
"generate",
"infinite",
"augmented",
"samples"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/bids/cohort.py#L88-L94 | train | 232,096 |
ANTsX/ANTsPy | ants/utils/slice_image.py | slice_image | def slice_image(image, axis=None, idx=None):
"""
Slice an image.
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = ants.slice_image(mni, axis=1, idx=100)
"""
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)
itkimage = libfn(image.pointer, axis, idx)
return iio.ANTsImage(pixeltype='float', dimension=ndim-1,
components=image.components, pointer=itkimage).clone(inpixeltype) | python | def slice_image(image, axis=None, idx=None):
"""
Slice an image.
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = ants.slice_image(mni, axis=1, idx=100)
"""
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)
itkimage = libfn(image.pointer, axis, idx)
return iio.ANTsImage(pixeltype='float', dimension=ndim-1,
components=image.components, pointer=itkimage).clone(inpixeltype) | [
"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",
")",
"itkimage",
"=",
"libfn",
"(",
"image",
".",
"pointer",
",",
"axis",
",",
"idx",
")",
"return",
"iio",
".",
"ANTsImage",
"(",
"pixeltype",
"=",
"'float'",
",",
"dimension",
"=",
"ndim",
"-",
"1",
",",
"components",
"=",
"image",
".",
"components",
",",
"pointer",
"=",
"itkimage",
")",
".",
"clone",
"(",
"inpixeltype",
")"
] | Slice an image.
Example
-------
>>> import ants
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = ants.slice_image(mni, axis=1, idx=100) | [
"Slice",
"an",
"image",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/slice_image.py#L10-L32 | train | 232,097 |
ANTsX/ANTsPy | ants/utils/pad_image.py | pad_image | def pad_image(image, shape=None, pad_width=None, value=0.0, return_padvals=False):
"""
Pad an image to have the given shape or to be isotropic.
Arguments
---------
image : ANTsImage
image to pad
shape : tuple
- if shape is given, the image will be padded in each dimension
until it has this shape
- if shape is not given, the image will be padded along each
dimension to match the largest existing dimension so that it
has isotropic dimension
pad_width : list of
pad_value : scalar
value with which image will be padded
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> img2 = ants.pad_image(img, shape=(300,300))
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = ants.pad_image(mni)
>>> mni3 = ants.pad_image(mni, pad_width=[(0,4),(0,4),(0,4)])
>>> mni4 = ants.pad_image(mni, pad_width=(4,4,4))
"""
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
lower_pad_vals = [math.floor(max(ns-os,0)/2) for os,ns in zip(image.shape, shape)]
upper_pad_vals = [math.ceil(max(ns-os,0)/2) for os,ns in zip(image.shape, shape)]
else:
if shape is not None:
raise ValueError('Cannot give both `shape` and `pad_width`. Pick one!')
if len(pad_width) != image.dimension:
raise ValueError('Must give pad width for each image dimension')
lower_pad_vals = []
upper_pad_vals = []
for p in pad_width:
if isinstance(p, (list, tuple)):
lower_pad_vals.append(p[0])
upper_pad_vals.append(p[1])
else:
lower_pad_vals.append(math.floor(p/2))
upper_pad_vals.append(math.ceil(p/2))
libfn = utils.get_lib_fn('padImageF%i' % ndim)
itkimage = libfn(image.pointer, lower_pad_vals, upper_pad_vals, value)
new_image = iio.ANTsImage(pixeltype='float', dimension=ndim,
components=image.components, pointer=itkimage).clone(inpixeltype)
if return_padvals:
return new_image, lower_pad_vals, upper_pad_vals
else:
return new_image | python | def pad_image(image, shape=None, pad_width=None, value=0.0, return_padvals=False):
"""
Pad an image to have the given shape or to be isotropic.
Arguments
---------
image : ANTsImage
image to pad
shape : tuple
- if shape is given, the image will be padded in each dimension
until it has this shape
- if shape is not given, the image will be padded along each
dimension to match the largest existing dimension so that it
has isotropic dimension
pad_width : list of
pad_value : scalar
value with which image will be padded
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> img2 = ants.pad_image(img, shape=(300,300))
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = ants.pad_image(mni)
>>> mni3 = ants.pad_image(mni, pad_width=[(0,4),(0,4),(0,4)])
>>> mni4 = ants.pad_image(mni, pad_width=(4,4,4))
"""
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
lower_pad_vals = [math.floor(max(ns-os,0)/2) for os,ns in zip(image.shape, shape)]
upper_pad_vals = [math.ceil(max(ns-os,0)/2) for os,ns in zip(image.shape, shape)]
else:
if shape is not None:
raise ValueError('Cannot give both `shape` and `pad_width`. Pick one!')
if len(pad_width) != image.dimension:
raise ValueError('Must give pad width for each image dimension')
lower_pad_vals = []
upper_pad_vals = []
for p in pad_width:
if isinstance(p, (list, tuple)):
lower_pad_vals.append(p[0])
upper_pad_vals.append(p[1])
else:
lower_pad_vals.append(math.floor(p/2))
upper_pad_vals.append(math.ceil(p/2))
libfn = utils.get_lib_fn('padImageF%i' % ndim)
itkimage = libfn(image.pointer, lower_pad_vals, upper_pad_vals, value)
new_image = iio.ANTsImage(pixeltype='float', dimension=ndim,
components=image.components, pointer=itkimage).clone(inpixeltype)
if return_padvals:
return new_image, lower_pad_vals, upper_pad_vals
else:
return new_image | [
"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",
"lower_pad_vals",
"=",
"[",
"math",
".",
"floor",
"(",
"max",
"(",
"ns",
"-",
"os",
",",
"0",
")",
"/",
"2",
")",
"for",
"os",
",",
"ns",
"in",
"zip",
"(",
"image",
".",
"shape",
",",
"shape",
")",
"]",
"upper_pad_vals",
"=",
"[",
"math",
".",
"ceil",
"(",
"max",
"(",
"ns",
"-",
"os",
",",
"0",
")",
"/",
"2",
")",
"for",
"os",
",",
"ns",
"in",
"zip",
"(",
"image",
".",
"shape",
",",
"shape",
")",
"]",
"else",
":",
"if",
"shape",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Cannot give both `shape` and `pad_width`. Pick one!'",
")",
"if",
"len",
"(",
"pad_width",
")",
"!=",
"image",
".",
"dimension",
":",
"raise",
"ValueError",
"(",
"'Must give pad width for each image dimension'",
")",
"lower_pad_vals",
"=",
"[",
"]",
"upper_pad_vals",
"=",
"[",
"]",
"for",
"p",
"in",
"pad_width",
":",
"if",
"isinstance",
"(",
"p",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"lower_pad_vals",
".",
"append",
"(",
"p",
"[",
"0",
"]",
")",
"upper_pad_vals",
".",
"append",
"(",
"p",
"[",
"1",
"]",
")",
"else",
":",
"lower_pad_vals",
".",
"append",
"(",
"math",
".",
"floor",
"(",
"p",
"/",
"2",
")",
")",
"upper_pad_vals",
".",
"append",
"(",
"math",
".",
"ceil",
"(",
"p",
"/",
"2",
")",
")",
"libfn",
"=",
"utils",
".",
"get_lib_fn",
"(",
"'padImageF%i'",
"%",
"ndim",
")",
"itkimage",
"=",
"libfn",
"(",
"image",
".",
"pointer",
",",
"lower_pad_vals",
",",
"upper_pad_vals",
",",
"value",
")",
"new_image",
"=",
"iio",
".",
"ANTsImage",
"(",
"pixeltype",
"=",
"'float'",
",",
"dimension",
"=",
"ndim",
",",
"components",
"=",
"image",
".",
"components",
",",
"pointer",
"=",
"itkimage",
")",
".",
"clone",
"(",
"inpixeltype",
")",
"if",
"return_padvals",
":",
"return",
"new_image",
",",
"lower_pad_vals",
",",
"upper_pad_vals",
"else",
":",
"return",
"new_image"
] | Pad an image to have the given shape or to be isotropic.
Arguments
---------
image : ANTsImage
image to pad
shape : tuple
- if shape is given, the image will be padded in each dimension
until it has this shape
- if shape is not given, the image will be padded along each
dimension to match the largest existing dimension so that it
has isotropic dimension
pad_width : list of
pad_value : scalar
value with which image will be padded
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
>>> img2 = ants.pad_image(img, shape=(300,300))
>>> mni = ants.image_read(ants.get_data('mni'))
>>> mni2 = ants.pad_image(mni)
>>> mni3 = ants.pad_image(mni, pad_width=[(0,4),(0,4),(0,4)])
>>> mni4 = ants.pad_image(mni, pad_width=(4,4,4)) | [
"Pad",
"an",
"image",
"to",
"have",
"the",
"given",
"shape",
"or",
"to",
"be",
"isotropic",
"."
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/pad_image.py#L10-L75 | train | 232,098 |
ANTsX/ANTsPy | ants/core/ants_metric.py | ANTsImageToImageMetric.set_fixed_image | def set_fixed_image(self, image):
"""
Set Fixed ANTsImage for metric
"""
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.setFixedImage(image.pointer, False)
self.fixed_image = image | python | def set_fixed_image(self, image):
"""
Set Fixed ANTsImage for metric
"""
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.setFixedImage(image.pointer, False)
self.fixed_image = image | [
"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",
".",
"setFixedImage",
"(",
"image",
".",
"pointer",
",",
"False",
")",
"self",
".",
"fixed_image",
"=",
"image"
] | Set Fixed ANTsImage for metric | [
"Set",
"Fixed",
"ANTsImage",
"for",
"metric"
] | 638020af2cdfc5ff4bdb9809ffe67aa505727a3b | https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_metric.py#L48-L59 | train | 232,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.