1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
%extend itkPyVectorContainer@PyVectorContainerTypes@{
%pythoncode %{
def array_view_from_vector_container(vector_container):
"""Get a NumPy array view of an itk.VectorContainer.
Warning: No copy of the data is performed. Using an array
view after its source vector has been deleted can results in corrupt values
or a segfault.
"""
import itk
itksize = vector_container.Size()
container_type = itk.template(vector_container)
if isinstance(container_type[1][1], type):
container_element_type = itk.template(container_type[1][1])
dimension = container_element_type[1][1]
shape = (itksize, dimension)
else:
shape = (itksize,)
element_type = "@ElementType@"
numpydatatype = _get_numpy_pixelid(element_type)
memview = itkPyVectorContainer@PyVectorContainerTypes@._array_view_from_vector_container(vector_container)
ndarrview = np.asarray(memview).view(dtype = numpydatatype).reshape(shape).view(np.ndarray)
return ndarrview
array_view_from_vector_container = staticmethod(array_view_from_vector_container)
def array_from_vector_container(vector_container):
"""Get a NumPy ndarray from an itk.VectorContainer.
This is a deep copy of the itk.VectorContainer and is completely safe and without potential side effects.
"""
arrayView = itkPyVectorContainer@PyVectorContainerTypes@.array_view_from_vector_container(vector_container)
# perform deep copy of the buffer
return np.array(arrayView, copy=True)
array_from_vector_container = staticmethod(array_from_vector_container)
def vector_container_from_array(ndarr):
"""Get an itk.VectorContainer from a NumPy array.
This is a deep copy of the NumPy array buffer and is completely safe without potential
side effects.
"""
assert ndarr.ndim == 1 , "Only arrays of 1 dimension are supported."
vec = itkPyVectorContainer@PyVectorContainerTypes@._vector_container_from_array(ndarr, ndarr.shape)
return vec
vector_container_from_array = staticmethod(vector_container_from_array)
%}
};
|