def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkXMLImageDataWriter(), 'Writing vtkXMLImageData.',
         ('vtkXMLImageData',), (),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemple #2
0
def numpy_to_vti(image, path):
    """
        Convert a numpy array into a .vti file.

        Args
        ----
            image: 3D ndarray with image data
            path: Where to save the image

        Returns
        -------
            True if writing successful
    """
    import vtk
    assert image.ndim == 3
    dim_x, dim_y, dim_z = image.shape
    image_data = vtk.vtkImageData()
    image_data.SetDimensions(dim_x, dim_y, dim_z)
    image_data.AllocateScalars(vtk.VTK_DOUBLE, 1)

    for i in range(dim_x):
        for j in range(dim_y):
            for k in range(dim_z):
                data = image[i, j, k]
                image_data.SetScalarComponentFromDouble(i, j, k, 0, data)

    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName(path)
    writer.SetInputData(image_data)
    return bool(writer.Write())
    def write_vtk(self, DX=2.0, DY=2.0, DZ=0.05):
        """Reads cell data from vals array and writes into a VTK file called
        'Stratal_Arch.vti' and is a structure grid object. Spacing defaults
        are 2.0/2.0/0.05"""

        vtk_obj = vtkImageData()

        vtk_obj.SetSpacing(DX, DY, DZ)
        vtk_obj.SetDimensions(self.dims[0] + 1, self.dims[1] + 1,
                              self.dims[2] + 1)

        # Start writing from the top of the object to match output from Eclipse
        vtk_obj.SetOrigin(0, 0, self.dims[2] + 1)

        array = vtkIntArray()
        array.SetName("Stratal Architecture")
        array.SetNumberOfComponents(1)

        for z in range(0, self.dims[2]):
            for y in range(0, self.dims[1]):
                for x in range(0, self.dims[0]):
                    val = self.vals[x][y][z]
                    array.InsertNextTuple1(val)
        vtk_obj.GetCellData().AddArray(array)

        vtk_f = vtkXMLImageDataWriter()
        vtk_f.SetFileName("Stratal_Arch.vti")
        vtk_f.SetInputData(vtk_obj)
        vtk_f.Write()
Exemple #4
0
    def __init__(self, module_manager):

        # call parent constructor
        ModuleBase.__init__(self, module_manager)

        self._writer = vtk.vtkXMLImageDataWriter()
        
        # ctor for this specific mixin
        FilenameViewModuleMixin.__init__(
            self,
            'Select a filename',
            'VTK Image Data (*.vti)|*.vti|All files (*)|*',
            {'vtkXMLImageDataWriter': self._writer},
            fileOpen=False)



        module_utils.setup_vtk_object_progress(
            self, self._writer,
            'Writing VTK ImageData')

        self._writer.SetDataModeToBinary()

        # set up some defaults
        self._config.filename = ''
        self._module_manager.sync_module_logic_with_config(self)
Exemple #5
0
def DoCoProcessing(datadescription):
    "Callback to do co-processing for current timestep"
    global coprocessor

    # Update the coprocessor by providing it the newly generated simulation data.
    # If the pipeline hasn't been setup yet, this will setup the pipeline.
    coprocessor.UpdateProducers(datadescription)

    # Write output data, if appropriate.
    coprocessor.WriteData(datadescription)

    # Write image capture (Last arg: rescale lookup table), if appropriate.
    coprocessor.WriteImages(datadescription,
                            rescale_lookuptable=rescale_lookuptable,
                            image_quality=0,
                            padding_amount=imageFileNamePadding)

    # Live Visualization, if enabled.
    coprocessor.DoLiveVisualization(datadescription, "localhost", 22222)

    view = GetActiveView()
    ss = vtk.vtkWindowToImageFilter()
    ss.SetInputBufferTypeToZBuffer()
    ss.SetInput(view.SMProxy.GetRenderWindow())
    ss.Update()
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetInputConnection(ss.GetOutputPort())
    writer.SetFileName("z_buffer_%d.vti" % (view.ViewTime * 10))
    writer.Write()
Exemple #6
0
def saveToVTI(filename, data, s, d, o):
    """ Zapisywanie danych do formatu vti
    data - to numpy array
    s - spacing (sx,sy,sz)
    d - dimensions (dx,dy,dz)
    o - origin (ox,oy,oz)
    """

    grid = vtkImageData()
    grid.SetSpacing(s[0], s[1], s[2])
    grid.SetDimensions(d[0], d[1], d[2])
    grid.SetOrigin(o[0], o[1], o[2])

    n = grid.GetNumberOfPoints()
    array = vtkFloatArray()
    array.SetNumberOfComponents(1)
    array.SetNumberOfTuples(n)
    array.SetVoidArray(data, np.prod(d), 1)
    grid.GetPointData().SetScalars(array)

    writer = vtkXMLImageDataWriter()
    writer.SetCompressorTypeToNone()
    writer.SetEncodeAppendedData(0)
    writer.SetFileName(filename)
    writer.SetInputData(grid)
    writer.Update()
def Export(imagedata, filename, bin=False):
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName(filename)
    if bin:
        writer.SetDataModeToBinary()
    else:
        writer.SetDataModeToAscii()
Exemple #8
0
def write_data(data,x,y,z):
    siz = x*y*z
    fs="%dH"%siz
    print "min(data)=",min(data),"max(data)=",max(data)
    print "size=",siz,"len of data=",len(data)
    ss = struct.pack(fs,*data)
    print "min(ss)=",min(ss),"max(ss)=",max(ss),"len(ss)=",len(ss)
    
    
    importer=vtk.vtkImageImport()
    importer.CopyImportVoidPointer(ss,len(ss))
    importer.SetDataScalarTypeToUnsignedShort()
    #importer.SetDataScalarTypeToUnsignedChar()
    #importer.SetDataScalarType(5)
    importer.SetNumberOfScalarComponents(1)
    importer.SetDataExtent(0,x-1,0,y-1,0,z-1)
    importer.SetWholeExtent(0,x-1,0,y-1,0,z-1)
    importer.Update()
    image = importer.GetOutput()
    #print image
    print "Image scalar range=",image.GetScalarRange()
    print "Image scalar type=",image.GetScalarTypeAsString()
    #print image
    
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetInput(image)
    writer.SetFileName("output.vti")
    print "Writing..."
    writer.Write()
    print "done"
 def exportImage(self, volumeNode, outputFormat, outputFolder):
     writer = vtk.vtkXMLImageDataWriter()
     writer.SetFileName("{0}/{1}.vti".format(outputFolder,
                                             volumeNode.GetName()))
     writer.SetInputData(volumeNode.GetImageData())
     writer.SetCompressorTypeToZLib()
     writer.Write()
    def convert__imageData2vti( self, tag=None ):

        # ------------------------------------------------- #
        # --- [1] Arguments Check                       --- #
        # ------------------------------------------------- #
        if ( tag is None ): sys.exit( "[convert__pointData2vts -@vtkDataManager-] tag == ???" )
        if ( self.Data[tag].pointData      is None ):
            self.Data[tag].generate__pointData()
        # ------------------------------------------------- #
        # --- [2] Preparation                           --- #
        # ------------------------------------------------- #
        imageData_ = vtknp.numpy_to_vtk( self.Data[tag].pointData, deep=True )
        imageData_.SetName( tag )
        # ------------------------------------------------- #
        # --- [3] store points & pointData              --- #
        # ------------------------------------------------- #
        self.image.GetPointData().AddArray( imageData_ )
        self.image.SetExtent ( self.Data[tag].Extent  )
        # ------------------------------------------------- #
        # --- [4] save in vtu File                      --- #
        # ------------------------------------------------- #
        writer = vtk.vtkXMLImageDataWriter()
        if ( self.DataFormat.lower() == "ascii"  ):
            writer.SetDataModeToAscii()
        if ( self.DataFormat.lower() == "binary" ):
            writer.SetDataModeToBinary()
        writer.SetFileName( self.vtkFile )
        writer.SetInputData( self.image )
        writer.Write()
        print( "[vtkDataConverter] output :: {0} ".format( self.vtkFile ) )
def Export(imagedata, filename, bin=False):
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName(filename)
    if bin:
        writer.SetDataModeToBinary()
    else:
        writer.SetDataModeToAscii()
Exemple #12
0
 def __del__(self):
     if self._needWrite:
         import vtk
         vw = vtk.vtkXMLImageDataWriter()
         vw.SetFileName(self._vol_file)
         vw.SetInputData(self._volume)
         vw.Write()
Exemple #13
0
    def write_output(self, species, increment):

        data = vtk.vtkImageData()
        data.SetDimensions(self.extents)
        data.SetOrigin(0, 0, 0)
        spacing = self.spacing
        data.SetSpacing(spacing, spacing, spacing)

        result = vtk.vtkDoubleArray()
        result.SetNumberOfComponents(1)
        result.SetNumberOfTuples(len(self.result))
        if species == "Oxygen":
            result.SetName("Oxygen Concentration")
        elif species == "Factor":
            result.SetName("Factor")

        # VTK uses [X, Y, Z] ordering so need to reverse the list
        # of cells.
        numCells = len(self.result)
        for idx in range(numCells):
            eachValue = self.result[idx]
            result.SetValue(idx, eachValue)

        data.GetPointData().AddArray(result)

        writer = vtk.vtkXMLImageDataWriter()
        writer.SetFileName(self.outputDirectory + "/" + str(self.name) +
                           species + str(increment) + ".vti")
        if vtk.VTK_MAJOR_VERSION <= 5:
            writer.SetInput(data)
        else:
            writer.SetInputData(data)
        writer.Write()
Exemple #14
0
def saveVtk3d(filepath, img, spacing=[1.0, 1.0, 1.0]):
    assert (img.ndim == 3)
    nx, ny, nz = img.shape
    dataImport = vtk.vtkImageImport()
    dataImport.SetNumberOfScalarComponents(1)
    dataImport.SetDataExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    dataImport.SetWholeExtent(0, nx - 1, 0, ny - 1, 0, nz - 1)
    dataType = img.dtype
    if dataType == np.float_ or dataType == np.float64:
        dataImport.SetDataScalarTypeToDouble()
    elif dataType == np.float32:
        dataImport.SetDataScalarTypeToFloat()
    elif dataType == np.int_ or dataType == np.int32:
        dataImport.SetDataScalarTypeToInt()
    elif dataType == np.int16:
        dataImport.SetDataScalarTypeToShort()
    elif dataType == np.uint16:
        dataImport.SetDataScalarTypeToUnsignedShort()
    elif dataType == np.uint8:
        dataImport.SetDataScalarTypeToUnsignedChar()
    else:
        # convert image to unsigned short
        img = utils.nnormalize(img)
        img = np.round(img * 65535.0).astype(np.uint16)
    dataString = img.tostring(order='F')
    dataImport.CopyImportVoidPointer(dataString, len(dataString))
    dataImport.SetDataSpacing(spacing)
    dataImport.Update()
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName(filepath)
    writer.SetInputData(dataImport.GetOutput())
    writer.Write()
    def write_vtk(self, DX=2.0, DY=2.0, DZ=0.05):
        """Reads cell data from vals array and writes into a VTK file called
        'Stratal_Arch.vti' and is a structure grid object. Spacing defaults
        are 2.0/2.0/0.05"""

        vtk_obj = vtkImageData()

        vtk_obj.SetSpacing(DX, DY, DZ)
        vtk_obj.SetDimensions(self.dims[0]+1, self.dims[1]+1, self.dims[2]+1)

        # Start writing from the top of the object to match output from Eclipse
        vtk_obj.SetOrigin(0, 0, self.dims[2]+1)

        array = vtkIntArray()
        array.SetName("Stratal Architecture")
        array.SetNumberOfComponents(1)

        for z in range(0, self.dims[2]):
            for y in range(0, self.dims[1]):
                for x in range(0, self.dims[0]):
                    val = self.vals[x][y][z]
                    array.InsertNextTuple1(val)
        vtk_obj.GetCellData().AddArray(array)

        vtk_f = vtkXMLImageDataWriter()
        vtk_f.SetFileName("Stratal_Arch.vti")
        vtk_f.SetInputData(vtk_obj)
        vtk_f.Write()
Exemple #16
0
 def generate(self, input_path, output_directory, part_name):
     
     input_path = work_dir + "/vtk_image/itk_tile_0_2_6.vti"
     
     reader = vtk.vtkXMLImageDataReader()
     reader.SetFileName(input_path)
     reader.Update()
      
     pad_filter = vtk.vtkImageConstantPad()
     pad_filter.SetInputConnection(reader.GetOutputPort())
     pad_filter.SetConstant(0)
     pad_filter.SetOutputWholeExtent(reader.GetOutput().GetExtent()[0]-5, 
                                     reader.GetOutput().GetExtent()[1]+5, 
                                     reader.GetOutput().GetExtent()[2]-5, 
                                     reader.GetOutput().GetExtent()[3]+5, 
                                     reader.GetOutput().GetExtent()[4]-5, 
                                     reader.GetOutput().GetExtent()[5]+5)
     pad_filter.Update()
      
     writer = vtk.vtkXMLImageDataWriter()
     writer.SetFileName(work_dir + "/surface/itk_tile_0_2_6_pad.vti")
     writer.SetInputConnection(pad_filter.GetOutputPort())
     writer.Update()    
     
     
     myArguments = 'vmtklevelsetsegmentation -ifile ' + work_dir + "/surface/itk_tile_0_2_6_pad.vti" + ' -ofile ' + output_path+"/itk_tile_0_2_6_ls.vti"
  
     myPype = pypes.PypeRun(myArguments)
      
     myArguments = 'vmtkmarchingcubes -ifile ' + output_path+"/itk_tile_0_2_6_ls.vti" + ' -ofile ' + output_path+"/itk_tile_0_2_6_model.vtp"
  
     myPype = pypes.PypeRun(myArguments)
     
Exemple #17
0
def write_vtk_image(vtkIm, fn, M=None):
    """
    This function writes a vtk image to disk
    Args:
        vtkIm: the vtk image to write
        fn: file name
    Returns:
        None
    """
    print("Writing vti with name: ", fn)
    if M is not None:
        M.Invert()
        reslice = vtk.vtkImageReslice()
        reslice.SetInputData(vtkIm)
        reslice.SetResliceAxes(M)
        reslice.SetInterpolationModeToNearestNeighbor()
        reslice.Update()
        vtkIm = reslice.GetOutput()

    _, extension = os.path.splitext(fn)
    if extension == '.vti':
        writer = vtk.vtkXMLImageDataWriter()
    elif extension == '.vtk':
        writer = vtk.vtkStructuredPointsWriter()
    elif extension == '.mhd':
        writer = vtk.vtkMetaImageWriter()
    else:
        raise ValueError("Incorrect extension " + extension)
    writer.SetInputData(vtkIm)
    writer.SetFileName(fn)
    writer.Update()
    writer.Write()
    return
Exemple #18
0
def saveImageToVTI(data, outputFile):
    # Currently, saves only the first time point !

    imageData = vtk.vtkImageData()

    # Sets the vtkImageData object's dimensions to match the data
    lx, ly, lz = data[0].shape
    lt = len(data)
    imageData.SetDimensions(lx, ly, lz)

    # Allocates scalars of the UINT8 type (value=3)
    imageData.AllocateScalars(3, 1)

    writer = vtk.vtkXMLImageDataWriter()

    path, file = os.path.split(outputFile)
    if not os.path.exists(path):
        os.mkdir(path)

    # This function writes the data for one time step into the vtkImageData object,
    # and returns the vtkImageData object

    writer.SetFileName(outputFile)

    for z in range(lz):
        for y in range(ly):
            for x in range(lx):
                imageData.SetScalarComponentFromDouble(x, y, z, 0,
                                                       data[0][x, y, z])

    # Writes the VTI files if requested
    writer.SetInputData(imageData)
    writer.Write()
Exemple #19
0
    def _handlerVoiSaveButton(self, event):
        input_data = self.getPrimaryInput()
        filename = self.controlFrame.voiFilenameText.GetValue()
        if input_data and self._voi_widget.GetEnabled() and filename:
            # see if we need to reset to zero origin
            zor = self.controlFrame.voiResetToOriginCheck.GetValue()

            extractVOI = vtk.vtkExtractVOI()
            extractVOI.SetInput(input_data)
            extractVOI.SetVOI(self._currentVOI)

            writer = vtk.vtkXMLImageDataWriter()
            writer.SetDataModeToBinary()
            writer.SetFileName(filename)
            
            if zor:
                ici = vtk.vtkImageChangeInformation()
                ici.SetOutputExtentStart(0,0,0)
                ici.SetInput(extractVOI.GetOutput())
                writer.SetInput(ici.GetOutput())

            else:
                writer.SetInput(extractVOI.GetOutput())

            writer.Write()
Exemple #20
0
    def _handlerVoiSaveButton(self, event):
        input_data = self.getPrimaryInput()
        filename = self.controlFrame.voiFilenameText.GetValue()
        if input_data and self._voi_widget.GetEnabled() and filename:
            # see if we need to reset to zero origin
            zor = self.controlFrame.voiResetToOriginCheck.GetValue()

            extractVOI = vtk.vtkExtractVOI()
            extractVOI.SetInput(input_data)
            extractVOI.SetVOI(self._currentVOI)

            writer = vtk.vtkXMLImageDataWriter()
            writer.SetDataModeToBinary()
            writer.SetFileName(filename)

            if zor:
                ici = vtk.vtkImageChangeInformation()
                ici.SetOutputExtentStart(0, 0, 0)
                ici.SetInput(extractVOI.GetOutput())
                writer.SetInput(ici.GetOutput())

            else:
                writer.SetInput(extractVOI.GetOutput())

            writer.Write()
Exemple #21
0
def writeVTI(V, filename):
    dims = V.shape

    imageData = vtk.vtkImageData()
    imageData.SetDimensions(dims[1], dims[0], dims[2])
    if vtk.VTK_MAJOR_VERSION <= 5:
        imageData.SetNumberOfScalarComponents(1)
        if V.dtype.type == np.uint8:
            imageData.SetScalarTypeToUnsignedChar()
        elif V.dtype.type == np.double:
            imageData.SetScalarTypeToDouble()
        else:
            sys.stderr.write('Not support data type\n')
    else:
        if V.dtype.type == np.uint8:
            imageData.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
        elif V.dtype.type == np.double:
            imageData.AllocateScalars(vtk.VTK_DOUBLE, 1)
        else:
            sys.stderr.write('Not support data type\n')

    # Fill every entry of the image data with V
    for z in range(dims[2]):
        for y in range(dims[1]):
            for x in range(dims[0]):
                imageData.SetScalarComponentFromDouble(y, x, z, 0, V[x, y, z])

    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName(filename)
    if vtk.VTK_MAJOR_VERSION <= 5:
        writer.SetInputConnection(imageData.GetProducerPort())
    else:
        writer.SetInputData(imageData)
    writer.Write()
def write_image(_data, path_to_image):
    # == make sure data type is unsigned char
    cast = vtk.vtkImageCast()
    if vtk.VTK_MAJOR_VERSION <= 5:
        cast.SetInput(_data)
    else:
        cast.SetInputData(_data)
    cast.SetOutputScalarTypeToUnsignedChar()
    cast.Update()
    _data = cast.GetOutput()
    # == write
    file_ext = fu.get_file_extension(path_to_image)
    if (file_ext == "vti"):
        print("Writing as  '.vti' file.")
        image_writer = vtk.vtkXMLImageDataWriter()
    elif (file_ext == "nii"):
        print("Writing as  '.nii' file.")
        image_writer = vtk.vtkNIFTIImageWriter()
        print(
            "VTK seems to change image orientation of NIFTI. Make sure to check image orientation relative to original image"
        )
    elif (file_ext == "mhd" or file_ext == "mha"):
        print("Writing as .mhd/.raw or .mha image.")
        image_writer = vtk.vtkMetaImageWriter()
        image_writer.SetCompression(False)
    else:
        print("No valid image file extension specified!")
    if vtk.VTK_MAJOR_VERSION <= 5:
        image_writer.SetInput(_data)
    else:
        image_writer.SetInputData(_data)
    image_writer.SetFileName(path_to_image)
    # image_writer.Update()
    image_writer.Write()
    print("Image has been saved as %s " % (path_to_image))
Exemple #23
0
 def write_vtk_field_grid(self, output):
     if self.vtk_field_grid is None:
         raise TypeError("No grid to be written")
     writer = vtk.vtkXMLImageDataWriter()
     writer.SetFileName(output)
     writer.SetInputData(self.vtk_field_grid)
     writer.Write()
Exemple #24
0
def dicom_to_vti(imagedata, filename):
    logging.debug("In data.dicom_to_vti()")
    extent = imagedata.GetWholeExtent()
    spacing = imagedata.GetSpacing()
    origin = imagedata.GetOrigin()

    center = (
        origin[0] + spacing[0] * 0.5 * (extent[0] + extent[1]),
        origin[1] + spacing[1] * 0.5 * (extent[2] + extent[3]),
        origin[2] + spacing[2] * 0.5 * (extent[4] + extent[5]),
    )

    resliceAxes = vtk.vtkMatrix4x4()
    vtkMatrix = (1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
    resliceAxes.DeepCopy(vtkMatrix)
    resliceAxes.SetElement(0, 3, center[0])
    resliceAxes.SetElement(1, 3, center[1])
    resliceAxes.SetElement(2, 3, center[2])

    reslice = vtk.vtkImageReslice()
    reslice.SetInput(imagedata)
    reslice.SetInformationInput(imagedata)
    reslice.SetResliceAxes(resliceAxes)
    reslice.SetOutputDimensionality(3)
    reslice.Update()

    imagedata = reslice.GetOutput()
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetInput(imagedata)
    writer.SetFileName(filename)
    writer.Write()
Exemple #25
0
def histogram3d_to_vtk(histogram3d,
                       filename='histogram.vti',
                       path='.',
                       origin_from_file=True
                       ):

    if origin_from_file is True:
        origin = histogram3d.scoring_mesh_translations
    else:
        origin = [0.0, 0.0, 0.0]

    imgdat = _vtk.vtkImageData()
    imgdat.GetPointData().SetScalars(
        _vtk_np.numpy_to_vtk(
            num_array=histogram3d.values.ravel(order='F'),
            deep=True,
            array_type=_vtk.VTK_FLOAT
        )
    )
    imgdat.SetDimensions(histogram3d.xnumbins, histogram3d.ynumbins, histogram3d.znumbins)
    imgdat.SetOrigin(origin[0] - (histogram3d.coordinates_normalization * (histogram3d.edges[0][-1] - histogram3d.edges[0][0]) / 2) + (histogram3d.coordinates_normalization * (histogram3d.edges[0][1] - histogram3d.edges[0][0]) / 2),
                     origin[1] - (histogram3d.coordinates_normalization * (histogram3d.edges[1][-1] - histogram3d.edges[1][0]) / 2) + (histogram3d.coordinates_normalization * (histogram3d.edges[1][1] - histogram3d.edges[1][0]) / 2),
                     origin[2] - (histogram3d.coordinates_normalization * (histogram3d.edges[2][-1] - histogram3d.edges[2][0]) / 2) + (histogram3d.coordinates_normalization * (histogram3d.edges[2][1] - histogram3d.edges[2][0]) / 2)
                     )
    imgdat.SetSpacing(
        histogram3d.coordinates_normalization * (histogram3d.edges[0][1] - histogram3d.edges[0][0]),
        histogram3d.coordinates_normalization * (histogram3d.edges[1][1] - histogram3d.edges[1][0]),
        histogram3d.coordinates_normalization * (histogram3d.edges[2][1] - histogram3d.edges[2][0])
    )
    writer = _vtk.vtkXMLImageDataWriter()
    writer.SetFileName(os.path.join(path, filename))
    writer.SetInputData(imgdat)
    writer.SetDataModeToBinary()
    writer.Write()
Exemple #26
0
def saveVTKSeg(magDataTemp, cMRA,TOF, pixel_spc, totalNodes, outPath):
        
        
            MagVTK = numpy_support.numpy_to_vtk(num_array=magDataTemp.ravel(order='F'), deep=True, array_type=vtk.VTK_DOUBLE)
                    
            img_vtk = vtk.vtkImageData()
            img_vtk.SetDimensions(magDataTemp.shape)
            img_vtk.AllocateScalars(vtk.VTK_FLOAT,1)
            img_vtk.SetSpacing(pixel_spc)
            img_vtk.SetOrigin(0,0,0)
            img_vtk.GetPointData().SetScalars(MagVTK)        
        
                
            writer = vtk.vtkXMLImageDataWriter()

            if cMRA:
              #  img_vtk.SetName("cMRA")
                writer.SetFileName(outPath + '/cMRAData.vti')
            elif TOF:
              #  img_vtk.SetName("TOF")
                writer.SetFileName(outPath + '/TOFData.vti')                
            else:
               # img_vtk.SetName("Magnitude")
                writer.SetFileName(outPath + '/MagData.vti')

            writer.SetInputData(img_vtk)
            ## This is set so we can see the data in a text editor.
            writer.SetDataModeToAscii()
            writer.Write()

            return 0
Exemple #27
0
 def __del__(self):
     if self._needWrite:
         import vtk
         vw = vtk.vtkXMLImageDataWriter()
         vw.SetFileName(self._vol_file)
         vw.SetInputData(self._volume)
         vw.Write()
Exemple #28
0
    def test_dither_boat(self):
        self.print_param.fill_pattern.value = 1
        self.print_param.skin_offset.value = 1.0
        self.print_param.infill.value = 0.5

        slicer = VoxelSlicer()
        slicer.set_settings(self.printer_setting,
                            self.printhead_setting, self.print_param)
        slicer.SetInputDataObject(self.part)
        slicer.Update()

        slice_stack = slicer.GetOutputDataObject(0)
        img_dim = slice_stack.GetDimensions()
        self.assertTrue(img_dim[2] > 0)
        (x_min, x_max, y_min, y_max, _, _) = slice_stack.GetExtent()

        mid_point = int(img_dim[2]/2)
        single_im = vtk.vtkExtractVOI()
        single_im.SetVOI(x_min, x_max, y_min, y_max, mid_point, mid_point)
        single_im.SetSampleRate(1, 1, 1)
        single_im.SetInputData(slice_stack)
        single_im.Update()

        writer = vtk.vtkBMPWriter()
        writer.SetInputData(single_im.GetOutput())
        writer.SetFileName(os.path.join(self.out_dir, 'test_d.bmp'))
        writer.Update()
        writer.Write()

        writer_3d = vtk.vtkXMLImageDataWriter()
        writer_3d.SetFileName(os.path.join(self.out_dir, 'test_d.vti'))
        writer_3d.SetInputData(slice_stack)
        writer_3d.Update()
        writer_3d.Write()
Exemple #29
0
def save_to_vti(imagedata, file_output):
    print("Saving")
    w = vtk.vtkXMLImageDataWriter()
    w.SetInputData(imagedata)
    w.SetFileName(file_output)
    w.Write()
    print("Saved")
Exemple #30
0
 def WriteVTKXMLImageFile(self):
     if (self.OutputFileName == ''):
         self.PrintError('Error: no OutputFileName.')
     self.PrintLog('Writing VTK XML image file.')
     writer = vtk.vtkXMLImageDataWriter()
     writer.SetInputData(self.Image)
     writer.SetFileName(self.OutputFileName)
     writer.Write()
Exemple #31
0
 def WriteVTKXMLImageFile(self):
     if self.OutputFileName == "":
         self.PrintError("Error: no OutputFileName.")
     self.PrintLog("Writing VTK XML image file.")
     writer = vtk.vtkXMLImageDataWriter()
     writer.SetInput(self.Image)
     writer.SetFileName(self.OutputFileName)
     writer.Write()
Exemple #32
0
 def WriteVTKXMLImageFile(self):
     if (self.OutputFileName == ''):
         self.PrintError('Error: no OutputFileName.')
     self.PrintLog('Writing VTK XML image file.')
     writer = vtk.vtkXMLImageDataWriter()
     writer.SetInputData(self.Image)
     writer.SetFileName(self.OutputFileName)
     writer.Write()
Exemple #33
0
 def CreateSampledvtkFile(self):
     # 1: presume we are reading a cellVis snapshot
     # 2: use x-axis limits to create a smaller matrix
     # 3: be lazy and use a full matrix - preallocation may make it faster
     # 4: This shirt is too tight.
     # 5: Use vtk python bindings.
     n_x = self.x_max - self.x_min + 1
     n_y = self.y_max - self.y_min + 1
     n_z = self.z_max - self.z_min + 1
     # this offset is designed to put x_min, y_min, z_min at 0,0,0
     offset_x = self.o_nx / 2 - self.x_min
     offset_y = self.o_ny / 2 - self.y_min
     offset_z = self.o_nz / 2 - self.z_min
     # determine var locations
     field_names = self.old_file.header_vars["field_names"].split()
     i_rx = field_names.index("rx")
     i_ry = field_names.index("ry")
     i_rz = field_names.index("rz")
     i_vm = field_names.index("Vm")
     grid = vtk.vtkImageData()
     grid.SetOrigin(0, 0, 0)
     dx = 0.2  # float(self.old_file.header_vars["dx"])
     dy = 0.2  # float(self.old_file.header_vars["dy"])
     dz = 0.2  # float(self.old_file.header_vars["dz"])
     grid.SetSpacing(dx, dy, dz)
     grid.SetDimensions((n_x + 1), (n_y + 1), (n_z + 1))
     array = vtk.vtkDoubleArray()
     array.SetNumberOfComponents(1)
     array.SetNumberOfTuples(grid.GetNumberOfCells())
     print "N tuples: ", array.GetNumberOfTuples()
     for ii in range(array.GetNumberOfTuples()):
         array.SetValue(ii, -1000.0)
     array.SetName("Vm")
     print 'parsing records'
     for record in self.old_file:
         fields = record.split()
         x = int(fields[i_rx]) + offset_x
         y = int(fields[i_ry]) + offset_y
         z = int(fields[i_rz]) + offset_z
         vm = float(fields[i_vm])
         if ((x < n_x) and (x >= 0) and (y < n_y) and (y >= 0) and (z < n_z)
                 and (z >= 0)):
             # Now lets calculate the effective GID
             vtkGID = x + n_x * (y + n_y * z)
             if vtkGID < grid.GetNumberOfCells():
                 array.SetValue(vtkGID, vm)
             else:
                 print 'to big'
     print 'Array constructed'
     grid.GetCellData().AddArray(array)
     print 'Added to grid'
     writer = vtk.vtkXMLImageDataWriter()
     writer.SetFileName((self.new_dir + os.sep + "subset.vti"))
     writer.SetInputConnection(grid.GetProducerPort())
     print 'writing'
     writer.Write()
     print 'done'
Exemple #34
0
def write_vtu(name, pd):
    """ Writes a VTU file
    @param name          file name including the file extension ("name.vtp")   
    @param pd            grid represented as vtkPolyData object
    """
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName(name)
    writer.SetInputData(pd)
    writer.Write()
Exemple #35
0
def write_sp(pd):
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName("mean_flow.vti")
    if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
      writer.SetInput(pd)
    else:
      writer.SetInputData(pd)
    writer.Write()
    return
Exemple #36
0
    def OnSaveImage(self, e):
        path = self._dialog_save()
        if path:
            vtkimg = to_vtk(self.m_input, self.spacing)

            w = vtk.vtkXMLImageDataWriter()
            w.SetFileName(path)
            w.SetInputData(vtkimg)
            w.Write()
Exemple #37
0
def write_sp(pd):
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName("mean_flow.vti")
    if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
        writer.SetInput(pd)
    else:
        writer.SetInputData(pd)
    writer.Write()
    return
Exemple #38
0
 def write_to_file(self, fname):
     
     if self.__data is not None:
         writer = vtk.vtkXMLImageDataWriter()
         writer.SetFileName(fname)
         writer.SetInput(self.__data)
         writer.Write()
     else:
         print "vtk object does not exist. Use VTKStructuredPoints.create_vtk_structured_points to initialize it"
    def test_load_data(self):
        vol = utils.dataloader.load_file(self.path_file)

        output_path = os.path.join(self.output_path, '23_30.vti')

        writer = vtk.vtkXMLImageDataWriter()
        writer.SetFileName(output_path)
        writer.SetInputData(vol)

        writer.Write()
Exemple #40
0
    def OnSaveMask(self, e):
        path = self._dialog_save()
        if path:
            mask = numpy.array(self.m_mask[1:, 1:, 1:])
            vtkimg = to_vtk(mask, self.spacing)

            w = vtk.vtkXMLImageDataWriter()
            w.SetFileName(path)
            w.SetInputData(vtkimg)
            w.Write()
Exemple #41
0
def main():
    filename = get_program_parameters()
    colors = vtk.vtkNamedColors()

    image_data = vtk.vtkImageData()

    image_data.SetDimensions(3, 4, 5)
    image_data.AllocateScalars(vtk.VTK_DOUBLE, 1)

    dims = image_data.GetDimensions()

    # Fill every entry of the image data with "2.0"
    for z in range(0, dims[2]):
        for y in range(0, dims[1]):
            for x in range(0, dims[0]):
                pixel = image_data.GetScalarPointer(x, y, z)

    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName(filename)
    writer.SetInputData(image_data)
    writer.Write()

    # Read the file(to test that it was written correctly)
    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(filename)
    reader.Update()

    # Convert the image to a polydata
    image_data_geometry_filter = vtk.vtkImageDataGeometryFilter()
    image_data_geometry_filter.SetInputConnection(reader.GetOutputPort())
    image_data_geometry_filter.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(image_data_geometry_filter.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetPointSize(3)

    # Setup rendering
    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.SetBackground(1, 1, 1)
    renderer.ResetCamera()

    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)

    render_window_interactor = vtk.vtkRenderWindowInteractor()
    renderer.SetBackground(colors.GetColor3d("Azure"))

    render_window_interactor.SetRenderWindow(render_window)
    render_window.Render()
    render_window_interactor.Initialize()
    render_window_interactor.Start()
Exemple #42
0
	def keyPressEvent(self, event):
		if event.key() == QtCore.Qt.Key_Space:
			if event.modifiers() == QtCore.Qt.NoModifier:
				self.WordleView.Modified()
				self.WordleView.Update()
			elif event.modifiers() == QtCore.Qt.ShiftModifier:
				self.table.Modified()
				self.WordleView.Update()
		
		# Change Fonts (f)
		if event.key() == QtCore.Qt.Key_F:
			if self.font_flag:
				self.WordleView.SetFontFamily("Tekton Pro")
			else:
				self.WordleView.SetFontFamily("Rockwell")
			self.font_flag = not self.font_flag
			self.WordleView.Update()
		
		# Write PNG (n)
		# Trying to use a integer-based QImage
		if event.key() == QtCore.Qt.Key_N:
			self.WordleView.SaveImage("out.png")
		
		# Grab ImageData (i)
		if event.key() == QtCore.Qt.Key_I:
			image = self.WordleView.GetImageData()
			# print image
			iw = vtk.vtkXMLImageDataWriter()
			iw.SetInput(image)
			iw.SetFileName("out.vti")
			iw.Write()
		
		# Write PDF (p)
		if event.key() == QtCore.Qt.Key_P:
			self.WordleView.SavePDF("out.pdf")
		
		# Write SVG (s)
		# SVG generation not compiled in by default...
		# if event.key() == QtCore.Qt.Key_S:
		# 	self.WordleView.SaveSVG("out.svg")
	
		# Switch only colors
		if event.key() == QtCore.Qt.Key_C:
			self.color_by_array = not self.color_by_array
			if event.modifiers() == QtCore.Qt.NoModifier:
				self.WordleView.SetColorByArray(self.color_by_array)
				self.WordleView.Update()
			elif event.modifiers() == QtCore.Qt.ShiftModifier:
				if self.color_by_array:
					self.WordleView.ApplyViewTheme(self.vt)
				else:
					self.WordleView.ApplyViewTheme(self.vt2)
				self.WordleView.Update()
def vtkImageData2vti(filePath, source):
    """Export a ``vtk.vtkImageData`` object to VTI file.
    
    Parameters
    ----------
    filePath : str
        Full path for the VTI to be created.
        
    source : vtk.vtkImageData
        object.
    
    """
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName(filePath)
    writer.SetInput(source)
    writer.Write()
def writeImage(
        image,
        filename,
        verbose=1):

    myVTK.myPrint(verbose, "*** writeImage: " + filename + " ***")

    if ('vtk' in filename):
        image_writer = vtk.vtkImageWriter()
    elif ('vti' in filename):
        image_writer = vtk.vtkXMLImageDataWriter()
    else:
        assert 0, "File must be .vtk or .vti. Aborting."

    image_writer.SetFileName(filename)
    image_writer.SetInputData(image)
    image_writer.Update()
    image_writer.Write()
Exemple #45
0
 def getWriter(self,polyData):
     writer = None;
     if self.destFormat == "vti":
         writer = vtk.vtkXMLImageDataWriter();
         writer.SetFileName(self.dest);
     elif self.destFormat in ("mha","mhd","raw"):
         writer = vtk.vtkMetaImageWriter();
         writer.SetFilePrefix(self.dest);
         writer.SetFileName(self.dest);
     elif self.destFormat == "mnc":
         writer = vtk.vtkMINCImageWriter();
         writer.SetFileName(self.dest);
         writer.StrictValidationOff();
     elif self.destFormat == "vtk":
         writer = vtk.vtkUnstructuredGridWriter();
         writer.SetFileName(self.dest);
     writer.SetInputData(polyData);
     writer.Update();
     return writer;
Exemple #46
0
def save_image_data(handle, image_data):
    """
    Save vtkImageData to XML file.

    :param handle: file name
    :param image_data: source

    :type handle: str
    :type image_data: :py:class:`vtk.vtkImageData`

    >>> image_data = create_image_data(32, 32, 32)
    >>> save_image_data('test.vit', image_data)
    """
    stub, ext = os.path.splitext(handle)
    handle = stub + '.vti'
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetInput(image_data)
    writer.SetFileName(handle)
    writer.Write()
	def WriteToFile(self, imageData, exportFileName, fileType):
		if fileType == DataReader.TypeMHD:
			if not exportFileName.endswith(".mhd"):
				exportFileName = exportFileName + ".mhd"
			writer = vtkMetaImageWriter()
			writer.SetFileName(exportFileName)
			writer.SetInputData(imageData)
			writer.Write()
		elif fileType == DataReader.TypeVTI:
			writer = vtkXMLImageDataWriter()
			writer.SetFileName(exportFileName)
			writer.SetInputData(imageData)
			writer.Write()
		elif fileType == DataReader.TypeMHA:
			writer = vtkMetaImageWriter()
			writer.SetFileName(exportFileName)
			writer.SetInputData(imageData)
			writer.Write()
		else:
			raise NotImplementedError("No writing support for type " + str(fileType))
    def write_file(self):
        """Writes all VTK grids in self.grid to VTI files"""

        for key, value in self.grid.iteritems():
            # creates directory for each term in Eclipse project directory
            # root for all VTI files is dated by parser runtime date
            dir_name = path.join(self.dir, time.strftime("%d_%m_%Y"))
            dir_name = path.join(dir_name, key)

            try:
                makedirs(dir_name)
            except OSError:
                pass

            i = 1
            for each in tqdm(value, "Writing "+key+" vtk files"):
                legacy = vtkXMLImageDataWriter()
                legacy.SetFileName(path.join(dir_name, key + str(i) + '.vti'))
                legacy.SetInputData(each)
                legacy.Write()
                i += 1
def write_vtk(arr, DX=2.0, DY=2.0, DZ=.05, x_dim=500, y_dim=500, z_dim=600):
    vtk = vtkImageData()

    vtk.SetSpacing(DX, DY, DZ)
    vtk.SetDimensions(x_dim+1, y_dim+1, z_dim+1)
    vtk.SetOrigin(0, 0, 0)

    vtk_arr = vtkFloatArray()
    vtk_arr.SetName("Stratal Permiablities")
    vtk_arr.SetNumberOfComponents(1)

    for z in range(z_dim):
        for y in range(y_dim):
            for x in range(x_dim):
                vtk_arr.InsertNextTuple1(arr[z][y][x])
    vtk.GetCellData().AddArray(vtk_arr)

    vtk_writer = vtkXMLImageDataWriter()
    vtk_writer.SetFileName("Stratal_Perms.vti")
    vtk_writer.SetInputData(vtk)
    vtk_writer.Write()
	def writeImageData(self, imageData, filename, callback = None):
		"""
		Writes the given vtkImageData-instance to disk
					 as .vti-file with the given filename
		Parameters:   imageData  vtkImageData-instance to be written
					  filename	filename to be used
		"""
		writer = vtk.vtkXMLImageDataWriter()
		writer.SetFileName(filename)
		#imageData.Update()
		#imageData.UpdateInformation()
		x, y, z = imageData.GetDimensions()
		self.outputDims = (x,y,z)
		
		pieces = (x * y * z) / (1024 * 1024)
		if pieces < 4:pieces = 4
		#writer.SetNumberOfPieces(pieces)
		writer.SetInput(imageData)
		def f(obj, evt):
			if obj and callback:
				callback(obj.GetProgress())
			if scripting.mainWindow:
				scripting.mainWindow.updateProgressBar(obj, evt, obj.GetProgress(),"Writing %s"%os.path.basename(filename), 0)
		writer.AddObserver("ProgressEvent", lib.messenger.send)
		lib.messenger.connect(writer, "ProgressEvent", f)
		Logging.info("Performing the write",kw="pipeline")
		try:
			ret = writer.Write()
			x, y, z = imageData.GetDimensions()
			
			self.outputDims = (x,y,z)
			if ret == 0:
				Logging.error("Failed to write image data",
				"Failed to write vtkImageData object to file %s" % self.filename)
				return
		except Exception, ex:
			Logging.error("Failed to write image data",
			"Failed to write vtkImageData object to file %s" % self.filename, ex)
			return
def writeImage(
        image,
        filename,
        verbose=0):

    mypy.my_print(verbose, "*** writeImage: "+filename+" ***")

    if ('vtk' in filename):
        image_writer = vtk.vtkImageWriter()
    elif ('vti' in filename):
        image_writer = vtk.vtkXMLImageDataWriter()
    else:
        assert 0, "File must be .vtk or .vti. Aborting."

    mypy.my_print(verbose, "n_points = "+str(image.GetNumberOfPoints()))

    image_writer.SetFileName(filename)
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        image_writer.SetInputData(image)
    else:
        image_writer.SetInput(image)
    image_writer.Update()
    image_writer.Write()
Exemple #52
0
def revti(name):
    in_vtifname = name
    out_vtifname = "/tmp/"+os.path.basename( os.path.splitext(name)[0] )+'.vti'
    
    reader = vtk.vtkXMLPImageDataReader()
    reader.SetFileName(in_vtifname)
    reader.Update()
    data = reader.GetOutput()
    cd = data.GetCellData()
    
    
    
    
    
    k = 0
    bc = cd.GetNumberOfArrays()
    while cd.GetNumberOfArrays() > len(save) or k > 10:
        k = k + 1
                
        for i in range(cd.GetNumberOfArrays()):
            if not ( cd.GetArrayName(i) in save ):
#                print "Removing:", cd.GetArrayName(i)
                cd.RemoveArray(cd.GetArrayName(i))
                break
#            else:
#                print "Keeping:", cd.GetArrayName(i)   
            
            
            
    print out_vtifname +" : ", bc, '/', cd.GetNumberOfArrays()
    
    
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetFileName(out_vtifname)
    
    writer.SetInputData(data)
    writer.Write()
	def writeDatasets(self, event = None):
		"""
		A method that writes the datasets
		"""
		dirname = self.browsedir.GetValue()
		pattern = self.patternEdit.GetValue()

		if self.imageMode == 0:
			ext = "ome.tif"
			writer = vtkbxd.vtkOMETIFFWriter()
		elif self.imageMode == 2:
			fext = self.vtkmenu.GetString(self.vtkmenu.GetSelection())		
			if fext.find("XML") != -1:
				ext = "vti"
				writer = vtk.vtkXMLImageDataWriter()
			else:
				ext = "vtk"
				writer = vtk.vtkDataSetWriter()
		else:
			return

		pattern = os.path.join(dirname,pattern) + "." + ext
		self.dlg = wx.ProgressDialog("Writing", "Writing dataset %d / %d" % (0, 0), maximum = self.imageAmnt, parent = self, style = wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_AUTO_HIDE)

		filenames = self.sourceListbox.GetItems()
		if len(filenames) != self.c * self.t:
			return

		if self.imageMode == 0: # vtkOMETIFFWriter specific
			writer.SetFileNamePattern(pattern)
			writer.SetTimePoints(self.t)
			writer.SetChannels(self.c)
			# Create uuids
			if self.imageAmnt > 1:
				for i in range(self.imageAmnt):
					uid = uuid.uuid4()
					writer.SetUUID(i,uid.get_urn())
			
			for c in range(self.c):
				ch_name = self.dataUnits[c].getName()
				excitation = int(self.dataUnits[c].getExcitationWavelength())
				emission = int(self.dataUnits[c].getEmissionWavelength())
				writer.SetChannelInfo(ch_name, excitation, emission)
		
		i = 0
		for c in range(self.c):
			imageName = self.dataUnits[c].getImageName()
			voxelSize = self.dataUnits[c].getVoxelSize()
			if self.t > 1:
				try:
					timeInc = self.dataUnits[c].getTimeStamp(1) - self.dataUnits[c].getTimeStamp(0)
				except:
					timeInc = 0.0
			
			for t in range(self.t):
				filenm = filenames[i]
				i += 1
				self.dlg.Update(i, "Writing dataset %d / %d" % (i, self.imageAmnt))
				if self.imageMode == 0:
					writer.SetCurrentChannel(c)
					writer.SetCurrentTimePoint(t)
					writer.SetImageName(imageName)
					writer.SetXResolution(voxelSize[0] * 10**6)
					writer.SetYResolution(voxelSize[1] * 10**6)
					writer.SetZResolution(voxelSize[2] * 10**6)
					if self.t > 1:
						writer.SetTimeIncrement(timeInc)
				writer.SetFileName(filenm)
				data = self.dataUnits[c].getTimepoint(t)
				data.SetUpdateExtent(data.GetWholeExtent())
				data.Update()
				writer.SetInput(data)
				writer.Write()
		self.dlg.Destroy()
Exemple #54
0
def write_vti(filename, atoms, data=None):
    from vtk import vtkStructuredPoints, vtkDoubleArray, vtkXMLImageDataWriter

    #if isinstance(fileobj, str):
    #    fileobj = paropen(fileobj, 'w')
        
    if isinstance(atoms, list):
        if len(atoms) > 1:
            raise ValueError('Can only write one configuration to a VTI file!')
        atoms = atoms[0]

    if data is None:
        raise ValueError('VTK XML Image Data (VTI) format requires data!')

    data = np.asarray(data)

    if data.dtype == complex:
        data = np.abs(data)

    cell = atoms.get_cell()

    assert np.all(cell==np.diag(cell.diagonal())), 'Unit cell must be orthogonal'

    bbox = np.array(list(zip(np.zeros(3),cell.diagonal()))).ravel()

    # Create a VTK grid of structured points
    spts = vtkStructuredPoints()
    spts.SetWholeBoundingBox(bbox)
    spts.SetDimensions(data.shape)
    spts.SetSpacing(cell.diagonal() / data.shape)
    #spts.SetSpacing(paw.gd.h_c * Bohr)

    #print 'paw.gd.h_c * Bohr=',paw.gd.h_c * Bohr
    #print 'atoms.cell.diagonal() / data.shape=', cell.diagonal()/data.shape
    #assert np.all(paw.gd.h_c * Bohr==cell.diagonal()/data.shape)

    #s = paw.wfs.kpt_u[0].psit_nG[0].copy()
    #data = paw.get_pseudo_wave_function(band=0, kpt=0, spin=0, pad=False)
    #spts.point_data.scalars = data.swapaxes(0,2).flatten()
    #spts.point_data.scalars.name = 'scalars'

    # Allocate a VTK array of type double and copy data
    da = vtkDoubleArray()
    da.SetName('scalars')
    da.SetNumberOfComponents(1)
    da.SetNumberOfTuples(np.prod(data.shape))

    for i,d in enumerate(data.swapaxes(0,2).flatten()):
        da.SetTuple1(i,d)

    # Assign the VTK array as point data of the grid
    spd = spts.GetPointData() # type(spd) is vtkPointData
    spd.SetScalars(da)

    """
    from vtk.util.vtkImageImportFromArray import vtkImageImportFromArray
    iia = vtkImageImportFromArray()
    #iia.SetArray(Numeric_asarray(data.swapaxes(0,2).flatten()))
    iia.SetArray(Numeric_asarray(data))
    ida = iia.GetOutput()
    ipd = ida.GetPointData()
    ipd.SetName('scalars')
    spd.SetScalars(ipd.GetScalars())
    """

    # Save the ImageData dataset to a VTK XML file.
    w = vtkXMLImageDataWriter()

    if fast:
        w.SetDataModeToAppend()
        w.EncodeAppendedDataOff()
    else:
        w.SetDataModeToAscii()

    w.SetFileName(filename)
    w.SetInput(spts)
    w.Write()
Exemple #55
0
def getthresh(args):
    inputfile = args[0] 
    outputfile = args[1]
    sx = args[2]
    ex = args[3]
    sy = args[4]
    ey = args[5]
    sz = args[6]
    ez = args[7]
    dataset = args[8]
    comptype = args[9]
    print ("Loading file, %s" % inputfile)
    #Determine if file is h5 or numpy
    if (inputfile.split(".")[1] == "npy"):
        rs = timeit.default_timer()
        vel = np.load(inputfile)
        re = timeit.default_timer()
    else:
        #read in file
        rs = timeit.default_timer()
        data_file = h5py.File(inputfile, 'r')
        vel = np.array(data_file[dataset])
        data_file.close()
        re = timeit.default_timer()

    cs = timeit.default_timer()
    #convert numpy array to vtk
    vtkdata = numpy_support.numpy_to_vtk(vel.flat, deep=True, array_type=vtk.VTK_FLOAT)
    vtkdata.SetNumberOfComponents(3)
    vtkdata.SetName("Velocity")
    image = vtk.vtkImageData()
    image.GetPointData().SetVectors(vtkdata)
    image.SetExtent(sx,ex,sy,ey,sz,ez)
    #NOTE: Hardcoding Spacing

    image.SetSpacing(.006135923, .006135923, .006135923)
    print ("Doing computation")
    ce = timeit.default_timer()
    vs = timeit.default_timer()
    if (comptype == "v"):
        vorticity = vtk.vtkCellDerivatives()
        vorticity.SetVectorModeToComputeVorticity()
        vorticity.SetTensorModeToPassTensors()
        vorticity.SetInputData(image)
        vorticity.Update()
    elif (comptype == "q"):
        vorticity = vtk.vtkGradientFilter()
        vorticity.SetInputData(image)
        vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
        vorticity.ComputeQCriterionOn()
        vorticity.SetComputeGradient(0)
        vorticity.Update()
    ve = timeit.default_timer()
    #Generate contour for comparison
    c = vtk.vtkContourFilter()
    c.SetValue(0,1128)
    if (comptype == "q"):
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    else:
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors())
        
    c.SetInputData(image)
    
    c.Update()
    w = vtk.vtkXMLPolyDataWriter()
    w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write
    w.SetFileName("contour.vtp")
    w.SetInputData(c.GetOutput())
    ws = timeit.default_timer()
    w.Write()


    ms = timeit.default_timer()
    if (comptype == "v"):
        mag = vtk.vtkImageMagnitude()
        cp = vtk.vtkCellDataToPointData()
        cp.SetInputData(vorticity.GetOutput())
        cp.Update()
        image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
        mag.SetInputData(image)
        mag.Update()
        m = mag.GetOutput()
        m.GetPointData().RemoveArray("Velocity")
    else:
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    me = timeit.default_timer()
    print ("Thresholding.")
    ts = timeit.default_timer()
    t = vtk.vtkImageThreshold()
    #t = vtk.vtkThreshold() #sparse representation

    if (comptype == "q"):
        t.SetInputData(image)
        t.ThresholdByUpper(783.3) #.25*67.17^2 = 1127
        #t.SetInputArrayToProcess(0,0,0, vorticity.GetOutput().FIELD_ASSOCIATION_POINTS, "Q-criterion")
        print("q criterion")
    else:
        t.SetInputData(m)
        t.SetInputArrayToProcess(0,0,0, mag.GetOutput().FIELD_ASSOCIATION_POINTS, "Magnitude")
        t.ThresholdByUpper(44.79) #44.79)
    #Set values in range to 1 and values out of range to 0
    t.SetInValue(1)
    t.SetOutValue(0)
    #t.ReplaceInOn()
    #t.ReplaceOutOn()
    print("Update thresh")
    t.Update()
    #wt = vtk.vtkXMLImageDataWriter()
    #wt.SetInputData(t.GetOutput())
    #wt.SetFileName("thresh.vti")
    #wt.Write()

    d = vtk.vtkImageDilateErode3D()
    d.SetInputData(t.GetOutput())
    d.SetKernelSize(3,3,3)
    d.SetDilateValue(1)
    d.SetErodeValue(0)
    print ("Update dilate")
    d.Update()

    iis = vtk.vtkImageToImageStencil()
    iis.SetInputData(d.GetOutput())
    iis.ThresholdByUpper(1)
    stencil = vtk.vtkImageStencil()
    stencil.SetInputConnection(2, iis.GetOutputPort())
    stencil.SetBackgroundValue(0)
    #image.GetPointData().RemoveArray("Vorticity")
    #Set scalars to velocity so it can be cut by the stencil
    image.GetPointData().SetScalars(image.GetPointData().GetVectors())
    #if (comptype == "q"):  #Use this to get just q-criterion data instead of velocity data.  Do we need both?
    #    image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetScalars("Q-criterion"))
    stencil.SetInputData(image)
    print ("Update stencil")    
    stencil.Update()
    te = timeit.default_timer()
    print("Setting up write")
    ws = timeit.default_timer()
    #Make velocity a vector again
    velarray = stencil.GetOutput().GetPointData().GetScalars()
    image.GetPointData().RemoveArray("Velocity")
    image.GetPointData().SetVectors(velarray)
    w = vtk.vtkXMLImageDataWriter()
    w.SetCompressorTypeToZLib()
    #w.SetCompressorTypeToNone() Need to figure out why this fails.
    w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write
    w.SetFileName(outputfile)
    w.SetInputData(image)
    if (0):
        w.SetCompressorTypeToZfp()
        w.GetCompressor().SetNx(ex-sx+1)
        w.GetCompressor().SetNy(ey-sy+1)
        w.GetCompressor().SetNz(ez-sz+1)
        w.GetCompressor().SetTolerance(1e-1)
        w.GetCompressor().SetNumComponents(3)

    w.Write()
    we = timeit.default_timer()

    print("Results:")
    print("Read time: %s" % str(re-rs))
    print ("Convert to vtk: %s" % str(ce-cs))
    if (comptype == "q"):
        print ("Q Computation: %s" % str(ve-vs))
        print ("Q Magnitude: %s" % str(me-ms))
    else:
        print ("Vorticity Computation: %s" % str(ve-vs))
        print ("Vorticity Magnitude: %s" % str(me-ms))
    print ("Threshold: %s" % str(te-ts))
    print ("Write %s" % str(we-ws))
    print ("Total time: %s" % str(we-rs))
#!/usr/bin/env python

import os
import vtk
from vtk.util.misc import vtkGetDataRoot
from vtk.util.misc import vtkGetTempDir

VTK_DATA_ROOT = vtkGetDataRoot()
VTK_TEMP_DIR = vtkGetTempDir()

rt = vtk.vtkRTAnalyticSource()
rt.Update()

inp = rt.GetOutput()
inp.GetInformation().Set(vtk.vtkDataObject.DATA_TIME_STEP(), 11)

file_root = VTK_TEMP_DIR + '/testxmlfield'
file0 = file_root + ".vti"

w = vtk.vtkXMLImageDataWriter()
w.SetInputData(inp)
w.SetFileName(file0)
w.Write()

r = vtk.vtkXMLImageDataReader()
r.SetFileName(file0)
r.UpdateInformation()
assert(r.GetOutputInformation(0).Get(vtk.vtkStreamingDemandDrivenPipeline.TIME_STEPS(), 0) == 11.0)

os.remove(file0)
def vortvelvolumei(args):
    #inputfile, outputfile, sx, ex, sy, ey, sz, ez, dataset):
    p = args[0]
    cubenum = args[1]
    print("Cube", cubenum)
    #Check for additonal parameters
    if (p["param1"] != ''):
        comptype = p["param1"]
    else:
        comptype = "q" #Default to q criterion
    if (p["param2"] != ''):
        thresh = float(p["param2"])
    else:
        thresh = 783.3 #Default for q threshold on isotropic data

    inputfile = p["inputfile"] +str(cubenum) + ".npy" 
    outputfile = p["outputfile"] + str(cubenum) + ".vti" #always VTK Image Data for this.
    sx = p["sx"]
    sy = p["sy"]
    sz = p["sz"]
    ex = p["ex"]
    ey = p["ey"]
    ez = p["ez"]
        
    print ("Loading file, %s" % inputfile)
    #Determine if file is h5 or numpy
    rs = timeit.default_timer()
    vel = np.load(inputfile)
    print ("File Loaded")
    re = timeit.default_timer()
    #convert numpy array to vtk
    cs = timeit.default_timer()
    #convert numpy array to vtk
    vtkdata = numpy_support.numpy_to_vtk(vel.flat, deep=True, array_type=vtk.VTK_FLOAT)
    vtkdata.SetNumberOfComponents(3)
    vtkdata.SetName("Velocity")
    image = vtk.vtkImageData()
    image.GetPointData().SetVectors(vtkdata)
    image.SetExtent(sx,ex,sy,ey,sz,ez)
    #NOTE: Hardcoding Spacing

    image.SetSpacing(.006135923, .006135923, .006135923)
    ce = timeit.default_timer()
    vs = timeit.default_timer()
    print ("Beginning computation: " + comptype)
    if (comptype == "v"):
        vorticity = vtk.vtkCellDerivatives()
        vorticity.SetVectorModeToComputeVorticity()
        vorticity.SetTensorModeToPassTensors()
        vorticity.SetInputData(image)
        vorticity.Update()
    elif (comptype == "q"):
        vorticity = vtk.vtkGradientFilter()
        vorticity.SetInputData(image)
        vorticity.SetInputScalars(image.FIELD_ASSOCIATION_POINTS,"Velocity")
        vorticity.ComputeQCriterionOn()
        vorticity.SetComputeGradient(0)
        vorticity.Update()
    ve = timeit.default_timer()
    print("Initial calculation done")
    ms = timeit.default_timer()
    if (comptype == "v"):
        mag = vtk.vtkImageMagnitude()
        cp = vtk.vtkCellDataToPointData()
        cp.SetInputData(vorticity.GetOutput())
        cp.Update()
        image.GetPointData().SetScalars(cp.GetOutput().GetPointData().GetVectors())
        mag.SetInputData(image)
        mag.Update()
        m = mag.GetOutput()
        m.GetPointData().RemoveArray("Velocity")
    else:
        image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetVectors("Q-criterion"))
    me = timeit.default_timer()
    print("Generating screenshot")
    c = vtk.vtkContourFilter()
    c.SetValue(0,thresh)
    c.SetInputData(image)
    c.Update()
    contour = c.GetOutput()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(contour)
    mapper.ScalarVisibilityOn()
    mapper.SetScalarRange(-1,1)
    mapper.SetScalarModeToUsePointFieldData()
    mapper.ColorByArrayComponent("Velocity", 0)
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    
    ren = vtk.vtkRenderer()
    ren.AddActor(actor)
    ren.SetBackground(1,1,1)
    camera = vtk.vtkCamera()
    ren.SetActiveCamera(camera)
    ren.ResetCamera()
    camera.Zoom(1.5) #This reduces the whitespace around the image

    renWin = vtk.vtkRenderWindow()
    renWin.SetSize(1024,1024)
    renWin.AddRenderer(ren)
    renWin.SetOffScreenRendering(1)

    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renWin)
    windowToImageFilter.Update()
    
    w = vtk.vtkPNGWriter()
    pngfilename = p["outputfile"] + str(cubenum) + ".png"
    w.SetFileName(pngfilename)
    w.SetInputConnection(windowToImageFilter.GetOutputPort())
    w.Write()

    #Shift camera angle and take snapshots around the cube.
    for aznum in range(4):
        camera.Azimuth(90)
        windowToImageFilter = vtk.vtkWindowToImageFilter()
        windowToImageFilter.SetInput(renWin)
        windowToImageFilter.Update()
        pngfilename = p["outputfile"] + str(cubenum) + "-r" + str(aznum)+ ".png"
        w.SetFileName(pngfilename)
        w.SetInputConnection(windowToImageFilter.GetOutputPort())
        w.Write()

    camera.Elevation(90) #Rotate camera to top
    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renWin)
    windowToImageFilter.Update()
    pngfilename = p["outputfile"] + str(cubenum) + "-t1.png"
    w.SetFileName(pngfilename)
    w.SetInputConnection(windowToImageFilter.GetOutputPort())
    w.Write()

    camera.Elevation(180) #Rotate camera to bottom
    windowToImageFilter = vtk.vtkWindowToImageFilter()
    windowToImageFilter.SetInput(renWin)
    windowToImageFilter.Update()
    pngfilename = p["outputfile"] + str(cubenum) + "-b1.png"
    w.SetFileName(pngfilename)
    w.SetInputConnection(windowToImageFilter.GetOutputPort())
    w.Write()

    print ("Thresholding.")
    ts = timeit.default_timer()
    t = vtk.vtkImageThreshold() #Dense represenation (0's included, structured grid)
    #t = vtk.vtkThreshold() #sparse representation

    if (comptype == "q"):
        t.SetInputData(image)
        t.ThresholdByUpper(thresh) #.25*67.17^2 = 1127
        #t.SetInputArrayToProcess(0,0,0, vorticity.GetOutput().FIELD_ASSOCIATION_POINTS, "Q-criterion")
        print("q criterion")
    else:
        t.SetInputData(m)
        t.SetInputArrayToProcess(0,0,0, mag.GetOutput().FIELD_ASSOCIATION_POINTS, "Magnitude")
        t.ThresholdByUpper(thresh) #44.79)
    #Set values in range to 1 and values out of range to 0
    t.SetInValue(1)
    t.SetOutValue(0)
    #t.ReplaceInOn()
    #t.ReplaceOutOn()
    print("Update thresh")
    t.Update()
    #wt = vtk.vtkXMLImageDataWriter()
    #wt.SetInputData(t.GetOutput())
    #wt.SetFileName("thresh.vti")
    #wt.Write()

    d = vtk.vtkImageDilateErode3D()
    d.SetInputData(t.GetOutput())
    d.SetKernelSize(4,4,4)
    d.SetDilateValue(1)
    d.SetErodeValue(0)
    print ("Update dilate")
    d.Update()

    iis = vtk.vtkImageToImageStencil()
    iis.SetInputData(d.GetOutput())
    iis.ThresholdByUpper(1)
    stencil = vtk.vtkImageStencil()
    stencil.SetInputConnection(2, iis.GetOutputPort())
    stencil.SetBackgroundValue(0)
    #image.GetPointData().RemoveArray("Vorticity")
    #Set scalars to velocity so it can be cut by the stencil
    image.GetPointData().SetScalars(image.GetPointData().GetVectors())
    #if (comptype == "q"):  #Use this to get just q-criterion data instead of velocity data.  Do we need both?
    #    image.GetPointData().SetScalars(vorticity.GetOutput().GetPointData().GetScalars("Q-criterion"))
    stencil.SetInputData(image)
    print ("Update stencil")    
    stencil.Update()
    te = timeit.default_timer()
    print("Setting up write")
    ws = timeit.default_timer()
    #Make velocity a vector again
    velarray = stencil.GetOutput().GetPointData().GetScalars()
    image.GetPointData().RemoveArray("Velocity")
    image.GetPointData().SetVectors(velarray)
    w = vtk.vtkXMLImageDataWriter()
    w.SetCompressorTypeToZLib()
    #w.SetCompressorTypeToNone() Need to figure out why this fails.
    w.SetEncodeAppendedData(0) #turn of base 64 encoding for fast write
    w.SetFileName(outputfile)
    w.SetInputData(image)
    if (0):
        w.SetCompressorTypeToZfp()
        w.GetCompressor().SetNx(ex-sx+1)
        w.GetCompressor().SetNy(ey-sy+1)
        w.GetCompressor().SetNz(ez-sz+1)
        w.GetCompressor().SetTolerance(1e-2)
        w.GetCompressor().SetNumComponents(3)

    #result = w.Write()
    result = 1 #don't write for benchmarking
    we = timeit.default_timer()

    print("Results:")
    print("Read time: %s" % str(re-rs))
    print ("Convert to vtk: %s" % str(ce-cs))
    if (comptype == "q"):
        print ("Q Computation: %s" % str(ve-vs))
        print ("Q Magnitude: %s" % str(me-ms))
    else:
        print ("Vorticity Computation: %s" % str(ve-vs))
        print ("Vorticity Magnitude: %s" % str(me-ms))
    print ("Threshold: %s" % str(te-ts))
    print ("Write %s" % str(we-ws))
    print ("Total time: %s" % str(we-rs))
    if (result):
        p["message"] = "Success"
        p["computetime"] = str(we-rs)
    return p #return the packet
Exemple #58
0
def writevti(image, path):
    """Write VTI-files, i.e. images in VTK XML format."""
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetInput(image)
    writer.SetFileName(path)
    writer.Write()