GDCM 3.2.1

ConvertPIL.py
1
14
15"""
16 save a DICOM image with PIL via numpy
17
18 Caveats:
19- Does not support UINT12/INT12
20
21 Usage:
22
23 python ConvertNumpy.py "IM000000"
24
25 Thanks:
26 plotting example - Ray Schumacher 2009
27"""
28
29 import gdcm
30 import numpy
31 from PIL import Image, ImageOps
32
33
34 def 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
46 def 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
50 def 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 result = numpy.frombuffer(gdcm_array, dtype=dtype)
63 maxV = float(result[result.argmax()])
64
67 result = numpy.log(result+50)
68 maxV = float(result[result.argmax()])
69 result = result*(2.**8/maxV)
70 result.shape = d
71 return result
72
73 if __name__ == "__main__":
74 import sys
75 r = gdcm.ImageReader()
76 filename = sys.argv[1]
77 r.SetFileName( filename )
78 if not r.Read(): sys.exit(1)
79 numpy_array = gdcm_to_numpy( r.GetImage() )
80
82 pilImage = Image.frombuffer('L',
83 numpy_array.shape,
84 numpy_array.astype(numpy.uint8),
85 'raw','L',0,1)
86
87 pilImage = ImageOps.autocontrast(pilImage, cutoff=.1)
88 pilImage.save(sys.argv[1]+'.jpg')
gdcm::ImageReader
ImageReader.
Definition gdcmImageReader.h:34