GDCM 2.2.1

- Main Page
- Related Pages
- Namespaces
- Classes
- Files
- Examples

ConvertNumpy.py
1 ############################################################################
2 #
3 # Program: GDCM (Grassroots DICOM). A DICOM library
4 #
5 # Copyright (c) 2006-2011 Mathieu Malaterre
6 # All rights reserved.
7 # See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
8 #
9 # This software is distributed WITHOUT ANY WARRANTY; without even
10 # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
11 # PURPOSE. See the above copyright notice for more information.
12 #
13 ############################################################################
14
15 """
16 This module add support for converting a gdcm.Image to a numpy array.
17
18 Caveats:
19 - Does not support UINT12/INT12
20
21 Removed:
22 - float16 is defined in GDCM API but no implementation exist for it ...
23 """
24
25 import gdcm
26 import numpy
27
28 def get_gdcm_to_numpy_typemap():
29 """Returns the GDCM Pixel Format to numpy array type mapping."""
30 _gdcm_np = {gdcm.PixelFormat.UINT8 :numpy.int8,
31 gdcm.PixelFormat.INT8 :numpy.uint8,
32 #gdcm.PixelFormat.UINT12 :numpy.uint12,
33 #gdcm.PixelFormat.INT12 :numpy.int12,
34 gdcm.PixelFormat.UINT16 :numpy.uint16,
35 gdcm.PixelFormat.INT16 :numpy.int16,
36 gdcm.PixelFormat.UINT32 :numpy.uint32,
37 gdcm.PixelFormat.INT32 :numpy.int32,
38 #gdcm.PixelFormat.FLOAT16:numpy.float16,
39 gdcm.PixelFormat.FLOAT32:numpy.float32,
40 gdcm.PixelFormat.FLOAT64:numpy.float64 }
41 return _gdcm_np
42
43 def get_numpy_array_type(gdcm_pixel_format):
44 """Returns a numpy array typecode given a GDCM Pixel Format."""
45 return get_gdcm_to_numpy_typemap()[gdcm_pixel_format]
46
47 def gdcm_to_numpy(image):
48 """Converts a GDCM image to a numpy array.
49 """
50 pf = image.GetPixelFormat()
51
52 assert pf.GetScalarType() in get_gdcm_to_numpy_typemap().keys(), \
53 "Unsupported array type %s"%pf
54
55 shape = image.GetDimension(0) * image.GetDimension(1), pf.GetSamplesPerPixel()
56 if image.GetNumberOfDimensions() == 3:
57 shape = shape[0] * image.GetDimension(2), shape[1]
58
59 dtype = get_numpy_array_type(pf.GetScalarType())
60 gdcm_array = image.GetBuffer()
61 result = numpy.frombuffer(gdcm_array, dtype=dtype)
62 result.shape = shape
63 return result
64
65 if __name__ == "__main__":
66 import sys
67 r = gdcm.ImageReader()
68 filename = sys.argv[1]
69 r.SetFileName( filename )
70 if not r.Read():
71 sys.exit(1)
72
73 numpy_array = gdcm_to_numpy( r.GetImage() )
74 print numpy_array