SimpleITK  
AdvancedImageReading/AdvancedImageReading.py
1 #!/usr/bin/env python
2 # =========================================================================
3 #
4 # Copyright NumFOCUS
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0.txt
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 # =========================================================================
19 
20 """ An SimpleITK example demonstrating advanced image reading techniques. """
21 
22 import sys
23 
24 import SimpleITK as sitk
25 import numpy as np
26 
27 if len(sys.argv) < 2:
28  print("Wrong number of arguments.", file=sys.stderr)
29  print("Usage: " + __file__ + " image_file_name", file=sys.stderr)
30  sys.exit(1)
31 
32 # Read image information without reading the bulk data.
33 file_reader = sitk.ImageFileReader()
34 file_reader.SetFileName(sys.argv[1])
35 file_reader.ReadImageInformation()
36 print(f"image size: {file_reader.GetSize()}")
37 print(f"image spacing: {file_reader.GetSpacing()}")
38 
39 # Some files have a rich meta-data dictionary (e.g. DICOM)
40 for key in file_reader.GetMetaDataKeys():
41  print(key + ": " + file_reader.GetMetaData(key))
42 print("-" * 20)
43 
44 # When low on memory, we can incrementally work on sub-images. The following
45 # subtracts two images (ok, the same image) by reading them as multiple'
46 # sub-images.
47 
48 image1_file_name = sys.argv[1]
49 image2_file_name = sys.argv[1]
50 
51 parts = 5 # Number of sub-regions we use
52 
53 file_reader = sitk.ImageFileReader()
54 file_reader.SetFileName(image1_file_name)
55 file_reader.ReadImageInformation()
56 image_size = file_reader.GetSize()
57 
58 result_img = sitk.Image(
59  file_reader.GetSize(),
60  file_reader.GetPixelID(),
61  file_reader.GetNumberOfComponents(),
62 )
63 result_img.SetSpacing(file_reader.GetSpacing())
64 result_img.SetOrigin(file_reader.GetOrigin())
65 result_img.SetDirection(file_reader.GetDirection())
66 
67 extract_size = list(file_reader.GetSize())
68 extract_size[-1] = extract_size[-1] // parts
69 current_index = [0] * file_reader.GetDimension()
70 for i in range(parts):
71  if i == (parts - 1):
72  extract_size[-1] = image_size[-1] - current_index[-1]
73  file_reader.SetFileName(image1_file_name)
74  file_reader.SetExtractIndex(current_index)
75  file_reader.SetExtractSize(extract_size)
76  sub_image1 = file_reader.Execute()
77 
78  file_reader.SetFileName(image2_file_name)
79  file_reader.SetExtractIndex(current_index)
80  file_reader.SetExtractSize(extract_size)
81  sub_image2 = file_reader.Execute()
82  idx = [slice(None, None)] * file_reader.GetDimension()
83  idx[-1] = current_index[-1]
84  result_img[idx] = sub_image1 - sub_image2
85  current_index[-1] += extract_size[-1]
86 del sub_image1
87 del sub_image2
88 
89 # Check that our iterative approach is equivalent to reading the whole images.
90 if np.any(
91  sitk.GetArrayViewFromImage(
92  result_img - sitk.ReadImage(image1_file_name) + sitk.ReadImage(image2_file_name)
93  )
94 ):
95  print("Subtraction error.")
96  sys.exit(1)
97 sys.exit(0)
itk::simple::Image
The Image class for SimpleITK.
Definition: sitkImage.h:76
itk::simple::ImageFileReader
Read an image file and return a SimpleITK Image.
Definition: sitkImageFileReader.h:74
itk::simple::ReadImage
SITKIO_EXPORT Image ReadImage(const std::vector< PathType > &fileNames, PixelIDValueEnum outputPixelType=sitkUnknown, const std::string &imageIO="")
ReadImage is a procedural interface to the ImageSeriesReader class which is convenient for most image...