22
22
print ("Usage: " + sys .argv [0 ] + " <input_image> <output_image>" )
23
23
sys .exit (1 )
24
24
25
- input_file_name = sys .argv [1 ]
25
+ # Parse comamnd line arguments
26
+ input_file_name = sys .argv [1 ]
26
27
output_file_name = sys .argv [2 ]
27
28
28
29
# Read input image
29
- itk_image = itk .imread (input_file_name )
30
+ PixelType = itk .ctype ("unsigned char" )
31
+ ImageType = itk .Image [itk .UC , 2 ]
32
+ itk_image = itk .imread (input_file_name , PixelType )
33
+ OriginalRegion = itk_image .GetLargestPossibleRegion ()
34
+ OriginalSize = OriginalRegion .GetSize ()
30
35
31
- # Copy itk.Imag pixel data to numpy array
32
- np_array = itk .array_from_image (itk_image )
36
+ print (f"The size of the ITK image data read from the input file = { OriginalSize } \n " )
33
37
34
- # Convert the numpy array pixel data back to ITK
35
- itk_np_copy = itk .image_from_array (np_array )
38
+ # There are two ways to bridge the data structures.
39
+ # i) Give direct access to memory holding the data called "View" functions for displaying
40
+ # purpose. But you can't modify the data
41
+ np_view_array = itk .GetArrayViewFromImage (itk_image , ttype = ImageType )
42
+ print (f"The size of the NumPy array viewed from itk::Image = { np_view_array .shape } " )
36
43
37
- # Write out the numpy array as an ITK image
38
- itk .imwrite (itk_np_copy ,output_file_name )
44
+ # ii) Generate a copy of the data using using array_from_image function.
45
+ # You can then freely modify the data as it has no effect on the original ITK image.
46
+
47
+ # Copy itk.Image pixel data to numpy array
48
+ np_array = itk .GetArrayFromImage (itk_image , ttype = ImageType )
49
+ print (f"The size of the NumPy array copied from itk::Image = { np_array .shape } " )
50
+
51
+ # Create an ITK image from the numpy array and then write it out
52
+ itk_np = itk .GetImageFromArray (np .ascontiguousarray (np_array ))
53
+
54
+ region = itk_np .GetLargestPossibleRegion ()
55
+ size = region .GetSize ()
56
+ print (f"ITK image data size after convesion from NumPy = { size } \n " )
57
+
58
+ itk .imwrite (itk_np , output_file_name )
59
+
60
+
61
+ # The order of the indexes is according to the type of object the data is stored in.
62
+ # A numpy array is indexed by [row , col ] for 2D data or [slice , row , col ] for 3D data.
63
+ # While ITK image data is indexed by (x , y ) for 2D or (x , y , z ) for 3D data.
64
+ # To demonstrate here, we create a 2D pixel array data
65
+ # and access a pixel with the same indices
66
+
67
+ np_data = np .array ([[1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ]], np .int32 )
68
+ itk_np_view_data = itk .image_view_from_array (np_data )
69
+
70
+ print (f"ITK image data pixel value at [2,1] = { itk_np_view_data .GetPixel ([2 ,1 ])} " )
71
+ print (f"NumPy array pixel value at [2,1] = { np_data [2 ,1 ]} " )
0 commit comments