diff --git a/invesalius/data/imagedata_utils.py b/invesalius/data/imagedata_utils.py index 96a0b64..cb7a3e6 100644 --- a/invesalius/data/imagedata_utils.py +++ b/invesalius/data/imagedata_utils.py @@ -1,10 +1,10 @@ -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer # Homepage: http://www.softwarepublico.gov.br # Contact: invesalius@cti.gov.br # License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt) -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- # Este programa e software livre; voce pode redistribui-lo e/ou # modifica-lo sob os termos da Licenca Publica Geral GNU, conforme # publicada pela Free Software Foundation; de acordo com a versao 2 @@ -15,7 +15,7 @@ # COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM # PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais # detalhes. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- import math import os @@ -28,21 +28,19 @@ import numpy import numpy as np import vtk from pubsub import pub as Publisher - from scipy.ndimage import shift, zoom from vtk.util import numpy_support import invesalius.constants as const -from invesalius.data import vtk_utils as vtk_utils -import invesalius.reader.bitmap_reader as bitmap_reader -import invesalius.utils as utils import invesalius.data.converters as converters import invesalius.data.slice_ as sl import invesalius.data.transformations as tr - +import invesalius.reader.bitmap_reader as bitmap_reader +import invesalius.utils as utils from invesalius import inv_paths +from invesalius.data import vtk_utils as vtk_utils -if sys.platform == 'win32': +if sys.platform == "win32": try: import win32api _has_win32api = True @@ -54,6 +52,7 @@ else: # TODO: Test cases which are originally in sagittal/coronal orientation # and have gantry + def ResampleImage3D(imagedata, value): """ Resample vtkImageData matrix. @@ -63,9 +62,9 @@ def ResampleImage3D(imagedata, value): size = imagedata.GetDimensions() width = float(size[0]) - height = float(size[1]/value) + height = float(size[1] / value) - resolution = (height/(extent[1]-extent[0])+1)*spacing[1] + resolution = (height / (extent[1] - extent[0]) + 1) * spacing[1] resample = vtk.vtkImageResample() resample.SetInput(imagedata) @@ -74,8 +73,10 @@ def ResampleImage3D(imagedata, value): return resample.GetOutput() -def ResampleImage2D(imagedata, px=None, py=None, resolution_percentage = None, - update_progress = None): + +def ResampleImage2D( + imagedata, px=None, py=None, resolution_percentage=None, update_progress=None +): """ Resample vtkImageData matrix. """ @@ -88,30 +89,30 @@ def ResampleImage2D(imagedata, px=None, py=None, resolution_percentage = None, factor_x = resolution_percentage factor_y = resolution_percentage else: - if abs(extent[1]-extent[3]) < abs(extent[3]-extent[5]): + if abs(extent[1] - extent[3]) < abs(extent[3] - extent[5]): f = extent[1] - elif abs(extent[1]-extent[5]) < abs(extent[1] - extent[3]): + elif abs(extent[1] - extent[5]) < abs(extent[1] - extent[3]): f = extent[1] - elif abs(extent[3]-extent[5]) < abs(extent[1] - extent[3]): + elif abs(extent[3] - extent[5]) < abs(extent[1] - extent[3]): f = extent[3] else: f = extent[1] - factor_x = px/float(f+1) - factor_y = py/float(f+1) + factor_x = px / float(f + 1) + factor_y = py / float(f + 1) resample = vtk.vtkImageResample() resample.SetInputData(imagedata) resample.SetAxisMagnificationFactor(0, factor_x) resample.SetAxisMagnificationFactor(1, factor_y) # resample.SetOutputSpacing(spacing[0] * factor_x, spacing[1] * factor_y, spacing[2]) - if (update_progress): + if update_progress: message = _("Generating multiplanar visualization...") - resample.AddObserver("ProgressEvent", lambda obj, - evt:update_progress(resample,message)) + resample.AddObserver( + "ProgressEvent", lambda obj, evt: update_progress(resample, message) + ) resample.Update() - return resample.GetOutput() @@ -131,7 +132,7 @@ def resize_image_array(image, resolution_percentage, as_mmap=False): out = zoom(image, resolution_percentage, image.dtype, order=2) if as_mmap: fname = tempfile.mktemp(suffix="_resized") - out_mmap = np.memmap(fname, shape=out.shape, dtype=out.dtype, mode='w+') + out_mmap = np.memmap(fname, shape=out.shape, dtype=out.dtype, mode="w+") out_mmap[:] = out return out_mmap return out @@ -159,7 +160,7 @@ def FixGantryTilt(matrix, spacing, tilt): for n, slice_ in enumerate(matrix): offset = gntan * n * spacing[2] - matrix[n] = shift(slice_, (-offset/spacing[1], 0), cval=matrix.min()) + matrix[n] = shift(slice_, (-offset / spacing[1], 0), cval=matrix.min()) def BuildEditedImage(imagedata, points): @@ -175,28 +176,28 @@ def BuildEditedImage(imagedata, points): imagedata.SetScalarComponentFromDouble(x, y, z, 0, colour) imagedata.Update() - if not(init_values): - xi = x - xf = x - yi = y - yf = y - zi = z - zf = z - init_values = 1 + if not (init_values): + xi = x + xf = x + yi = y + yf = y + zi = z + zf = z + init_values = 1 - if (xi > x): + if xi > x: xi = x - elif(xf < x): + elif xf < x: xf = x - if (yi > y): + if yi > y: yi = y - elif(yf < y): + elif yf < y: yf = y - if (zi > z): + if zi > z: zi = z - elif(zf < z): + elif zf < z: zf = z clip = vtk.vtkImageClip() @@ -226,8 +227,9 @@ def Export(imagedata, filename, bin=False): writer.SetDataModeToBinary() else: writer.SetDataModeToAscii() - #writer.SetInput(imagedata) - #writer.Write() + # writer.SetInput(imagedata) + # writer.Write() + def Import(filename): reader = vtk.vtkXMLImageDataReader() @@ -238,6 +240,7 @@ def Import(filename): return reader.GetOutput() + def View(imagedata): viewer = vtk.vtkImageViewer() viewer.SetInput(imagedata) @@ -246,16 +249,17 @@ def View(imagedata): viewer.Render() import time + time.sleep(10) -def ExtractVOI(imagedata,xi,xf,yi,yf,zi,zf): +def ExtractVOI(imagedata, xi, xf, yi, yf, zi, zf): """ Cropping the vtkImagedata according with values. """ voi = vtk.vtkExtractVOI() - voi.SetVOI(xi,xf,yi,yf,zi,zf) + voi.SetVOI(xi, xf, yi, yf, zi, zf) voi.SetInputData(imagedata) voi.SetSampleRate(1, 1, 1) voi.Update() @@ -274,27 +278,30 @@ def create_dicom_thumbnails(image, window=None, level=None): thumbnail_paths = [] for i in range(np_image.shape[0]): thumb_image = zoom(np_image[i], 0.25) - thumb_image = np.array(get_LUT_value_255(thumb_image, window, level), dtype=np.uint8) - thumbnail_path = tempfile.mktemp(prefix='thumb_', suffix='.png') + thumb_image = np.array( + get_LUT_value_255(thumb_image, window, level), dtype=np.uint8 + ) + thumbnail_path = tempfile.mktemp(prefix="thumb_", suffix=".png") imageio.imsave(thumbnail_path, thumb_image) thumbnail_paths.append(thumbnail_path) return thumbnail_paths else: - thumbnail_path = tempfile.mktemp(prefix='thumb_', suffix='.png') + thumbnail_path = tempfile.mktemp(prefix="thumb_", suffix=".png") if pf.GetSamplesPerPixel() == 1: thumb_image = zoom(np_image, 0.25) - thumb_image = np.array(get_LUT_value_255(thumb_image, window, level), dtype=np.uint8) + thumb_image = np.array( + get_LUT_value_255(thumb_image, window, level), dtype=np.uint8 + ) else: thumb_image = zoom(np_image, (0.25, 0.25, 1)) imageio.imsave(thumbnail_path, thumb_image) return thumbnail_path - def array2memmap(arr, filename=None): if filename is None: - filename = tempfile.mktemp(prefix='inv3_', suffix='.dat') - matrix = numpy.memmap(filename, mode='w+', dtype=arr.dtype, shape=arr.shape) + filename = tempfile.mktemp(prefix="inv3_", suffix=".dat") + matrix = numpy.memmap(filename, mode="w+", dtype=arr.dtype, shape=arr.shape) matrix[:] = arr[:] matrix.flush() return matrix @@ -307,34 +314,44 @@ def bitmap2memmap(files, slice_size, orientation, spacing, resolution_percentage """ message = _("Generating multiplanar visualization...") if len(files) > 1: - update_progress= vtk_utils.ShowProgress(len(files) - 1, dialog_type = "ProgressDialog") + update_progress = vtk_utils.ShowProgress( + len(files) - 1, dialog_type="ProgressDialog" + ) temp_file = tempfile.mktemp() - if orientation == 'SAGITTAL': + if orientation == "SAGITTAL": if resolution_percentage == 1.0: shape = slice_size[1], slice_size[0], len(files) else: - shape = math.ceil(slice_size[1]*resolution_percentage),\ - math.ceil(slice_size[0]*resolution_percentage), len(files) + shape = ( + math.ceil(slice_size[1] * resolution_percentage), + math.ceil(slice_size[0] * resolution_percentage), + len(files), + ) - elif orientation == 'CORONAL': + elif orientation == "CORONAL": if resolution_percentage == 1.0: shape = slice_size[1], len(files), slice_size[0] else: - shape = math.ceil(slice_size[1]*resolution_percentage), len(files),\ - math.ceil(slice_size[0]*resolution_percentage) + shape = ( + math.ceil(slice_size[1] * resolution_percentage), + len(files), + math.ceil(slice_size[0] * resolution_percentage), + ) else: if resolution_percentage == 1.0: shape = len(files), slice_size[1], slice_size[0] else: - shape = len(files), math.ceil(slice_size[1]*resolution_percentage),\ - math.ceil(slice_size[0]*resolution_percentage) - + shape = ( + len(files), + math.ceil(slice_size[1] * resolution_percentage), + math.ceil(slice_size[0] * resolution_percentage), + ) if resolution_percentage == 1.0: - matrix = numpy.memmap(temp_file, mode='w+', dtype='int16', shape=shape) - + matrix = numpy.memmap(temp_file, mode="w+", dtype="int16", shape=shape) + cont = 0 max_scalar = None min_scalar = None @@ -347,21 +364,31 @@ def bitmap2memmap(files, slice_size, orientation, spacing, resolution_percentage print(image_as_array.dtype) - image = converters.to_vtk(image_as_array, spacing=spacing,\ - slice_number=1, orientation=orientation.upper()) + image = converters.to_vtk( + image_as_array, + spacing=spacing, + slice_number=1, + orientation=orientation.upper(), + ) if resolution_percentage != 1.0: - - - image_resized = ResampleImage2D(image, px=None, py=None,\ - resolution_percentage = resolution_percentage, update_progress = None) - yx_shape = image_resized.GetDimensions()[1], image_resized.GetDimensions()[0] - - - if not(first_resample_entry): - shape = shape[0], yx_shape[0], yx_shape[1] - matrix = numpy.memmap(temp_file, mode='w+', dtype='int16', shape=shape) + image_resized = ResampleImage2D( + image, + px=None, + py=None, + resolution_percentage=resolution_percentage, + update_progress=None, + ) + + yx_shape = ( + image_resized.GetDimensions()[1], + image_resized.GetDimensions()[0], + ) + + if not (first_resample_entry): + shape = shape[0], yx_shape[0], yx_shape[1] + matrix = numpy.memmap(temp_file, mode="w+", dtype="int16", shape=shape) first_resample_entry = True image = image_resized @@ -375,26 +402,26 @@ def bitmap2memmap(files, slice_size, orientation, spacing, resolution_percentage array = numpy_support.vtk_to_numpy(image.GetPointData().GetScalars()) - if array.dtype == 'uint16': + if array.dtype == "uint16": new_array = np.empty_like(array, dtype=np.int16) new_array = array - 32768 array = new_array - if orientation == 'CORONAL': + if orientation == "CORONAL": array.shape = matrix.shape[0], matrix.shape[2] - matrix[:, n, :] = array[:,::-1] - elif orientation == 'SAGITTAL': + matrix[:, n, :] = array[:, ::-1] + elif orientation == "SAGITTAL": array.shape = matrix.shape[0], matrix.shape[1] # TODO: Verify if it's necessary to add the slices swapped only in # sagittal rmi or only in # Rasiane's case or is necessary in all # sagittal cases. - matrix[:, :, n] = array[:,::-1] + matrix[:, :, n] = array[:, ::-1] else: array.shape = matrix.shape[1], matrix.shape[2] matrix[n] = array - + if len(files) > 1: - update_progress(cont,message) + update_progress(cont, message) cont += 1 matrix.flush() @@ -411,27 +438,29 @@ def dcm2memmap(files, slice_size, orientation, resolution_percentage): """ if len(files) > 1: message = _("Generating multiplanar visualization...") - update_progress= vtk_utils.ShowProgress(len(files) - 1, dialog_type = "ProgressDialog") + update_progress = vtk_utils.ShowProgress( + len(files) - 1, dialog_type="ProgressDialog" + ) first_slice = read_dcm_slice_as_np2(files[0], resolution_percentage) slice_size = first_slice.shape[::-1] temp_file = tempfile.mktemp() - if orientation == 'SAGITTAL': + if orientation == "SAGITTAL": shape = slice_size[0], slice_size[1], len(files) - elif orientation == 'CORONAL': + elif orientation == "CORONAL": shape = slice_size[1], len(files), slice_size[0] else: shape = len(files), slice_size[1], slice_size[0] - matrix = numpy.memmap(temp_file, mode='w+', dtype='int16', shape=shape) + matrix = numpy.memmap(temp_file, mode="w+", dtype="int16", shape=shape) for n, f in enumerate(files): im_array = read_dcm_slice_as_np2(f, resolution_percentage)[::-1] - if orientation == 'CORONAL': + if orientation == "CORONAL": matrix[:, shape[1] - n - 1, :] = im_array - elif orientation == 'SAGITTAL': + elif orientation == "SAGITTAL": # TODO: Verify if it's necessary to add the slices swapped only in # sagittal rmi or only in # Rasiane's case or is necessary in all # sagittal cases. @@ -456,15 +485,15 @@ def dcmmf2memmap(dcm_file, orientation): pf = image.GetPixelFormat() np_image = converters.gdcm_to_numpy(image, pf.GetSamplesPerPixel() == 1) temp_file = tempfile.mktemp() - matrix = numpy.memmap(temp_file, mode='w+', dtype='int16', shape=np_image.shape) + matrix = numpy.memmap(temp_file, mode="w+", dtype="int16", shape=np_image.shape) print("Number of dimensions", np_image.shape) z, y, x = np_image.shape - if orientation == 'CORONAL': + if orientation == "CORONAL": spacing = xs, zs, ys matrix.shape = y, z, x for n in range(z): matrix[:, n, :] = np_image[n][::-1] - elif orientation == 'SAGITTAL': + elif orientation == "SAGITTAL": spacing = zs, ys, xs matrix.shape = y, x, z for n in range(z): @@ -495,7 +524,7 @@ def img2memmap(group): data = numpy.swapaxes(data, 0, 2) data = numpy.fliplr(data) - matrix = numpy.memmap(temp_file, mode='w+', dtype=np.int16, shape=data.shape) + matrix = numpy.memmap(temp_file, mode="w+", dtype=np.int16, shape=data.shape) matrix[:] = data[:] matrix.flush() @@ -507,10 +536,14 @@ def img2memmap(group): def get_LUT_value_255(data, window, level): shape = data.shape data_ = data.ravel() - data = np.piecewise(data_, - [data_ <= (level - 0.5 - (window-1)/2), - data_ > (level - 0.5 + (window-1)/2)], - [0, 255, lambda data_: ((data_ - (level - 0.5))/(window-1) + 0.5)*(255)]) + data = np.piecewise( + data_, + [ + data_ <= (level - 0.5 - (window - 1) / 2), + data_ > (level - 0.5 + (window - 1) / 2), + ], + [0, 255, lambda data_: ((data_ - (level - 0.5)) / (window - 1) + 0.5) * (255)], + ) data.shape = shape return data @@ -534,7 +567,9 @@ def world2invspace(affine=None): # remove scaling factor for non-unitary voxel dimensions scale, shear, angs, trans, persp = tr.decompose_matrix(affine) - affine_noscale = tr.compose_matrix(scale=None, shear=shear, angles=angs, translate=trans, perspective=persp) + affine_noscale = tr.compose_matrix( + scale=None, shear=shear, angles=angs, translate=trans, perspective=persp + ) # repos_img = [0.] * 6 # repos_img[1] = -float(shape[1]) # @@ -579,7 +614,7 @@ def convert_world_to_voxel(xyz, affine): # print("xyz: ", xyz, "\naffine", affine) # convert xyz coordinate to 1x4 homogeneous coordinates array - xyz_homo = np.hstack((xyz, 1.)).reshape([4, 1]) + xyz_homo = np.hstack((xyz, 1.0)).reshape([4, 1]) ijk_homo = np.linalg.inv(affine) @ xyz_homo ijk = ijk_homo.T[np.newaxis, 0, :3] @@ -587,13 +622,13 @@ def convert_world_to_voxel(xyz, affine): def create_grid(xy_range, z_range, z_offset, spacing): - x = np.arange(xy_range[0], xy_range[1]+1, spacing) - y = np.arange(xy_range[0], xy_range[1]+1, spacing) - z = z_offset + np.arange(z_range[0], z_range[1]+1, spacing) + x = np.arange(xy_range[0], xy_range[1] + 1, spacing) + y = np.arange(xy_range[0], xy_range[1] + 1, spacing) + z = z_offset + np.arange(z_range[0], z_range[1] + 1, spacing) xv, yv, zv = np.meshgrid(x, y, -z) coord_grid = np.array([xv, yv, zv]) # create grid of points - grid_number = x.shape[0]*y.shape[0]*z.shape[0] + grid_number = x.shape[0] * y.shape[0] * z.shape[0] coord_grid = coord_grid.reshape([3, grid_number]).T # sort grid from distance to the origin/coil center coord_list = coord_grid[np.argsort(np.linalg.norm(coord_grid, axis=1)), :] @@ -604,11 +639,11 @@ def create_grid(xy_range, z_range, z_offset, spacing): def create_spherical_grid(radius=10, subdivision=1): - x = np.linspace(-radius, radius, int(2*radius/subdivision)+1) + x = np.linspace(-radius, radius, int(2 * radius / subdivision) + 1) xv, yv, zv = np.meshgrid(x, x, x) coord_grid = np.array([xv, yv, zv]) # create grid of points - grid_number = x.shape[0]**3 + grid_number = x.shape[0] ** 3 coord_grid = coord_grid.reshape([3, grid_number]).T sph_grid = coord_grid[np.linalg.norm(coord_grid, axis=1) < radius, :] diff --git a/invesalius/reader/bitmap_reader.py b/invesalius/reader/bitmap_reader.py index 8cc16ce..bdc946c 100644 --- a/invesalius/reader/bitmap_reader.py +++ b/invesalius/reader/bitmap_reader.py @@ -1,10 +1,10 @@ -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer # Homepage: http://www.softwarepublico.gov.br # Contact: invesalius@cti.gov.br # License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt) -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- # Este programa e software livre; voce pode redistribui-lo e/ou # modifica-lo sob os termos da Licenca Publica Geral GNU, conforme # publicada pela Free Software Foundation; de acordo com a versao 2 @@ -15,56 +15,55 @@ # COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM # PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais # detalhes. -#-------------------------------------------------------------------------- +# -------------------------------------------------------------------------- +import imghdr import os -import threading -import tempfile +import re import sys +import tempfile +import threading +from multiprocessing import cpu_count + +import numpy import vtk -import re -import invesalius.constants as const import wx - +from imageio import imread from pubsub import pub as Publisher -from multiprocessing import cpu_count - from vtk.util import numpy_support -from imageio import imread -import numpy -import imghdr -import invesalius.utils as utils +import invesalius.constants as const import invesalius.data.converters as converters +import invesalius.utils as utils from invesalius import inv_paths - -#flag to control vtk error in read files -no_error = True +# flag to control vtk error in read files +no_error = True vtk_error = False -if sys.platform == 'win32': +if sys.platform == "win32": try: import win32api + _has_win32api = True except ImportError: _has_win32api = False else: _has_win32api = False -class Singleton: - def __init__(self,klass): +class Singleton: + def __init__(self, klass): self.klass = klass self.instance = None - - def __call__(self,*args,**kwds): + + def __call__(self, *args, **kwds): if self.instance == None: - self.instance = self.klass(*args,**kwds) + self.instance = self.klass(*args, **kwds) return self.instance + @Singleton class BitmapData: - def __init__(self): self.data = None @@ -86,7 +85,7 @@ class BitmapData: k = {} for v in sizes: - k[v] = '' + k[v] = "" if len(k.keys()) > 1: return False @@ -94,10 +93,10 @@ class BitmapData: return True def GetFirstPixelSize(self): - - path = self.data[0][0] + + path = self.data[0][0] size = ReadBitmap(path).dtype.itemsize * 8 - + return size def RemoveFileByPath(self, path): @@ -110,8 +109,8 @@ class BitmapData: if path.encode(const.FS_ENCODE) in v: return i -class BitmapFiles: +class BitmapFiles: def __init__(self): self.bitmapfiles = [] @@ -119,7 +118,7 @@ class BitmapFiles: self.bitmapfiles.append(bmp) def Sort(self, x): - c_re = re.compile('\d+') + c_re = re.compile("\d+") if len(c_re.findall(x[6])) > 0: return [int(i) for i in c_re.findall(x[6])] else: @@ -127,37 +126,37 @@ class BitmapFiles: def GetValues(self): bmpfile = self.bitmapfiles - bmpfile.sort(key = self.Sort) + bmpfile.sort(key=self.Sort) bmp_data = BitmapData() bmp_data.data = bmpfile return bmpfile -class LoadBitmap: +class LoadBitmap: def __init__(self, bmp_file, filepath): self.bmp_file = bmp_file self.filepath = utils.decode(filepath, const.FS_ENCODE) - + self.run() - + def run(self): global vtk_error - #----- verify extension ------------------ + # ----- verify extension ------------------ extension = VerifyDataType(self.filepath) file_name = self.filepath.split(os.path.sep)[-1] n_array = ReadBitmap(self.filepath) - - if not(isinstance(n_array, numpy.ndarray)): + + if not (isinstance(n_array, numpy.ndarray)): return False - - image = converters.to_vtk(n_array, spacing=(1,1,1),\ - slice_number=1, orientation="AXIAL") + image = converters.to_vtk( + n_array, spacing=(1, 1, 1), slice_number=1, orientation="AXIAL" + ) dim = image.GetDimensions() x = dim[0] @@ -165,16 +164,16 @@ class LoadBitmap: img = vtk.vtkImageResample() img.SetInputData(image) - img.SetAxisMagnificationFactor ( 0, 0.25 ) - img.SetAxisMagnificationFactor ( 1, 0.25 ) - img.SetAxisMagnificationFactor ( 2, 1 ) + img.SetAxisMagnificationFactor(0, 0.25) + img.SetAxisMagnificationFactor(1, 0.25) + img.SetAxisMagnificationFactor(2, 1) img.Update() tp = img.GetOutput().GetScalarTypeAsString() image_copy = vtk.vtkImageData() image_copy.DeepCopy(img.GetOutput()) - + thumbnail_path = tempfile.mktemp() write_png = vtk.vtkPNGWriter() @@ -187,20 +186,28 @@ class LoadBitmap: img = vtk.vtkImageCast() img.SetInputData(image_copy) img.SetOutputScalarTypeToUnsignedShort() - #img.SetClampOverflow(1) + # img.SetClampOverflow(1) img.Update() write_png = vtk.vtkPNGWriter() write_png.SetInputConnection(img.GetOutputPort()) write_png.SetFileName(thumbnail_path) write_png.Write() - + vtk_error = False id = wx.NewId() - bmp_item = [self.filepath, thumbnail_path, extension, x, y,\ - str(x) + ' x ' + str(y), file_name, id] + bmp_item = [ + self.filepath, + thumbnail_path, + extension, + x, + y, + str(x) + " x " + str(y), + file_name, + id, + ] self.bmp_file.Add(bmp_item) @@ -217,7 +224,6 @@ def yGetBitmaps(directory, recursive=True, gui=True): dirpath, dirnames, filenames = os.walk(directory) nfiles = len(filenames) - counter = 0 bmp_file = BitmapFiles() @@ -228,7 +234,7 @@ def yGetBitmaps(directory, recursive=True, gui=True): filepath = os.path.join(dirpath, name).encode(const.FS_ENCODE) counter += 1 if gui: - yield (counter,nfiles) + yield (counter, nfiles) LoadBitmap(bmp_file, filepath) else: dirpath, dirnames, filenames = os.walk(directory) @@ -236,7 +242,7 @@ def yGetBitmaps(directory, recursive=True, gui=True): filepath = str(os.path.join(dirpath, name)).encode(const.FS_ENCODE) counter += 1 if gui: - yield (counter,nfiles) + yield (counter, nfiles) yield bmp_file.GetValues() @@ -252,12 +258,12 @@ class ProgressBitmapReader: def SetWindowEvent(self, frame): self.frame = frame - def SetDirectoryPath(self, path,recursive=True): + def SetDirectoryPath(self, path, recursive=True): self.running = True self.stoped = False - self.GetBitmaps(path,recursive) + self.GetBitmaps(path, recursive) - def UpdateLoadFileProgress(self,cont_progress): + def UpdateLoadFileProgress(self, cont_progress): Publisher.sendMessage("Update bitmap load", data=cont_progress) def EndLoadFile(self, bitmap_list): @@ -279,29 +285,31 @@ class ProgressBitmapReader: self.UpdateLoadFileProgress(None) self.stoped = False + def VtkErrorPNGWriter(obj, f): global vtk_error vtk_error = True + def ScipyRead(filepath): try: r = imread(filepath, flatten=True) - dt = r.dtype - if dt == "float" or dt == "float16"\ - or dt == "float32" or dt == "float64": - shift=-r.max()/2 - simage = numpy.zeros_like(r, dtype='int16') - simage[:] = r.astype('int32') + shift + dt = r.dtype + if dt == "float" or dt == "float16" or dt == "float32" or dt == "float64": + shift = -r.max() / 2 + simage = numpy.zeros_like(r, dtype="int16") + simage[:] = r.astype("int32") + shift return simage else: return r - except(IOError): + except (IOError): return False + def VtkRead(filepath, t): if not const.VTK_WARNING: - log_path = os.path.join(inv_paths.USER_LOG_DIR, 'vtkoutput.txt') + log_path = os.path.join(inv_paths.USER_LOG_DIR, "vtkoutput.txt") fow = vtk.vtkFileOutputWindow() fow.SetFileName(log_path.encode(const.FS_ENCODE)) ow = vtk.vtkOutputWindow() @@ -317,7 +325,7 @@ def VtkRead(filepath, t): elif t == "png": reader = vtk.vtkPNGReader() - + elif t == "jpeg" or t == "jpg": reader = vtk.vtkJPEGReader() @@ -327,11 +335,11 @@ def VtkRead(filepath, t): reader.AddObserver("ErrorEvent", VtkErrorToPy) reader.SetFileName(filepath) reader.Update() - + if no_error: image = reader.GetOutput() dim = image.GetDimensions() - + if reader.GetNumberOfScalarComponents() > 1: luminanceFilter = vtk.vtkImageLuminance() luminanceFilter.SetInputData(image) @@ -349,7 +357,7 @@ def VtkRead(filepath, t): return False -def ReadBitmap(filepath): +def ReadBitmap(filepath): t = VerifyDataType(filepath) if _has_win32api: @@ -361,65 +369,65 @@ def ReadBitmap(filepath): except UnicodeDecodeError: measures_info = False if measures_info: - Publisher.sendMessage('Set bitmap spacing', spacing=measures_info) + Publisher.sendMessage("Set bitmap spacing", spacing=measures_info) return False img_array = VtkRead(filepath, t) - - if not(isinstance(img_array, numpy.ndarray)): - + + if not (isinstance(img_array, numpy.ndarray)): + no_error = True - + img_array = ScipyRead(filepath) - - if not(isinstance(img_array, numpy.ndarray)): + + if not (isinstance(img_array, numpy.ndarray)): return False return img_array - + def GetPixelSpacingFromInfoFile(filepath): filepath = utils.decode(filepath, const.FS_ENCODE) - if filepath.endswith('.DS_Store'): + if filepath.endswith(".DS_Store"): return False - fi = open(filepath, 'r') + fi = open(filepath, "r") lines = fi.readlines() - measure_scale = 'mm' + measure_scale = "mm" values = [] if len(lines) > 0: - #info text from avizo - if '# Avizo Stacked Slices' in lines[0]: - value = lines[2].split(' ') + # info text from avizo + if "# Avizo Stacked Slices" in lines[0]: + value = lines[2].split(" ") spx = float(value[1]) spy = float(value[2]) - value = lines[5].split(' ') + value = lines[5].split(" ") spz = float(value[1]) return [spx * 0.001, spy * 0.001, spz * 0.001] else: - #info text from skyscan + # info text from skyscan for l in lines: - if 'Pixel Size' in l: - if 'um' in l: - measure_scale = 'um' - + if "Pixel Size" in l: + if "um" in l: + measure_scale = "um" + value = l.split("=")[-1] values.append(value) if len(values) > 0: value = values[-1] - - value = value.replace('\n','') - value = value.replace('\r','') - #convert um to mm (InVesalius default) - if measure_scale == 'um': + value = value.replace("\n", "") + value = value.replace("\r", "") + + # convert um to mm (InVesalius default) + if measure_scale == "um": value = float(value) * 0.001 - measure_scale = 'mm' + measure_scale = "mm" - elif measure_scale == 'nm': + elif measure_scale == "nm": value = float(value) * 0.000001 return [value, value, value] @@ -428,6 +436,7 @@ def GetPixelSpacingFromInfoFile(filepath): else: return False + def VtkErrorToPy(obj, evt): global no_error no_error = False @@ -442,4 +451,3 @@ def VerifyDataType(filepath): return False except IOError: return False - -- libgit2 0.21.2