From 3aa03487ce9ce8290b8270beba82ef41eb27d4c9 Mon Sep 17 00:00:00 2001 From: Thiago Franco de Moraes Date: Mon, 5 Oct 2015 15:51:19 -0300 Subject: [PATCH] saving and opening in the new way --- invesalius/data/imagedata_utils.py | 11 ++++++++--- invesalius/data/mask.py | 29 +++++++++++++++++++++++++++-- invesalius/data/surface.py | 40 +++++++++++++++++++++++++++++++++++++++- invesalius/project.py | 155 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------------------------------- 4 files changed, 155 insertions(+), 80 deletions(-) diff --git a/invesalius/data/imagedata_utils.py b/invesalius/data/imagedata_utils.py index bb48376..85fab4e 100644 --- a/invesalius/data/imagedata_utils.py +++ b/invesalius/data/imagedata_utils.py @@ -32,6 +32,7 @@ from vtk.util import numpy_support import constants as const from data import vtk_utils + import utils # TODO: Test cases which are originally in sagittal/coronal orientation @@ -421,10 +422,12 @@ def dcm2memmap(files, slice_size, orientation, resolution_percentage): From a list of dicom files it creates memmap file in the temp folder and returns it and its related filename. """ + from project import Project message = _("Generating multiplanar visualization...") update_progress= vtk_utils.ShowProgress(len(files) - 1, dialog_type = "ProgressDialog") - - temp_file = tempfile.mktemp() + proj = Project() + wdir = proj.working_dir + temp_file = os.path.join(wdir, 'matrix.dat') if orientation == 'SAGITTAL': if resolution_percentage == 1.0: @@ -496,7 +499,9 @@ def dcm2memmap(files, slice_size, orientation, resolution_percentage): def analyze2mmap(analyze): data = analyze.get_data() header = analyze.get_header() - temp_file = tempfile.mktemp() + proj = Project() + wdir = proj.working_dir + temp_file = os.path.join(wdir, 'matrix.dat') # Sagital if header['orient'] == 2: diff --git a/invesalius/data/mask.py b/invesalius/data/mask.py index 63c04c4..e076d56 100644 --- a/invesalius/data/mask.py +++ b/invesalius/data/mask.py @@ -33,6 +33,7 @@ import session as ses from wx.lib.pubsub import pub as Publisher + class EditionHistoryNode(object): def __init__(self, index, orientation, array, clean=False): self.index = index @@ -259,6 +260,26 @@ class Mask(): path = os.path.join(dirpath, mask_file) self._open_mask(path, tuple(shape)) + def save_workdir(self): + mask = {} + filename = os.path.split(self.temp_file)[-1] + + mask['index'] = self.index + mask['name'] = self.name + mask['colour'] = self.colour + mask['opacity'] = self.opacity + mask['threshold_range'] = self.threshold_range + mask['edition_threshold_range'] = self.edition_threshold_range + mask['visible'] = self.is_shown + mask['mask_file'] = filename + mask['mask_shape'] = self.matrix.shape + mask['edited'] = self.was_edited + + plist_filename = os.path.splitext(self.temp_file)[0]+ '.plist' + plistlib.writePlist(mask, plist_filename) + + return os.path.split(plist_filename)[-1] + def OnFlipVolume(self, pubsub_evt): axis = pubsub_evt.data submatrix = self.matrix[1:, 1:, 1:] @@ -289,10 +310,14 @@ class Mask(): Mask.general_index = index def create_mask(self, shape): - print "Creating a mask" - self.temp_file = tempfile.mktemp() + from project import Project + proj = Project() + wdir = proj.working_dir + self.temp_file = tempfile.mktemp(prefix='mask%d_' % self.index, dir=wdir) + print "Creating mask at", self.temp_file shape = shape[0] + 1, shape[1] + 1, shape[2] + 1 self.matrix = numpy.memmap(self.temp_file, mode='w+', dtype='uint8', shape=shape) + proj.save_workdir() def clean(self): self.matrix[1:, 1:, 1:] = 0 diff --git a/invesalius/data/surface.py b/invesalius/data/surface.py index 138d943..8fe6f7e 100644 --- a/invesalius/data/surface.py +++ b/invesalius/data/surface.py @@ -59,6 +59,7 @@ class Surface(): self.transparency = const.SURFACE_TRANSPARENCY self.volume = 0 self.is_shown = 1 + self.temp_file = '' if not name: self.name = const.SURFACE_NAME_PATTERN %(self.index+1) else: @@ -101,6 +102,19 @@ class Surface(): self.polydata = pu.Import(os.path.join(dirpath, sp['polydata'])) Surface.general_index = max(Surface.general_index, self.index) + def save_workdir(self): + surface = {'colour': self.colour, + 'index': self.index, + 'name': self.name, + 'polydata': self.temp_file, + 'transparency': self.transparency, + 'visible': bool(self.is_shown), + 'volume': self.volume, + } + plist_filename = os.path.splitext(self.temp_file)[0] + '.plist' + plistlib.writePlist(surface, plist_filename) + return os.path.split(plist_filename)[-1] + def _set_class_index(self, index): Surface.general_index = index @@ -278,6 +292,17 @@ class SurfaceManager(): surface.index = index self.last_surface_index = index + wdir = proj.working_dir + temp_file = tempfile.mktemp(prefix='surface%d_' % surface.index, suffix='.vtp', dir=wdir) + + writer = vtk.vtkXMLPolyDataWriter() + writer.SetInput(polydata) + writer.SetFileName(temp_file) + writer.Write() + del writer + + surface.temp_file = temp_file + # Set actor colour and transparency actor.GetProperty().SetColor(surface.colour) actor.GetProperty().SetOpacity(1-surface.transparency) @@ -307,6 +332,7 @@ class SurfaceManager(): (surface.index, surface.name, surface.colour, surface.volume, surface.transparency)) + return surface.index def OnCloseProject(self, pubsub_evt): @@ -644,6 +670,8 @@ class SurfaceManager(): polydata.DebugOn() del filled_polydata + proj = prj.Project() + normals = vtk.vtkPolyDataNormals() normals.ReleaseDataFlagOn() normals_ref = weakref.ref(normals) @@ -693,6 +721,17 @@ class SurfaceManager(): surface = Surface(index = self.last_surface_index) else: surface = Surface(name=surface_name) + + wdir = proj.working_dir + temp_file = tempfile.mktemp(prefix='surface%d_' % surface.index, suffix='.vtp', dir=wdir) + + writer = vtk.vtkXMLPolyDataWriter() + writer.SetInput(polydata) + writer.SetFileName(temp_file) + writer.Write() + del writer + + surface.temp_file = temp_file surface.colour = colour surface.polydata = polydata del polydata @@ -707,7 +746,6 @@ class SurfaceManager(): prop.SetInterpolation(interpolation) - proj = prj.Project() if overwrite: proj.ChangeSurface(surface) else: diff --git a/invesalius/project.py b/invesalius/project.py index 96ae4d1..73f468d 100644 --- a/invesalius/project.py +++ b/invesalius/project.py @@ -74,6 +74,7 @@ class Project(object): self.raycasting_preset = '' + self.working_dir = tempfile.mkdtemp() #self.surface_quality_list = ["Low", "Medium", "High", "Optimal *", # "Custom"i] @@ -84,6 +85,13 @@ class Project(object): # Allow insertion of new surface quality modes def Close(self): + try: + print ">>>>> Trying to remove", self.working_dir + os.rmdir(self.working_dir) + print ">>>> done" + except OSError: + print ">>>> It was not possible" + for name in self.__dict__: attr = getattr(self, name) del attr @@ -195,77 +203,10 @@ class Project(object): return measures def SavePlistProject(self, dir_, filename): - dir_temp = tempfile.mkdtemp() - filename_tmp = os.path.join(dir_temp, 'matrix.dat') - filelist = {} - - project = { - # Format info - "format_version": 1, - "invesalius_version": const.INVESALIUS_VERSION, - "date": datetime.datetime.now().isoformat(), - - # case info - "name": self.name, # patient's name - "modality": self.modality, # CT, RMI, ... - "orientation": self.original_orientation, - "window_width": self.window, - "window_level": self.level, - "scalar_range": self.threshold_range, - "spacing": self.spacing, - } - - # Saving the matrix containing the slices - matrix = {'filename': u'matrix.dat', - 'shape': self.matrix_shape, - 'dtype': self.matrix_dtype, - } - project['matrix'] = matrix - filelist[self.matrix_filename] = 'matrix.dat' - #shutil.copyfile(self.matrix_filename, filename_tmp) - - # Saving the masks - masks = {} - for index in self.mask_dict: - masks[str(index)] = self.mask_dict[index].SavePlist(dir_temp, - filelist) - project['masks'] = masks - - # Saving the surfaces - surfaces = {} - for index in self.surface_dict: - surfaces[str(index)] = self.surface_dict[index].SavePlist(dir_temp, - filelist) - project['surfaces'] = surfaces - - # Saving the measurements - measurements = self.GetMeasuresDict() - measurements_filename = 'measurements.plist' - temp_mplist = tempfile.mktemp() - plistlib.writePlist(measurements, - temp_mplist) - filelist[temp_mplist] = measurements_filename - project['measurements'] = measurements_filename - - # Saving the annotations (empty in this version) - project['annotations'] = {} - - # Saving the main plist - temp_plist = tempfile.mktemp() - plistlib.writePlist(project, temp_plist) - filelist[temp_plist] = 'main.plist' - - # Compressing and generating the .inv3 file path = os.path.join(dir_,filename) - Compress(dir_temp, path, filelist) + filelist = self.save_workdir() + Compress(self.working_dir, path, filelist) - # Removing the temp folder. - shutil.rmtree(dir_temp) - - for f in filelist: - if filelist[f].endswith('.plist'): - print f - os.remove(f) def OpenPlistProject(self, filename): import data.measures as ms @@ -278,7 +219,9 @@ class Project(object): ow.SetInstance(fow) filelist = Extract(filename, tempfile.mkdtemp()) + print "@@@@", os.path.split(filelist[0])[0] dirpath = os.path.abspath(os.path.split(filelist[0])[0]) + self.working_dir = dirpath # Opening the main file from invesalius 3 project main_plist = os.path.join(dirpath ,'main.plist') @@ -326,15 +269,77 @@ class Project(object): measure.Load(measurements[index]) self.measurement_dict[int(index)] = measure + def save_workdir(self): + filelist = [] + project = { + # Format info + "format_version": 1, + "invesalius_version": const.INVESALIUS_VERSION, + "date": datetime.datetime.now().isoformat(), + + # case info + "name": self.name, # patient's name + "modality": self.modality, # CT, RMI, ... + "orientation": self.original_orientation, + "window_width": self.window, + "window_level": self.level, + "scalar_range": self.threshold_range, + "spacing": self.spacing, + } + + # Saving the matrix containing the slices + matrix = {'filename': u'matrix.dat', + 'shape': self.matrix_shape, + 'dtype': self.matrix_dtype, + } + + project['matrix'] = matrix + filelist.append(os.path.join(self.working_dir, 'matrix.dat')) + #shutil.copyfile(self.matrix_filename, filename_tmp) + + # Saving the masks + masks = {} + for index in self.mask_dict: + masks[str(index)] = self.mask_dict[index].save_workdir() + filelist.append(os.path.join(self.working_dir, masks[str(index)])) + filelist.append(os.path.join(self.working_dir, os.path.splitext(masks[str(index)])[0])) + project['masks'] = masks + + # # Saving the surfaces + surfaces = {} + for index in self.surface_dict: + surfaces[str(index)] = self.surface_dict[index].save_workdir() + filelist.append(os.path.join(self.working_dir, surfaces[str(index)])) + filelist.append(os.path.join(self.working_dir, os.path.splitext(surfaces[str(index)])[0])) + project['surfaces'] = surfaces + + # Saving the measurements + measurements = self.GetMeasuresDict() + measurements_filename = 'measurements.plist' + temp_mplist = os.path.join(self.working_dir, measurements_filename) + plistlib.writePlist(measurements, temp_mplist) + project['measurements'] = measurements_filename + filelist.append(os.path.join(self.working_dir, 'measurements.plist')) + + # Saving the annotations (empty in this version) + project['annotations'] = {} + + # Saving the main plist + pfname = os.path.join(self.working_dir, 'main.plist') + plistlib.writePlist(project, pfname) + filelist.append(os.path.join(self.working_dir, 'main.plist')) + + return filelist + + def Compress(folder, filename, filelist): tmpdir, tmpdir_ = os.path.split(folder) current_dir = os.path.abspath(".") - #os.chdir(tmpdir) - #file_list = glob.glob(os.path.join(tmpdir_,"*")) - tar_filename = tmpdir_ + ".inv3" tar = tarfile.open(filename.encode(wx.GetDefaultPyEncoding()), "w:gz") for name in filelist: - tar.add(name, arcname=os.path.join(tmpdir_, filelist[name])) + sname = name.split(os.path.sep) + print ">>>>", sname + tar.add(name, arcname=os.path.join(sname[-2], sname[-1])) tar.close() #shutil.move(tmpdir_+ ".inv3", filename) #os.chdir(current_dir) @@ -350,6 +355,8 @@ def Extract(filename, folder): fname = os.path.join(folder, t.name.decode('utf-8')) fdst = file(fname, 'wb') + print fsrc, fdst + shutil.copyfileobj(fsrc, fdst) filelist.append(fname) @@ -361,7 +368,7 @@ def Extract(filename, folder): print filelist return filelist - + def Extract_(filename, folder): tar = tarfile.open(filename, "r:gz") #tar.list(verbose=True) -- libgit2 0.21.2