16 This module add support for converting a gdcm.Image to a numpy array.
19 - Does not support UINT12/INT12
22 - float16 is defined in GDCM API but no implementation exist for it ...
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.uint8,
31 gdcm.PixelFormat.INT8 :numpy.int8,
34 gdcm.PixelFormat.UINT16 :numpy.uint16,
35 gdcm.PixelFormat.INT16 :numpy.int16,
36 gdcm.PixelFormat.UINT32 :numpy.uint32,
37 gdcm.PixelFormat.INT32 :numpy.int32,
39 gdcm.PixelFormat.FLOAT32:numpy.float32,
40 gdcm.PixelFormat.FLOAT64:numpy.float64 }
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]
47 def gdcm_to_numpy(image):
48 """Converts a GDCM image to a numpy array.
50 pf = image.GetPixelFormat()
52 assert pf.GetScalarType()
in get_gdcm_to_numpy_typemap().keys(), \
53 "Unsupported array type %s"%pf
55 shape = image.GetDimension(0) * image.GetDimension(1), pf.GetSamplesPerPixel()
56 if image.GetNumberOfDimensions() == 3:
57 shape = shape[0] * image.GetDimension(2), shape[1]
59 dtype = get_numpy_array_type(pf.GetScalarType())
60 gdcm_array = image.GetBuffer()
61 result = numpy.frombuffer(gdcm_array, dtype=dtype)
65 if __name__ ==
"__main__":
68 filename = sys.argv[1]
69 r.SetFileName( filename )
73 numpy_array = gdcm_to_numpy( r.GetImage() )
ImageReader.
Definition: gdcmImageReader.h:34