16 save a DICOM image with PIL via numpy
19 - Does not support UINT12/INT12
23 python ConvertNumpy.py "IM000000"
26 plotting example - Ray Schumacher 2009
31 from PIL
import Image, ImageOps
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 }
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]
50 def gdcm_to_numpy(image):
51 """Converts a GDCM image to a numpy array.
53 pf = image.GetPixelFormat().GetScalarType()
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()])
67 result = numpy.log(result+50)
68 maxV = float(result[result.argmax()])
69 result = result*(2.**8/maxV)
73 if __name__ ==
"__main__":
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() )
82 pilImage = Image.frombuffer(
'L',
84 numpy_array.astype(numpy.uint8),
87 pilImage = ImageOps.autocontrast(pilImage, cutoff=.1)
88 pilImage.save(sys.argv[1]+
'.jpg')