Commit 49e8a01399a7734fcf4a1e37d3b4981399425e16

Authored by tfmoraes
1 parent c026c917

ENH: starting to using memmap in slices

Showing 1 changed file with 49 additions and 0 deletions   Show diff stats
invesalius/data/imagedata_utils.py
... ... @@ -19,10 +19,16 @@
19 19  
20 20 import math
21 21 import os
  22 +import tempfile
  23 +
  24 +import gdcm
  25 +import numpy
22 26 import vtk
23 27 import vtkgdcm
24 28 import wx.lib.pubsub as ps
25 29  
  30 +from vtk.util import numpy_support
  31 +
26 32 import constants as const
27 33 from data import vtk_utils
28 34 import utils
... ... @@ -449,3 +455,46 @@ class ImageCreator:
449 455 imagedata.Update()
450 456  
451 457 return imagedata
  458 +
  459 +def get_gdcm_to_numpy_typemap():
  460 + """Returns the GDCM Pixel Format to numpy array type mapping."""
  461 + _gdcm_np = {gdcm.PixelFormat.UINT8 :numpy.int8,
  462 + gdcm.PixelFormat.INT8 :numpy.uint8,
  463 + #gdcm.PixelFormat.UINT12 :numpy.uint12,
  464 + #gdcm.PixelFormat.INT12 :numpy.int12,
  465 + gdcm.PixelFormat.UINT16 :numpy.uint16,
  466 + gdcm.PixelFormat.INT16 :numpy.int16,
  467 + gdcm.PixelFormat.UINT32 :numpy.uint32,
  468 + gdcm.PixelFormat.INT32 :numpy.int32,
  469 + #gdcm.PixelFormat.FLOAT16:numpy.float16,
  470 + gdcm.PixelFormat.FLOAT32:numpy.float32,
  471 + gdcm.PixelFormat.FLOAT64:numpy.float64 }
  472 + return _gdcm_np
  473 +
  474 +def get_numpy_array_type(gdcm_pixel_format):
  475 + """Returns a numpy array typecode given a GDCM Pixel Format."""
  476 + return get_gdcm_to_numpy_typemap()[gdcm_pixel_format]
  477 +
  478 +def dcm2memmap(files, slice_size):
  479 + """
  480 + From a list of dicom files it creates memmap file in the temp folder and
  481 + returns.
  482 + """
  483 + temp_file = tempfile.mktemp()
  484 + shape = len(files), slice_size[0], slice_size[1]
  485 +
  486 + matrix = numpy.memmap(temp_file, mode='w+', dtype='uint16', shape=shape)
  487 +
  488 + for n, f in enumerate(files):
  489 + dcm_image = gdcm.ImageReader()
  490 + dcm_image.SetFileName(f)
  491 + dcm_image.Read()
  492 +
  493 + image = dcm_image.GetImage()
  494 + pf = image.GetPixelFormat().GetScalarType()
  495 + dtype = get_numpy_array_type(pf)
  496 +
  497 + dcm_array = image.GetBuffer()
  498 + array = numpy.frombuffer(dcm_array, dtype)
  499 + array.shape = slice_size
  500 + matrix[n] = array
... ...