Exemple #1
0
    def from_mask(self, mask):
        mask = np.array(mask.matrix[1:, 1:, 1:])
        slic = sl.Slice()
        image = slic.matrix

        mask = to_vtk(mask, spacing=slic.spacing)
        image = to_vtk(image, spacing=slic.spacing)

        flip = vtk.vtkImageFlip()
        flip.SetInputData(image)
        flip.SetFilteredAxis(1)
        flip.FlipAboutOriginOn()
        flip.ReleaseDataFlagOn()
        flip.Update()
        image = flip.GetOutput()

        flip = vtk.vtkImageFlip()
        flip.SetInputData(mask)
        flip.SetFilteredAxis(1)
        flip.FlipAboutOriginOn()
        flip.ReleaseDataFlagOn()
        flip.Update()
        mask = flip.GetOutput()

        # Image
        self.refImage = image

        self._do_surface_creation(mask)
    def run(self):
        global vtk_error

        #----- 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)):
            return False
            
        image = converters.to_vtk(n_array, spacing=(1,1,1),\
                slice_number=1, orientation="AXIAL")


        dim = image.GetDimensions()
        x = dim[0]
        y = dim[1]

        img = vtk.vtkImageResample()
        img.SetInputData(image)
        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()
        write_png.SetInputConnection(img.GetOutputPort())
        write_png.AddObserver("WarningEvent", VtkErrorPNGWriter)
        write_png.SetFileName(thumbnail_path)
        write_png.Write()

        if vtk_error:
            img = vtk.vtkImageCast()
            img.SetInputData(image_copy)
            img.SetOutputScalarTypeToUnsignedShort()
            #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]
        self.bmp_file.Add(bmp_item)
    def run(self):
        global vtk_error

        #----- 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)):
            return False
            
        image = converters.to_vtk(n_array, spacing=(1,1,1),\
                slice_number=1, orientation="AXIAL")


        dim = image.GetDimensions()
        x = dim[0]
        y = dim[1]

        img = vtk.vtkImageResample()
        img.SetInputData(image)
        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()
        write_png.SetInputConnection(img.GetOutputPort())
        write_png.AddObserver("WarningEvent", VtkErrorPNGWriter)
        write_png.SetFileName(thumbnail_path)
        write_png.Write()

        if vtk_error:
            img = vtk.vtkImageCast()
            img.SetInputData(image_copy)
            img.SetOutputScalarTypeToUnsignedShort()
            #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]
        self.bmp_file.Add(bmp_item)
Exemple #4
0
    def LoadImage(self):
        slice_data = slice_.Slice()
        n_array = slice_data.matrix
        spacing = slice_data.spacing
        slice_number = 0
        orientation = 'AXIAL'

        image = converters.to_vtk(n_array, spacing, slice_number, orientation)
        self.image = image
Exemple #5
0
    def LoadImage(self):
        slice_data = slice_.Slice()
        n_array = slice_data.matrix
        spacing = slice_data.spacing
        slice_number = 0
        orientation = 'AXIAL'

        image = converters.to_vtk(n_array, spacing, slice_number, orientation) 
        self.image = image
Exemple #6
0
    def ShowSlice(self, index = 0):
        bitmap = self.bitmap_list[index]

        # UPDATE GUI
        ## Text related to size
        value = STR_SIZE %(bitmap[3], bitmap[4])
        self.text_image_size.SetValue(value)

        value1 = ''
        value2 = ''

        value = "%s\n%s" %(value1, value2)
        self.text_image_location.SetValue(value)


        #self.text_patient.SetValue(value)
        self.text_patient.SetValue('')

        #self.text_acquisition.SetValue(value)
        self.text_acquisition.SetValue('')



        n_array = bitmap_reader.ReadBitmap(bitmap[0])
        
        image = converters.to_vtk(n_array, spacing=(1,1,1),\
                slice_number=1, orientation="AXIAL")


        # ADJUST CONTRAST
        window_level = n_array.max()/2
        window_width = n_array.max()
        
        colorer = vtk.vtkImageMapToWindowLevelColors()
        colorer.SetInputData(image)
        colorer.SetWindow(float(window_width))
        colorer.SetLevel(float(window_level))
        colorer.Update()

        if self.actor is None:
            self.actor = vtk.vtkImageActor()
            self.renderer.AddActor(self.actor)

        # PLOT IMAGE INTO VIEWER
        self.actor.SetInputData(colorer.GetOutput())
        self.renderer.ResetCamera()
        self.interactor.Render()

        # Setting slider position
        self.slider.SetValue(index)
    def ShowSlice(self, index = 0):
        bitmap = self.bitmap_list[index]

        # UPDATE GUI
        ## Text related to size
        value = STR_SIZE %(bitmap[3], bitmap[4])
        self.text_image_size.SetValue(value)

        value1 = ''
        value2 = ''

        value = "%s\n%s" %(value1, value2)
        self.text_image_location.SetValue(value)


        #self.text_patient.SetValue(value)
        self.text_patient.SetValue('')

        #self.text_acquisition.SetValue(value)
        self.text_acquisition.SetValue('')



        n_array = bitmap_reader.ReadBitmap(bitmap[0])
        
        image = converters.to_vtk(n_array, spacing=(1,1,1),\
                slice_number=1, orientation="AXIAL")


        # ADJUST CONTRAST
        window_level = n_array.max()/2
        window_width = n_array.max()
        
        colorer = vtk.vtkImageMapToWindowLevelColors()
        colorer.SetInputData(image)
        colorer.SetWindow(float(window_width))
        colorer.SetLevel(float(window_level))
        colorer.Update()

        if self.actor is None:
            self.actor = vtk.vtkImageActor()
            self.renderer.AddActor(self.actor)

        # PLOT IMAGE INTO VIEWER
        self.actor.SetInputData(colorer.GetOutput())
        self.renderer.ResetCamera()
        self.interactor.Render()

        # Setting slider position
        self.slider.SetValue(index)
Exemple #8
0
    def from_mask_file(self, mask_path):
        slic = sl.Slice()
        image = slic.matrix
        image = to_vtk(image, spacing=slic.spacing)

        # Read the mask
        mask_reader = vtk.vtkNIFTIImageReader()
        mask_reader.SetFileName(mask_path)
        mask_reader.Update()

        mask = mask_reader.GetOutput()

        mask_sFormMatrix = mask_reader.GetSFormMatrix()

        # Image
        self.refImage = image

        self._do_surface_creation(mask, mask_sFormMatrix)
    def ShowBlackSlice(self, pub_sub):
        n_array = numpy.zeros((100,100))
       
        self.text_image_size.SetValue('')

        image = converters.to_vtk(n_array, spacing=(1,1,1),\
                slice_number=1, orientation="AXIAL")

        colorer = vtk.vtkImageMapToWindowLevelColors()
        colorer.SetInputData(image)
        colorer.Update()

        if self.actor is None:
            self.actor = vtk.vtkImageActor()
            self.renderer.AddActor(self.actor)

        # PLOT IMAGE INTO VIEWER
        self.actor.SetInputData(colorer.GetOutput())
        self.renderer.ResetCamera()
        self.interactor.Render()

        # Setting slider position
        self.slider.SetValue(0)
Exemple #10
0
    def ShowBlackSlice(self, pub_sub):
        n_array = numpy.zeros((100, 100))

        self.text_image_size.SetValue('')

        image = converters.to_vtk(n_array, spacing=(1,1,1),\
                slice_number=1, orientation="AXIAL")

        colorer = vtk.vtkImageMapToWindowLevelColors()
        colorer.SetInputData(image)
        colorer.Update()

        if self.actor is None:
            self.actor = vtk.vtkImageActor()
            self.renderer.AddActor(self.actor)

        # PLOT IMAGE INTO VIEWER
        self.actor.SetInputData(colorer.GetOutput())
        self.renderer.ResetCamera()
        self.interactor.Render()

        # Setting slider position
        self.slider.SetValue(0)
Exemple #11
0
    def CreateSurface(self, roi):
        if self.from_binary:
            a_mask = numpy.array(self.mask[roi.start + 1:roi.stop + 1, 1:, 1:])
            image = converters.to_vtk(a_mask, self.spacing, roi.start, "AXIAL")
            del a_mask
        else:
            a_image = numpy.array(self.image[roi])

            if self.algorithm == u'InVesalius 3.b2':
                a_mask = numpy.array(self.mask[roi.start + 1:roi.stop + 1, 1:,
                                               1:])
                a_image[a_mask == 1] = a_image.min() - 1
                a_image[a_mask == 254] = (self.min_value +
                                          self.max_value) / 2.0

                image = converters.to_vtk(a_image, self.spacing, roi.start,
                                          "AXIAL")

                gauss = vtk.vtkImageGaussianSmooth()
                gauss.SetInputData(image)
                gauss.SetRadiusFactor(0.3)
                gauss.ReleaseDataFlagOn()
                gauss.Update()

                del image
                image = gauss.GetOutput()
                del gauss
                del a_mask
            else:
                image = converters.to_vtk(a_image, self.spacing, roi.start,
                                          "AXIAL")
            del a_image

        if self.imagedata_resolution:
            # image = iu.ResampleImage3D(image, self.imagedata_resolution)
            image = ResampleImage3D(image, self.imagedata_resolution)

        flip = vtk.vtkImageFlip()
        flip.SetInputData(image)
        flip.SetFilteredAxis(1)
        flip.FlipAboutOriginOn()
        flip.ReleaseDataFlagOn()
        flip.Update()

        del image
        image = flip.GetOutput()
        del flip

        #filename = tempfile.mktemp(suffix='_%s.vti' % (self.pid))
        #writer = vtk.vtkXMLImageDataWriter()
        #writer.SetInput(mask_vtk)
        #writer.SetFileName(filename)
        #writer.Write()

        #print "Writing piece", roi, "to", filename

        # Create vtkPolyData from vtkImageData
        #print "Generating Polydata"
        #if self.mode == "CONTOUR":
        #print "Contour"
        contour = vtk.vtkContourFilter()
        contour.SetInputData(image)
        #contour.SetInput(flip.GetOutput())
        if self.from_binary:
            contour.SetValue(0, 127)  # initial threshold
        else:
            contour.SetValue(0, self.min_value)  # initial threshold
            contour.SetValue(1, self.max_value)  # final threshold
        contour.ComputeScalarsOn()
        contour.ComputeGradientsOn()
        contour.ComputeNormalsOn()
        contour.ReleaseDataFlagOn()
        contour.Update()
        #contour.AddObserver("ProgressEvent", lambda obj,evt:
        #                    self.SendProgress(obj, _("Generating 3D surface...")))
        polydata = contour.GetOutput()
        del image
        del contour

        #else: #mode == "GRAYSCALE":
        #mcubes = vtk.vtkMarchingCubes()
        #mcubes.SetInput(flip.GetOutput())
        #mcubes.SetValue(0, self.min_value)
        #mcubes.SetValue(1, self.max_value)
        #mcubes.ComputeScalarsOff()
        #mcubes.ComputeGradientsOff()
        #mcubes.ComputeNormalsOff()
        #mcubes.AddObserver("ProgressEvent", lambda obj,evt:
        #self.SendProgress(obj, _("Generating 3D surface...")))
        #polydata = mcubes.GetOutput()

        #triangle = vtk.vtkTriangleFilter()
        #triangle.SetInput(polydata)
        #triangle.AddObserver("ProgressEvent", lambda obj,evt:
        #self.SendProgress(obj, _("Generating 3D surface...")))
        #triangle.Update()
        #polydata = triangle.GetOutput()

        #if self.decimate_reduction:

        ##print "Decimating"
        #decimation = vtk.vtkDecimatePro()
        #decimation.SetInput(polydata)
        #decimation.SetTargetReduction(0.3)
        #decimation.AddObserver("ProgressEvent", lambda obj,evt:
        #self.SendProgress(obj, _("Generating 3D surface...")))
        ##decimation.PreserveTopologyOn()
        #decimation.SplittingOff()
        #decimation.BoundaryVertexDeletionOff()
        #polydata = decimation.GetOutput()

        self.pipe.send(None)

        filename = tempfile.mktemp(suffix='_%s.vtp' % (self.pid))
        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetInputData(polydata)
        writer.SetFileName(filename)
        writer.Write()

        print("Writing piece", roi, "to", filename)
        del polydata
        del writer

        self.q_out.put(filename)
def create_surface_piece(filename, shape, dtype, mask_filename, mask_shape,
                         mask_dtype, roi, spacing, mode, min_value, max_value,
                         decimate_reduction, smooth_relaxation_factor,
                         smooth_iterations, language, flip_image,
                         from_binary, algorithm, imagedata_resolution, fill_border_holes):


    log_path = tempfile.mktemp('vtkoutput.txt')
    fow = vtk.vtkFileOutputWindow()
    fow.SetFileName(log_path)
    ow = vtk.vtkOutputWindow()
    ow.SetInstance(fow)


    pad_bottom = (roi.start == 0)
    pad_top = (roi.stop >= shape[0])

    if fill_border_holes:
        padding = (1, 1, pad_bottom)
    else:
        padding = (0, 0, 0)

    if from_binary:
        mask = numpy.memmap(mask_filename, mode='r',
                                 dtype=mask_dtype,
                                 shape=mask_shape)
        if fill_border_holes:
            a_mask = pad_image(mask[roi.start + 1: roi.stop + 1, 1:, 1:], 0, pad_bottom, pad_top)
        else:
            a_mask = numpy.array(mask[roi.start + 1: roi.stop + 1, 1:, 1:])
        image =  converters.to_vtk(a_mask, spacing, roi.start, "AXIAL", padding=padding)
        del a_mask
    else:
        image = numpy.memmap(filename, mode='r', dtype=dtype,
                                  shape=shape)
        mask = numpy.memmap(mask_filename, mode='r',
                                 dtype=mask_dtype,
                                 shape=mask_shape)
        if fill_border_holes:
            a_image = pad_image(image[roi], numpy.iinfo(image.dtype).min, pad_bottom, pad_top)
        else:
            a_image = numpy.array(image[roi])
        #  if z_iadd:
            #  a_image[0, 1:-1, 1:-1] = image[0]
        #  if z_eadd:
            #  a_image[-1, 1:-1, 1:-1] = image[-1]

        if algorithm == u'InVesalius 3.b2':
            a_mask = numpy.array(mask[roi.start + 1: roi.stop + 1, 1:, 1:])
            a_image[a_mask == 1] = a_image.min() - 1
            a_image[a_mask == 254] = (min_value + max_value) / 2.0

            image =  converters.to_vtk(a_image, spacing, roi.start, "AXIAL", padding=padding)

            gauss = vtk.vtkImageGaussianSmooth()
            gauss.SetInputData(image)
            gauss.SetRadiusFactor(0.3)
            gauss.ReleaseDataFlagOn()
            gauss.Update()

            del image
            image = gauss.GetOutput()
            del gauss
            del a_mask
        else:
            #  if z_iadd:
                #  origin = -spacing[0], -spacing[1], -spacing[2]
            #  else:
                #  origin = 0, -spacing[1], -spacing[2]
            image = converters.to_vtk(a_image, spacing, roi.start, "AXIAL", padding=padding)
        del a_image

    if imagedata_resolution:
        image = ResampleImage3D(image, imagedata_resolution)

    flip = vtk.vtkImageFlip()
    flip.SetInputData(image)
    flip.SetFilteredAxis(1)
    flip.FlipAboutOriginOn()
    flip.ReleaseDataFlagOn()
    flip.Update()

    #  writer = vtk.vtkXMLImageDataWriter()
    #  writer.SetFileName('/tmp/camboja.vti')
    #  writer.SetInputData(flip.GetOutput())
    #  writer.Write()

    del image
    image = flip.GetOutput()
    del flip

    contour = vtk.vtkContourFilter()
    contour.SetInputData(image)
    if from_binary:
        contour.SetValue(0, 127) # initial threshold
    else:
        contour.SetValue(0, min_value) # initial threshold
        contour.SetValue(1, max_value) # final threshold
    #  contour.ComputeScalarsOn()
    #  contour.ComputeGradientsOn()
    #  contour.ComputeNormalsOn()
    contour.ReleaseDataFlagOn()
    contour.Update()

    polydata = contour.GetOutput()
    del image
    del contour

    filename = tempfile.mktemp(suffix='_%d_%d.vtp' % (roi.start, roi.stop))
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetInputData(polydata)
    writer.SetFileName(filename)
    writer.Write()

    print("Writing piece", roi, "to", filename)
    print("MY PID MC", os.getpid())
    return filename
Exemple #13
0
def create_surface_piece(filename, shape, dtype, mask_filename, mask_shape,
                         mask_dtype, roi, spacing, mode, min_value, max_value,
                         decimate_reduction, smooth_relaxation_factor,
                         smooth_iterations, language, flip_image, from_binary,
                         algorithm, imagedata_resolution):
    if from_binary:
        mask = numpy.memmap(mask_filename,
                            mode='r',
                            dtype=mask_dtype,
                            shape=mask_shape)
        a_mask = numpy.array(mask[roi.start + 1:roi.stop + 1, 1:, 1:])
        image = converters.to_vtk(a_mask, spacing, roi.start, "AXIAL")
        del a_mask
    else:
        image = numpy.memmap(filename, mode='r', dtype=dtype, shape=shape)
        mask = numpy.memmap(mask_filename,
                            mode='r',
                            dtype=mask_dtype,
                            shape=mask_shape)
        a_image = numpy.array(image[roi])

        if algorithm == u'InVesalius 3.b2':
            a_mask = numpy.array(mask[roi.start + 1:roi.stop + 1, 1:, 1:])
            a_image[a_mask == 1] = a_image.min() - 1
            a_image[a_mask == 254] = (min_value + max_value) / 2.0

            image = converters.to_vtk(a_image, spacing, roi.start, "AXIAL")

            gauss = vtk.vtkImageGaussianSmooth()
            gauss.SetInputData(image)
            gauss.SetRadiusFactor(0.3)
            gauss.ReleaseDataFlagOn()
            gauss.Update()

            del image
            image = gauss.GetOutput()
            del gauss
            del a_mask
        else:
            image = converters.to_vtk(a_image, spacing, roi.start, "AXIAL")
        del a_image

    if imagedata_resolution:
        image = ResampleImage3D(image, imagedata_resolution)

    flip = vtk.vtkImageFlip()
    flip.SetInputData(image)
    flip.SetFilteredAxis(1)
    flip.FlipAboutOriginOn()
    flip.ReleaseDataFlagOn()
    flip.Update()

    del image
    image = flip.GetOutput()
    del flip

    contour = vtk.vtkContourFilter()
    contour.SetInputData(image)
    if from_binary:
        contour.SetValue(0, 127)  # initial threshold
    else:
        contour.SetValue(0, min_value)  # initial threshold
        contour.SetValue(1, max_value)  # final threshold
    #  contour.ComputeScalarsOn()
    #  contour.ComputeGradientsOn()
    #  contour.ComputeNormalsOn()
    contour.ReleaseDataFlagOn()
    contour.Update()

    polydata = contour.GetOutput()
    del image
    del contour

    filename = tempfile.mktemp(suffix='_%d_%d.vtp' % (roi.start, roi.stop))
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetInputData(polydata)
    writer.SetFileName(filename)
    writer.Write()

    print("Writing piece", roi, "to", filename)
    print("MY PID MC", os.getpid())
    return filename
Exemple #14
0
    def CreateSurface(self, roi):
        if self.from_binary:
            a_mask = numpy.array(self.mask[roi.start + 1: roi.stop + 1,
                                           1:, 1:])
            image =  converters.to_vtk(a_mask, self.spacing, roi.start,
                                       "AXIAL")
            del a_mask
        else:
            a_image = numpy.array(self.image[roi])

            if self.algorithm == u'InVesalius 3.b2':
                a_mask = numpy.array(self.mask[roi.start + 1: roi.stop + 1,
                                               1:, 1:])
                a_image[a_mask == 1] = a_image.min() - 1
                a_image[a_mask == 254] = (self.min_value + self.max_value) / 2.0

                image =  converters.to_vtk(a_image, self.spacing, roi.start,
                                           "AXIAL")

                gauss = vtk.vtkImageGaussianSmooth()
                gauss.SetInputData(image)
                gauss.SetRadiusFactor(0.3)
                gauss.ReleaseDataFlagOn()
                gauss.Update()

                del image
                image = gauss.GetOutput()
                del gauss
                del a_mask
            else:
                image = converters.to_vtk(a_image, self.spacing, roi.start,
                                           "AXIAL")
            del a_image

        if self.imagedata_resolution:
            # image = iu.ResampleImage3D(image, self.imagedata_resolution)
            image = ResampleImage3D(image, self.imagedata_resolution)

        flip = vtk.vtkImageFlip()
        flip.SetInputData(image)
        flip.SetFilteredAxis(1)
        flip.FlipAboutOriginOn()
        flip.ReleaseDataFlagOn()
        flip.Update()

        del image
        image = flip.GetOutput()
        del flip

        #filename = tempfile.mktemp(suffix='_%s.vti' % (self.pid))
        #writer = vtk.vtkXMLImageDataWriter()
        #writer.SetInput(mask_vtk)
        #writer.SetFileName(filename)
        #writer.Write()

        #print "Writing piece", roi, "to", filename

        # Create vtkPolyData from vtkImageData
        #print "Generating Polydata"
        #if self.mode == "CONTOUR":
        #print "Contour"
        contour = vtk.vtkContourFilter()
        contour.SetInputData(image)
        #contour.SetInput(flip.GetOutput())
        if self.from_binary:
            contour.SetValue(0, 127) # initial threshold
        else:
            contour.SetValue(0, self.min_value) # initial threshold
            contour.SetValue(1, self.max_value) # final threshold
        contour.ComputeScalarsOn()
        contour.ComputeGradientsOn()
        contour.ComputeNormalsOn()
        contour.ReleaseDataFlagOn()
        contour.Update()
        #contour.AddObserver("ProgressEvent", lambda obj,evt:
        #                    self.SendProgress(obj, _("Generating 3D surface...")))
        polydata = contour.GetOutput()
        del image
        del contour

        #else: #mode == "GRAYSCALE":
            #mcubes = vtk.vtkMarchingCubes()
            #mcubes.SetInput(flip.GetOutput())
            #mcubes.SetValue(0, self.min_value)
            #mcubes.SetValue(1, self.max_value)
            #mcubes.ComputeScalarsOff()
            #mcubes.ComputeGradientsOff()
            #mcubes.ComputeNormalsOff()
            #mcubes.AddObserver("ProgressEvent", lambda obj,evt:
                                #self.SendProgress(obj, _("Generating 3D surface...")))
            #polydata = mcubes.GetOutput()

        #triangle = vtk.vtkTriangleFilter()
        #triangle.SetInput(polydata)
        #triangle.AddObserver("ProgressEvent", lambda obj,evt:
						#self.SendProgress(obj, _("Generating 3D surface...")))
        #triangle.Update()
        #polydata = triangle.GetOutput()

        #if self.decimate_reduction:
            
            ##print "Decimating"
            #decimation = vtk.vtkDecimatePro()
            #decimation.SetInput(polydata)
            #decimation.SetTargetReduction(0.3)
            #decimation.AddObserver("ProgressEvent", lambda obj,evt:
                            #self.SendProgress(obj, _("Generating 3D surface...")))
            ##decimation.PreserveTopologyOn()
            #decimation.SplittingOff()
            #decimation.BoundaryVertexDeletionOff()
            #polydata = decimation.GetOutput()

        self.pipe.send(None)
        
        filename = tempfile.mktemp(suffix='_%s.vtp' % (self.pid))
        writer = vtk.vtkXMLPolyDataWriter()
        writer.SetInputData(polydata)
        writer.SetFileName(filename)
        writer.Write()

        print "Writing piece", roi, "to", filename
        del polydata
        del writer

        self.q_out.put(filename)
def bitmap2memmap(files, slice_size, orientation, spacing,
                  resolution_percentage):
    """
    From a list of dicom files it creates memmap file in the temp folder and
    returns it and its related filename.
    """
    message = _("Generating multiplanar visualization...")
    update_progress = vtk_utils.ShowProgress(len(files) - 1,
                                             dialog_type="ProgressDialog")

    temp_file = tempfile.mktemp()

    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)

    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)
    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)

    if resolution_percentage == 1.0:
        matrix = numpy.memmap(temp_file, mode='w+', dtype='int16', shape=shape)

    cont = 0
    max_scalar = None
    min_scalar = None

    xy_shape = None
    first_resample_entry = False

    for n, f in enumerate(files):
        image_as_array = bitmap_reader.ReadBitmap(f)

        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)
                first_resample_entry = True

            image = image_resized

        min_aux, max_aux = image.GetScalarRange()
        if min_scalar is None or min_aux < min_scalar:
            min_scalar = min_aux

        if max_scalar is None or max_aux > max_scalar:
            max_scalar = max_aux

        array = numpy_support.vtk_to_numpy(image.GetPointData().GetScalars())

        if array.dtype == 'uint16':
            array = array - 32768 / 2

        array = array.astype("int16")

        if orientation == 'CORONAL':
            array.shape = matrix.shape[0], matrix.shape[2]
            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]
        else:
            array.shape = matrix.shape[1], matrix.shape[2]
            matrix[n] = array

        update_progress(cont, message)
        cont += 1

    matrix.flush()
    scalar_range = min_scalar, max_scalar

    return matrix, scalar_range, temp_file
def bitmap2memmap(files, slice_size, orientation, spacing, resolution_percentage):
    """
    From a list of dicom files it creates memmap file in the temp folder and
    returns it and its related filename.
    """
    message = _("Generating multiplanar visualization...")
    update_progress= vtk_utils.ShowProgress(len(files) - 1, dialog_type = "ProgressDialog")

    temp_file = tempfile.mktemp()

    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)

    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)
    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)


    if resolution_percentage == 1.0:
        matrix = numpy.memmap(temp_file, mode='w+', dtype='int16', shape=shape)
    
    cont = 0
    max_scalar = None
    min_scalar = None

    xy_shape = None
    first_resample_entry = False

    for n, f in enumerate(files):
        image_as_array = bitmap_reader.ReadBitmap(f)

        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)
                first_resample_entry = True

            image = image_resized

        min_aux, max_aux = image.GetScalarRange()
        if min_scalar is None or min_aux < min_scalar:
            min_scalar = min_aux

        if max_scalar is None or max_aux > max_scalar:
            max_scalar = max_aux

        array = numpy_support.vtk_to_numpy(image.GetPointData().GetScalars())

        if array.dtype == 'uint16':
            array = array - 32768/2
       
        array = array.astype("int16")

        if orientation == 'CORONAL':
            array.shape = matrix.shape[0], matrix.shape[2]
            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]
        else:
            array.shape = matrix.shape[1], matrix.shape[2]
            matrix[n] = array
        
        update_progress(cont,message)
        cont += 1

    matrix.flush()
    scalar_range = min_scalar, max_scalar

    return matrix, scalar_range, temp_file
Exemple #17
0
    def ShowSlice(self, index=0):
        try:
            dicom = self.dicom_list[index]
        except IndexError:
            dicom = self.dicom_list[0]

        if self.actor is None:
            self.__init_vtk()

        # UPDATE GUI
        ## Text related to size
        value = STR_SIZE % (dicom.image.size[0], dicom.image.size[1])
        self.text_image_size.SetValue(value)

        ## Text related to slice position
        if not (dicom.image.spacing):
            value1 = ''
        else:
            value1 = STR_SPC % (dicom.image.spacing[2])

        if dicom.image.orientation_label == 'AXIAL':
            value2 = STR_LOCAL % (dicom.image.position[2])
        elif dicom.image.orientation_label == 'CORONAL':
            value2 = STR_LOCAL % (dicom.image.position[1])
        elif dicom.image.orientation_label == 'SAGITTAL':
            value2 = STR_LOCAL % (dicom.image.position[0])
        else:
            value2 = ''

        value = "%s\n%s" % (value1, value2)
        self.text_image_location.SetValue(value)

        ## Text related to patient/ acquisiiton data
        value = STR_PATIENT %(dicom.patient.id,\
                              dicom.acquisition.protocol_name)
        self.text_patient.SetValue(value)

        ## Text related to acquisition date and time
        value = STR_ACQ % (dicom.acquisition.date, dicom.acquisition.time)
        self.text_acquisition.SetValue(value)

        if isinstance(dicom.image.thumbnail_path, list):
            reader = vtkPNGReader()
            if _has_win32api:
                reader.SetFileName(
                    win32api.GetShortPathName(
                        dicom.image.thumbnail_path[index]).encode(
                            const.FS_ENCODE))
            else:
                reader.SetFileName(dicom.image.thumbnail_path[index])
            reader.Update()

            image = reader.GetOutput()
        else:
            filename = dicom.image.file
            if _has_win32api:
                filename = win32api.GetShortPathName(filename).encode(
                    const.FS_ENCODE)

            np_image = imagedata_utils.read_dcm_slice_as_np2(filename)
            vtk_image = converters.to_vtk(np_image, dicom.image.spacing, 0,
                                          'AXIAL')

            # ADJUST CONTRAST
            window_level = dicom.image.level
            window_width = dicom.image.window
            colorer = vtkImageMapToWindowLevelColors()
            colorer.SetInputData(vtk_image)
            colorer.SetWindow(float(window_width))
            colorer.SetLevel(float(window_level))
            colorer.Update()

            image = colorer.GetOutput()

        flip = vtkImageFlip()
        flip.SetInputData(image)
        flip.SetFilteredAxis(1)
        flip.FlipAboutOriginOn()
        flip.ReleaseDataFlagOn()
        flip.Update()

        if self.actor is None:
            self.actor = vtkImageActor()
            self.renderer.AddActor(self.actor)

        self.canvas.modified = True

        # PLOT IMAGE INTO VIEWER
        self.actor.SetInputData(flip.GetOutput())
        self.renderer.ResetCamera()
        self.interactor.Render()

        # Setting slider position
        self.slider.SetValue(index)
Exemple #18
0
def create_surface_piece(filename, shape, dtype, mask_filename, mask_shape,
                         mask_dtype, roi, spacing, mode, min_value, max_value,
                         decimate_reduction, smooth_relaxation_factor,
                         smooth_iterations, language, flip_image, from_binary,
                         algorithm, imagedata_resolution, fill_border_holes):

    log_path = tempfile.mktemp('vtkoutput.txt')
    fow = vtkFileOutputWindow()
    fow.SetFileName(log_path)
    ow = vtkOutputWindow()
    ow.SetInstance(fow)

    pad_bottom = (roi.start == 0)
    pad_top = (roi.stop >= shape[0])

    if fill_border_holes:
        padding = (1, 1, pad_bottom)
    else:
        padding = (0, 0, 0)

    if from_binary:
        mask = numpy.memmap(mask_filename,
                            mode='r',
                            dtype=mask_dtype,
                            shape=mask_shape)
        if fill_border_holes:
            a_mask = pad_image(mask[roi.start + 1:roi.stop + 1, 1:, 1:], 0,
                               pad_bottom, pad_top)
        else:
            a_mask = numpy.array(mask[roi.start + 1:roi.stop + 1, 1:, 1:])
        image = converters.to_vtk(a_mask,
                                  spacing,
                                  roi.start,
                                  "AXIAL",
                                  padding=padding)
        del a_mask
    else:
        image = numpy.memmap(filename, mode='r', dtype=dtype, shape=shape)
        mask = numpy.memmap(mask_filename,
                            mode='r',
                            dtype=mask_dtype,
                            shape=mask_shape)
        if fill_border_holes:
            a_image = pad_image(image[roi],
                                numpy.iinfo(image.dtype).min, pad_bottom,
                                pad_top)
        else:
            a_image = numpy.array(image[roi])
        #  if z_iadd:
        #  a_image[0, 1:-1, 1:-1] = image[0]
        #  if z_eadd:
        #  a_image[-1, 1:-1, 1:-1] = image[-1]

        if algorithm == u'InVesalius 3.b2':
            a_mask = numpy.array(mask[roi.start + 1:roi.stop + 1, 1:, 1:])
            a_image[a_mask == 1] = a_image.min() - 1
            a_image[a_mask == 254] = (min_value + max_value) / 2.0

            image = converters.to_vtk(a_image,
                                      spacing,
                                      roi.start,
                                      "AXIAL",
                                      padding=padding)

            gauss = vtkImageGaussianSmooth()
            gauss.SetInputData(image)
            gauss.SetRadiusFactor(0.3)
            gauss.ReleaseDataFlagOn()
            gauss.Update()

            del image
            image = gauss.GetOutput()
            del gauss
            del a_mask
        else:
            #  if z_iadd:
            #  origin = -spacing[0], -spacing[1], -spacing[2]
            #  else:
            #  origin = 0, -spacing[1], -spacing[2]
            image = converters.to_vtk(a_image,
                                      spacing,
                                      roi.start,
                                      "AXIAL",
                                      padding=padding)
        del a_image

    #  if imagedata_resolution:
    #  image = ResampleImage3D(image, imagedata_resolution)

    flip = vtkImageFlip()
    flip.SetInputData(image)
    flip.SetFilteredAxis(1)
    flip.FlipAboutOriginOn()
    flip.ReleaseDataFlagOn()
    flip.Update()

    #  writer = vtkXMLImageDataWriter()
    #  writer.SetFileName('/tmp/camboja.vti')
    #  writer.SetInputData(flip.GetOutput())
    #  writer.Write()

    del image
    image = flip.GetOutput()
    del flip

    contour = vtkContourFilter()
    contour.SetInputData(image)
    if from_binary:
        contour.SetValue(0, 127)  # initial threshold
    else:
        contour.SetValue(0, min_value)  # initial threshold
        contour.SetValue(1, max_value)  # final threshold
    #  contour.ComputeScalarsOn()
    #  contour.ComputeGradientsOn()
    #  contour.ComputeNormalsOn()
    contour.ReleaseDataFlagOn()
    contour.Update()

    polydata = contour.GetOutput()
    del image
    del contour

    filename = tempfile.mktemp(suffix='_%d_%d.vtp' % (roi.start, roi.stop))
    writer = vtkXMLPolyDataWriter()
    writer.SetInputData(polydata)
    writer.SetFileName(filename)
    writer.Write()

    print("Writing piece", roi, "to", filename)
    print("MY PID MC", os.getpid())
    return filename