1
14
15"""
16display a DICOM image with matPlotLib via numpy
17
18Caveats:
19- Does not support UINT12/INT12
20
21Usage:
22
23 python ConvertNumpy.py "IM000000"
24
25Thanks:
26 plotting example - Ray Schumacher 2009
27"""
28
29import gdcm
30import numpy
31from pylab import *
32
33
34def get_gdcm_to_numpy_typemap():
35 """Returns the GDCM Pixel Format to numpy array type mapping."""
36 _gdcm_np = {gdcm.PixelFormat.UINT8 :numpy.int8,
37 gdcm.PixelFormat.INT8 :numpy.uint8,
38 gdcm.PixelFormat.UINT16 :numpy.uint16,
39 gdcm.PixelFormat.INT16 :numpy.int16,
40 gdcm.PixelFormat.UINT32 :numpy.uint32,
41 gdcm.PixelFormat.INT32 :numpy.int32,
42 gdcm.PixelFormat.FLOAT32:numpy.float32,
43 gdcm.PixelFormat.FLOAT64:numpy.float64 }
44 return _gdcm_np
45
46def get_numpy_array_type(gdcm_pixel_format):
47 """Returns a numpy array typecode given a GDCM Pixel Format."""
48 return get_gdcm_to_numpy_typemap()[gdcm_pixel_format]
49
50def gdcm_to_numpy(image):
51 """Converts a GDCM image to a numpy array.
52 """
53 pf = image.GetPixelFormat().GetScalarType()
54 print 'pf', pf
55 print image.GetPixelFormat().GetScalarTypeAsString()
56 assert pf in get_gdcm_to_numpy_typemap().keys(), \
57 "Unsupported array type %s"%pf
58 d = image.GetDimension(0), image.GetDimension(1)
59 print 'Image Size: %d x %d' % (d[0], d[1])
60 dtype = get_numpy_array_type(pf)
61 gdcm_array = image.GetBuffer()
62
63 result = numpy.frombuffer(gdcm_array, dtype=dtype).astype(float)
64
68 result.shape = d
69 return result
70
71if __name__ == "__main__":
72 import sys
74 filename = sys.argv[1]
75 r.SetFileName( filename )
76 if not r.Read(): sys.exit(1)
77 numpy_array = gdcm_to_numpy( r.GetImage() )
78
79 subplot(111)
80 title(filename)
81
82 imshow(numpy_array, interpolation='bilinear', cmap=cm.jet)
83
84 subplots_adjust(bottom=0.1, right=0.8, top=0.9)
85 cax = axes([0.85, 0.1, 0.075, 0.8])
86 colorbar(cax=cax)
87 title('values')
88 get_current_fig_manager().window.title('plot')
89 show()
ImageReader.
Definition gdcmImageReader.h:34