simpleitk 2.5.0__cp310-cp310-macosx_10_9_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of simpleitk might be problematic. Click here for more details.

SimpleITK/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ # ========================================================================
2
+ #
3
+ # Copyright NumFOCUS
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0.txt
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+ # ========================================================================
18
+ from SimpleITK.SimpleITK import *
19
+ from SimpleITK.extra import *
20
+
21
+ from SimpleITK._version import __version__
SimpleITK/_version.py ADDED
@@ -0,0 +1,54 @@
1
+ # ========================================================================
2
+ #
3
+ # Copyright NumFOCUS
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0.txt
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+ # ========================================================================
18
+
19
+
20
+ def _get_pep386version():
21
+ """Uses configured CMake version variable to construct a pep 386 compliant version string."""
22
+
23
+ sitk_major = "2"
24
+ sitk_minor = "5"
25
+ sitk_patch = "0"
26
+ sitk_tweak = ""
27
+ sitk_rc = ""
28
+ sitk_post = ""
29
+ sitk_dev = ""
30
+ sitk_hash = "681c6"
31
+
32
+ version = sitk_major + "." + sitk_minor
33
+
34
+ if sitk_patch:
35
+ version += "." + sitk_patch
36
+ if sitk_tweak:
37
+ version += "." + sitk_tweak
38
+
39
+ if sitk_rc:
40
+ version += sitk_rc
41
+
42
+ if sitk_post:
43
+ version += ".post" + sitk_post
44
+ elif sitk_dev:
45
+ version += ".dev" + sitk_dev
46
+
47
+ # Local Version Identifier
48
+ if sitk_hash and "ON" not in ['1', 'ON']:
49
+ version += "+g" + sitk_hash
50
+
51
+ return version
52
+
53
+
54
+ __version__ = _get_pep386version()
SimpleITK/extra.py ADDED
@@ -0,0 +1,496 @@
1
+ # ========================================================================
2
+ #
3
+ # Copyright NumFOCUS
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0.txt
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+ # ========================================================================
18
+
19
+ from pathlib import Path
20
+ from SimpleITK.SimpleITK import *
21
+ from SimpleITK.SimpleITK import _GetMemoryViewFromImage
22
+ from SimpleITK.SimpleITK import _SetImageFromArray
23
+
24
+ from typing import Iterable, List, Optional, Type, Union, Tuple
25
+
26
+
27
+ PathType = Union[str, Path, Iterable[str], Iterable[Path]]
28
+
29
+
30
+ def MinimumMaximum(image: Image) -> Tuple[float, float]:
31
+ """
32
+ Computes the minimum and the maximum intensity values of an image.
33
+
34
+ This is a custom overloaded python method, which returns the minimum and maximum measurements as a tuple.
35
+
36
+ Also See
37
+ --------
38
+ itk::simple::MinimumMaximumImageFilter for the object-oriented interface
39
+
40
+ :param image:
41
+ :return:
42
+ """
43
+ f = MinimumMaximumImageFilter()
44
+ f.Execute(image)
45
+ return f.GetMinimum(), f.GetMaximum()
46
+
47
+
48
+ def Resample(
49
+ image1: Image,
50
+ *args,
51
+ referenceImage: Optional[Image] = None,
52
+ size: Optional[int] = None,
53
+ **kwargs,
54
+ ) -> Image:
55
+ """
56
+ Resample ( Image image1,
57
+ Transform transform = itk::simple::Transform(),
58
+ InterpolatorEnum interpolator = itk::simple::sitkLinear,
59
+ double defaultPixelValue = 0.0,
60
+ PixelIDValueEnum outputPixelType = itk::simple::sitkUnknown,
61
+ bool useNearestNeighborExtrapolator = false);
62
+
63
+ Resample ( Image image1,
64
+ Image referenceImage,
65
+ Transform transform = itk::simple::Transform(),
66
+ InterpolatorEnum interpolator = itk::simple::sitkLinear,
67
+ double defaultPixelValue = 0.0,
68
+ PixelIDValueEnum outputPixelType = sitkUnknown,
69
+ bool useNearestNeighborExtrapolator = false);
70
+
71
+ Resample ( const Image& image1,
72
+ VectorUInt32 size,
73
+ Transform transform = itk::simple::Transform(),
74
+ InterpolatorEnum interpolator = itk::simple::sitkLinear,
75
+ VectorDouble outputOrigin = std::vector<double>(3, 0.0),
76
+ VectorDouble outputSpacing = std::vector<double>(3, 1.0),
77
+ VectorDouble outputDirection = std::vector<double>(),
78
+ double defaultPixelValue = 0.0,
79
+ PixelIDValueEnum outputPixelType = sitkUnknown,
80
+ bool useNearestNeighborExtrapolator = false);
81
+
82
+ itk::simple::ResampleImageFilter procedural interface.
83
+
84
+ This is a custom overloaded python method, which fully supports the 3 signatures with positional and keyword
85
+ arguments. The second positional parameters without a default value are used to determine which overloaded
86
+ procedure signature to invoke.
87
+
88
+ """
89
+
90
+ def _r_image(
91
+ referenceImage,
92
+ transform=Transform(),
93
+ interpolator=sitkLinear,
94
+ defaultPixelValue=0.0,
95
+ outputPixelType=sitkUnknown,
96
+ useNearestNeighborExtrapolator=False,
97
+ ):
98
+ resampler = ResampleImageFilter()
99
+ resampler.SetReferenceImage(referenceImage)
100
+ resampler.SetTransform(transform)
101
+ resampler.SetInterpolator(interpolator)
102
+ resampler.SetDefaultPixelValue(defaultPixelValue)
103
+ resampler.SetOutputPixelType(outputPixelType)
104
+ resampler.SetUseNearestNeighborExtrapolator(useNearestNeighborExtrapolator)
105
+ return resampler.Execute(image1)
106
+
107
+ def _r(
108
+ size,
109
+ transform=Transform(),
110
+ interpolator=sitkLinear,
111
+ outputOrigin=(0.0, 0.0, 0.0),
112
+ outputSpacing=(1.0, 1.0, 1.0),
113
+ outputDirection=(),
114
+ defaultPixelValue=0.0,
115
+ outputPixelType=sitkUnknown,
116
+ useNearestNeighborExtrapolator=False,
117
+ ):
118
+ resampler = ResampleImageFilter()
119
+ resampler.SetSize(size)
120
+ resampler.SetTransform(transform)
121
+ resampler.SetInterpolator(interpolator)
122
+ resampler.SetOutputOrigin(outputOrigin)
123
+ resampler.SetOutputSpacing(outputSpacing)
124
+ resampler.SetOutputDirection(outputDirection)
125
+ resampler.SetDefaultPixelValue(defaultPixelValue)
126
+ resampler.SetOutputPixelType(outputPixelType)
127
+ resampler.SetUseNearestNeighborExtrapolator(useNearestNeighborExtrapolator)
128
+ return resampler.Execute(image1)
129
+
130
+ if args:
131
+ if isinstance(args[0], Image):
132
+ return _r_image(*args, **kwargs)
133
+ if not isinstance(args[0], Transform):
134
+ try:
135
+ iter(args[0])
136
+ except TypeError:
137
+ pass
138
+ else:
139
+ return _r(*args, **kwargs)
140
+
141
+ if referenceImage is not None:
142
+ return _r_image(referenceImage, *args, **kwargs)
143
+ if size is not None:
144
+ return _r(size, *args, **kwargs)
145
+
146
+ return _r_image(image1, *args, **kwargs)
147
+
148
+
149
+ HAVE_NUMPY = True
150
+ try:
151
+ import numpy
152
+ except ImportError:
153
+ HAVE_NUMPY = False
154
+
155
+
156
+ def _get_numpy_dtype(sitkImage: Image) -> Type["numpy.number"]:
157
+ """Given a SimpleITK image, returns the numpy.dtype which describes the data"""
158
+
159
+ if not HAVE_NUMPY:
160
+ raise ImportError("Numpy not available.")
161
+
162
+ np = numpy
163
+
164
+ # this is a mapping from sitk's pixel id to numpy's scalar types
165
+ _sitk_np = {
166
+ sitkUInt8: numpy.uint8,
167
+ sitkUInt16: numpy.uint16,
168
+ sitkUInt32: numpy.uint32,
169
+ sitkUInt64: numpy.uint64,
170
+ sitkInt8: numpy.int8,
171
+ sitkInt16: numpy.int16,
172
+ sitkInt32: numpy.int32,
173
+ sitkInt64: numpy.int64,
174
+ sitkFloat32: numpy.float32,
175
+ sitkFloat64: numpy.float64,
176
+ sitkComplexFloat32: numpy.complex64,
177
+ sitkComplexFloat64: numpy.complex128,
178
+ sitkVectorUInt8: numpy.uint8,
179
+ sitkVectorInt8: numpy.int8,
180
+ sitkVectorUInt16: numpy.uint16,
181
+ sitkVectorInt16: numpy.int16,
182
+ sitkVectorUInt32: numpy.uint32,
183
+ sitkVectorInt32: numpy.int32,
184
+ sitkVectorUInt64: numpy.uint64,
185
+ sitkVectorInt64: numpy.int64,
186
+ sitkVectorFloat32: numpy.float32,
187
+ sitkVectorFloat64: numpy.float64,
188
+ sitkLabelUInt8: numpy.uint8,
189
+ sitkLabelUInt16: numpy.uint16,
190
+ sitkLabelUInt32: numpy.uint32,
191
+ sitkLabelUInt64: numpy.uint64,
192
+ }
193
+
194
+ return _sitk_np[sitkImage.GetPixelIDValue()]
195
+
196
+
197
+ def _get_sitk_pixelid(numpy_array_type: Type["numpy.ndarray"]) -> int:
198
+ """Returns a SimpleITK PixelID given a numpy array."""
199
+
200
+ if not HAVE_NUMPY:
201
+ raise ImportError("Numpy not available.")
202
+
203
+ np = numpy
204
+
205
+ # This is a Mapping from numpy dtypes to sitk's pixel types.
206
+ _np_sitk = {
207
+ np.dtype(np.uint8): sitkUInt8,
208
+ np.dtype(np.uint16): sitkUInt16,
209
+ np.dtype(np.uint32): sitkUInt32,
210
+ np.dtype(np.uint64): sitkUInt64,
211
+ np.dtype(np.int8): sitkInt8,
212
+ np.dtype(np.int16): sitkInt16,
213
+ np.dtype(np.int32): sitkInt32,
214
+ np.dtype(np.int64): sitkInt64,
215
+ np.dtype(np.float32): sitkFloat32,
216
+ np.dtype(np.float64): sitkFloat64,
217
+ np.dtype(np.complex64): sitkComplexFloat32,
218
+ np.dtype(np.complex128): sitkComplexFloat64,
219
+ }
220
+ try:
221
+ return _np_sitk[numpy_array_type.dtype]
222
+ except KeyError:
223
+ raise TypeError("dtype: {0} is not supported.".format(numpy_array_type.dtype))
224
+
225
+
226
+ def _get_sitk_vector_pixelid(numpy_array_type: Type["numpy.ndarray"]) -> int:
227
+ """Returns a SimpleITK vector PixelID given a numpy array."""
228
+
229
+ if not HAVE_NUMPY:
230
+ raise ImportError("Numpy not available.")
231
+
232
+ np = numpy
233
+
234
+ # This is a Mapping from numpy dtypes to sitk's pixel types.
235
+ _np_sitk = {
236
+ np.dtype(np.uint8): sitkVectorUInt8,
237
+ np.dtype(np.uint16): sitkVectorUInt16,
238
+ np.dtype(np.uint32): sitkVectorUInt32,
239
+ np.dtype(np.uint64): sitkVectorUInt64,
240
+ np.dtype(np.int8): sitkVectorInt8,
241
+ np.dtype(np.int16): sitkVectorInt16,
242
+ np.dtype(np.int32): sitkVectorInt32,
243
+ np.dtype(np.int64): sitkVectorInt64,
244
+ np.dtype(np.float32): sitkVectorFloat32,
245
+ np.dtype(np.float64): sitkVectorFloat64,
246
+ }
247
+
248
+ try:
249
+ return _np_sitk[numpy_array_type.dtype]
250
+ except KeyError:
251
+ raise TypeError(
252
+ "dtype: {0} is not supported as an array.".format(numpy_array_type.dtype)
253
+ )
254
+
255
+
256
+ # SimplyITK <-> Numpy Array conversion support.
257
+
258
+
259
+ def GetArrayViewFromImage(image: Image) -> "numpy.ndarray":
260
+ """Get a NumPy ndarray view of a SimpleITK Image.
261
+
262
+ Returns a Numpy ndarray object as a "view" of the SimpleITK's Image buffer. This reduces pixel buffer copies, but
263
+ requires that the SimpleITK image object is kept around while the buffer is being used.
264
+ """
265
+
266
+ if not HAVE_NUMPY:
267
+ raise ImportError("NumPy not available.")
268
+
269
+ pixel_id = image.GetPixelIDValue()
270
+ assert (
271
+ pixel_id != sitkUnknown
272
+ ), "An SimpleITK image of Unknown pixel type should not exists!"
273
+
274
+ dtype = _get_numpy_dtype(image)
275
+
276
+ shape = image.GetSize()
277
+ if image.GetNumberOfComponentsPerPixel() > 1:
278
+ shape = (image.GetNumberOfComponentsPerPixel(),) + shape
279
+
280
+ image.MakeUnique()
281
+
282
+ image_memory_view = _GetMemoryViewFromImage(image)
283
+ array_view = numpy.asarray(image_memory_view).view(dtype=dtype)
284
+ array_view.shape = shape[::-1]
285
+
286
+ return array_view
287
+
288
+
289
+ def GetArrayFromImage(image: Image) -> "numpy.ndarray":
290
+ """Get a NumPy ndarray from a SimpleITK Image.
291
+
292
+ This is a deep copy of the image buffer and is completely safe and without potential side effects.
293
+ """
294
+
295
+ # TODO: If the image is already not unique then a second copy may be made before the numpy copy is done.
296
+ array_view = GetArrayViewFromImage(image)
297
+
298
+ # perform deep copy of the image buffer
299
+ return numpy.array(array_view, copy=True)
300
+
301
+
302
+ def GetImageFromArray(arr: "numpy.ndarray", isVector: Optional[bool] = None) -> Image:
303
+ """Get a SimpleITK Image from a numpy array.
304
+
305
+ If isVector is True, then the Image will have a Vector pixel type, and the last dimension of the array will be
306
+ considered the component index. By default when isVector is None, 4D arrays
307
+ are automatically considered 3D vector images, but 3D arrays are 3D images.
308
+ """
309
+
310
+ if not HAVE_NUMPY:
311
+ raise ImportError("Numpy not available.")
312
+
313
+ z = numpy.asarray(arr)
314
+
315
+ if isVector is None:
316
+ if z.ndim == 4 and z.dtype != numpy.complex64 and z.dtype != numpy.complex128:
317
+ isVector = True
318
+
319
+ if isVector:
320
+ id = _get_sitk_vector_pixelid(z)
321
+ if z.ndim > 2:
322
+ number_of_components = z.shape[-1]
323
+ shape = z.shape[-2::-1]
324
+ else:
325
+ number_of_components = 1
326
+ shape = z.shape[::-1]
327
+ else:
328
+ number_of_components = 1
329
+ id = _get_sitk_pixelid(z)
330
+ shape = z.shape[::-1]
331
+
332
+ # SimpleITK throws an exception if the image dimension is not supported
333
+ img = Image(shape, id, number_of_components)
334
+
335
+ _SetImageFromArray(z, img)
336
+
337
+ return img
338
+
339
+
340
+ def ReadImage(
341
+ fileName: PathType,
342
+ outputPixelType: int = sitkUnknown,
343
+ imageIO: str = "",
344
+ ) -> Image:
345
+ r"""ReadImage is a procedural interface to the ImageFileReader class which is convenient for most image reading
346
+ tasks.
347
+
348
+ This method can read a single image or a list of images into a volume.
349
+
350
+ Parameters
351
+ ----------
352
+ fileName
353
+ A single or a list of file names. the filename of an Image e.g. "cthead.mha"
354
+ outputPixelType
355
+ The pixel type of the returned Image. By default the value is sitkUnknown, which enable the output pixel type to
356
+ be same as the file. If the pixel type is specified then the itk::ConvertPixelBuffer will be used to convert the
357
+ pixels.
358
+ imageIO
359
+ The name of the ITK ImageIO to use to read the file. An option to override the automatically detected ImageIO used
360
+ to read the image. The available ImageIOs are listed by the GetRegisteredImageIOs method. If the ImageIO can not
361
+ be constructed an exception will be generated. If the ImageIO can not read the file an exception will be
362
+ generated.
363
+
364
+ Returns
365
+ -------
366
+ The provided image file name(s) read into an Image.
367
+
368
+ Also See
369
+ --------
370
+ itk::simple::ImageFileReader for reading a single file.
371
+ itk::simple::ImageSeriesReader for reading a series and meta-data dictionaries.
372
+
373
+ """
374
+
375
+ if isinstance(fileName, (str, Path)):
376
+ reader = ImageFileReader()
377
+ reader.SetFileName(fileName)
378
+ else:
379
+ reader = ImageSeriesReader()
380
+ reader.SetFileNames(fileName)
381
+
382
+ reader.SetImageIO(imageIO)
383
+ reader.SetOutputPixelType(outputPixelType)
384
+ return reader.Execute()
385
+
386
+
387
+ def WriteImage(
388
+ image: Image,
389
+ fileName: PathType,
390
+ useCompression: bool = False,
391
+ compressionLevel: int = -1,
392
+ *,
393
+ imageIO: str = "",
394
+ compressor: str = "",
395
+ ) -> None:
396
+ r"""
397
+ WriteImage is a procedural interface to the ImageFileWriter and ImageSeriesWriter classes which is convenient for
398
+ many image writing tasks.
399
+
400
+ For an input image of N dimensions, a series of N-1 dimensional (slices) images can be written by providing a list
401
+ if file names equal to the number of slices in the input image.
402
+
403
+ Parameters
404
+ ----------
405
+ image
406
+ the input image to be written
407
+ fileName
408
+ a single or a list of file names to be written
409
+ useCompression
410
+ request to compress the written file
411
+ compressionLevel
412
+ a hint for the amount of compression to be applied during writing
413
+ imageIO
414
+ the name of the ImageIO to perform the writing
415
+ compressor
416
+ a hint for the compression algorithm to use
417
+
418
+ Also See
419
+ --------
420
+ itk::simple::ImageFileWriter for writing a single file.
421
+ itk::simple::ImageSeriesWriter for writing a series of files
422
+ """
423
+ if isinstance(fileName, (str, Path)):
424
+ writer = ImageFileWriter()
425
+ writer.SetFileName(fileName)
426
+ else:
427
+ writer = ImageSeriesWriter()
428
+ writer.SetFileNames(fileName)
429
+
430
+ writer.SetUseCompression(useCompression)
431
+ writer.SetCompressionLevel(compressionLevel)
432
+ writer.SetImageIO(imageIO)
433
+ writer.SetCompressor(compressor)
434
+ return writer.Execute(image)
435
+
436
+
437
+ def SmoothingRecursiveGaussian(
438
+ image1: Image,
439
+ sigma: List[float] = [1] * 3,
440
+ normalizeAcrossScale: bool = False,
441
+ ) -> Image:
442
+ """Computes the smoothing of an image by convolution with
443
+ the Gaussian kernels implemented as IIR filters.
444
+
445
+ This function directly calls the execute method of SmoothingRecursiveGaussianImageFilter
446
+ in order to support a procedural API.
447
+
448
+ Also See
449
+ --------
450
+ itk::simple::SmoothingRecursiveGaussianImageFilter for the object oriented interface
451
+ """
452
+
453
+ f = SmoothingRecursiveGaussianImageFilter()
454
+ f.SetSigma(sigma)
455
+ f.SetNormalizeAcrossScale(normalizeAcrossScale)
456
+ return f.Execute(image1)
457
+
458
+
459
+ def DiscreteGaussian(
460
+ image1: Image,
461
+ variance: List[float] = [1] * 3,
462
+ maximumKernelWidth: int = 32,
463
+ maximumError: float = 0.01,
464
+ useImageSpacing: bool = True,
465
+ ) -> Image:
466
+ """Blurs an image by separable convolution with discrete
467
+ gaussian kernels. This filter performs Gaussian blurring by
468
+ separable convolution of an image and a discrete Gaussian
469
+ operator (kernel).
470
+
471
+ This function directly calls the execute method of DiscreteGaussianImageFilter
472
+ in order to support a procedural API.
473
+
474
+ Also See
475
+ --------
476
+ itk::simple::DiscreteGaussianImageFilter for the object oriented interface
477
+ """
478
+ f = DiscreteGaussianImageFilter()
479
+ f.SetVariance(variance)
480
+ f.SetMaximumKernelWidth(maximumKernelWidth)
481
+ f.SetMaximumError(maximumError)
482
+ f.SetUseImageSpacing(useImageSpacing)
483
+ return f.Execute(image1)
484
+
485
+
486
+ __all__ = [
487
+ "MinimumMaximum",
488
+ "Resample",
489
+ "GetArrayViewFromImage",
490
+ "GetArrayFromImage",
491
+ "GetImageFromArray",
492
+ "ReadImage",
493
+ "WriteImage",
494
+ "SmoothingRecursiveGaussian",
495
+ "DiscreteGaussian",
496
+ ]
SimpleITK/py.typed ADDED
File without changes