def avgProjectionsVtk(self, filenames , extent):
     '''Returns the average of the input images
     
     Input is passed as filenames pointing to 2D TIFF
     Output is a vtkImageData
     gives the same result as avgProjections within machine precision.
     '''
     num = len(filenames)
     readers = [vtk.vtkTIFFReader() for i in range(num)]
     scalers = [vtk.vtkImageShiftScale() for i in range(num)]
     vois = [vtk.vtkExtractVOI() for i in range(num)]
     avger = vtk.vtkImageWeightedSum()
     counter = 0
     for reader, voi, scaler, filename in zip(readers, vois , scalers ,filenames):
         reader.SetFileName(filename)
         reader.Update()
         print ("reading {0}".format(filename))
         voi.SetInputData(reader.GetOutput())
         voi.SetVOI(extent)
         voi.Update()
         print ("extracting VOI")
         scaler.SetInputData(voi.GetOutput())
         scaler.SetOutputScalarTypeToDouble()
         scaler.SetScale(1)
         scaler.SetShift(0)
         scaler.Update()
         avger.AddInputData(scaler.GetOutput())
         avger.SetWeight(counter , 1/float(num))
         counter = counter + 1
         print ("adding input connection {0}".format(counter))
         
     
     avger.Update()
     return avger.GetOutput()
示例#2
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkTIFFReader(), 'Reading vtkTIFF.',
         (), ('vtkTIFF',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
示例#3
0
def loadImageData(filename, spacing=()):
    """Read and return a ``vtkImageData`` object from file.
    Use ``load`` instead.
    E.g. `img = load('myfile.tif').imagedata()`
    """
    if ".tif" in filename.lower():
        reader = vtk.vtkTIFFReader()
    elif ".slc" in filename.lower():
        reader = vtk.vtkSLCReader()
        if not reader.CanReadFile(filename):
            colors.printc("~prohibited Sorry bad slc file " + filename, c=1)
            return None
    elif ".vti" in filename.lower():
        reader = vtk.vtkXMLImageDataReader()
    elif ".mhd" in filename.lower():
        reader = vtk.vtkMetaImageReader()
    elif ".dem" in filename.lower():
        reader = vtk.vtkDEMReader()
    elif ".nii" in filename.lower():
        reader = vtk.vtkNIFTIImageReader()
    elif ".nrrd" in filename.lower():
        reader = vtk.vtkNrrdReader()
        if not reader.CanReadFile(filename):
            colors.printc("~prohibited Sorry bad nrrd file " + filename, c=1)
            return None
    reader.SetFileName(filename)
    reader.Update()
    image = reader.GetOutput()
    if len(spacing) == 3:
        image.SetSpacing(spacing[0], spacing[1], spacing[2])
    return image
示例#4
0
 def getExtent(self):
     # this method reads the first image and returns a tuple having info about the extents of the image
     reader2 = vtk.vtkTIFFReader()
     reader2.SetFileName(
         str(self.dirPath + self.filePrefix + self.ui_l.lineEdit_3.text() +
             ".tif"))
     reader2.Update()
     return reader2.GetDataExtent()
示例#5
0
    def __init__(self, obj=None):
        vtk.vtkImageActor.__init__(self)
        Base3DProp.__init__(self)

        if utils.isSequence(obj) and len(obj):
            iac = vtk.vtkImageAppendComponents()
            nchan = obj.shape[
                2]  # get number of channels in inputimage (L/LA/RGB/RGBA)
            for i in range(nchan):
                #arr = np.flip(np.flip(array[:,:,i], 0), 0).ravel()
                arr = np.flip(obj[:, :, i], 0).ravel()
                varb = numpy_to_vtk(arr,
                                    deep=True,
                                    array_type=vtk.VTK_UNSIGNED_CHAR)
                imgb = vtk.vtkImageData()
                imgb.SetDimensions(obj.shape[1], obj.shape[0], 1)
                imgb.GetPointData().SetScalars(varb)
                iac.AddInputData(0, imgb)
            iac.Update()
            img = iac.GetOutput()
            self.SetInputData(img)

        elif isinstance(obj, vtk.vtkImageData):
            self.SetInputData(obj)
            img = obj

        elif isinstance(obj, str):
            if "https://" in obj:
                import vedo.io as io
                obj = io.download(obj, verbose=False)

            if ".png" in obj:
                picr = vtk.vtkPNGReader()
            elif ".jpg" in obj or ".jpeg" in obj:
                picr = vtk.vtkJPEGReader()
            elif ".bmp" in obj:
                picr = vtk.vtkBMPReader()
            elif ".tif" in obj:
                picr = vtk.vtkTIFFReader()
            else:
                colors.printc("Cannot understand picture format", obj, c='r')
                return
            picr.SetFileName(obj)
            self.filename = obj
            picr.Update()
            img = picr.GetOutput()
            self.SetInputData(img)

        else:
            img = vtk.vtkImageData()
            self.SetInputData(img)

        self._data = img

        sx, sy, _ = img.GetDimensions()
        self.shape = np.array([sx, sy])

        self._mapper = self.GetMapper()
示例#6
0
def dicom_viewer(directory, slice_queue, mouse_move_event):
    filenames = vtk.vtkStringArray()
    for i, filename in enumerate(os.listdir(directory)):
        filenames.InsertNextValue(os.path.join(directory, filename))

    reader = vtk.vtkTIFFReader()
    reader.SetFileNames(filenames)
    reader.Update()

    image_viewer = vtk.vtkResliceImageViewer()
    image_viewer.SetInputData(reader.GetOutput())
    # image_viewer.SetInputConnection(reader.GetOutputPort())
    interactor = vtk.vtkRenderWindowInteractor()
    image_viewer.SetupInteractor(interactor)
    image_viewer.Render()
    image_viewer.GetRenderer().ResetCamera()
    image_viewer.Render()

    # Store the initial image size
    init_image_size = None
    init_image_size = interactor.GetSize()

    # def on_mouse_move(obj, event):
    #     mouse_queue.put(obj.GetEventPosition())
    #     mouse_move_event.set()
    #     return

    def on_scroll_wheel_move(obj, event):
        slice_queue.put(image_viewer.GetSlice())
        return

    # Listener for left mouse button press:
    #   Gets mouse position in current window pixels and converts
    #   them to pixel position based on initial image size,
    #   with the origin at the bottom left corner
    def on_left_mouse_button_press(obj, event):
        if (init_image_size != None):
            mouse_position = obj.GetEventPosition()
            current_image_size = obj.GetSize()
            posX = int(
                round(mouse_position[0] * init_image_size[0] /
                      current_image_size[0]))
            posY = int(
                round(mouse_position[1] * init_image_size[1] /
                      current_image_size[1]))
            print(posX, posY)
        return

    # Add left mouse button press observer
    interactor.AddObserver("LeftButtonPressEvent", on_left_mouse_button_press,
                           101.0)

    # interactor.AddObserver("MouseMoveEvent", on_mouse_move)
    interactor.AddObserver("MouseWheelForwardEvent", on_scroll_wheel_move,
                           100.0)
    interactor.AddObserver("MouseWheelBackwardEvent", on_scroll_wheel_move,
                           100.0)
    interactor.Start()
示例#7
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkTIFFReader(),
                                       'Reading vtkTIFF.', (),
                                       ('vtkTIFF', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
示例#8
0
文件: picture.py 项目: marcomusy/vedo
    def __init__(self, obj=None, channels=(), flip=False):
        vtk.vtkImageActor.__init__(self)
        vedo.base.Base3DProp.__init__(self)


        if utils.isSequence(obj) and len(obj): # passing array
            img = _get_img(obj, flip)

        elif isinstance(obj, vtk.vtkImageData):
            img = obj

        elif isinstance(obj, str):
            if "https://" in obj:
                obj = vedo.io.download(obj, verbose=False)

            fname = obj.lower()
            if fname.endswith(".png"):
                picr = vtk.vtkPNGReader()
            elif fname.endswith(".jpg") or fname.endswith(".jpeg"):
                picr = vtk.vtkJPEGReader()
            elif fname.endswith(".bmp"):
                picr = vtk.vtkBMPReader()
            elif fname.endswith(".tif") or fname.endswith(".tiff"):
                picr = vtk.vtkTIFFReader()
                picr.SetOrientationType(vedo.settings.tiffOrientationType)
            else:
                colors.printc("Cannot understand picture format", obj, c='r')
                return
            picr.SetFileName(obj)
            self.filename = obj
            picr.Update()
            img = picr.GetOutput()

        else:
            img = vtk.vtkImageData()

        # select channels
        nchans = len(channels)
        if nchans and img.GetPointData().GetScalars().GetNumberOfComponents() > nchans:
            pec = vtk.vtkImageExtractComponents()
            pec.SetInputData(img)
            if nchans == 3:
                pec.SetComponents(channels[0], channels[1], channels[2])
            elif nchans == 2:
                pec.SetComponents(channels[0], channels[1])
            elif nchans == 1:
                pec.SetComponents(channels[0])
            pec.Update()
            img = pec.GetOutput()

        self._data = img
        self.SetInputData(img)

        sx,sy,_ = img.GetDimensions()
        self.shape = np.array([sx,sy])

        self._mapper = self.GetMapper()
示例#9
0
    def test_get_tif(self):
        '''tif file returns correct reader'''
        extension='.tif'
        expected = type(vtk.vtkTIFFReader())
        writer = vtk.vtkTIFFWriter()

        filename = os.path.join(self.test_dir, 'file'+extension)
        self.generate_image(filename, writer)
        self.assertEqual(type(get_vtk_reader(filename)), expected)
示例#10
0
def read_tiff(directory):
    # Accumulate file names
    filenames = vtk.vtkStringArray()
    for i, filename in enumerate(os.listdir(directory)):
        filenames.InsertNextValue(os.path.join(directory, filename))
    # Create reader object with filenames
    reader = vtk.vtkTIFFReader()
    reader.SetFileNames(filenames)
    reader.Update()
    return reader
示例#11
0
 def FileExtensionsDescriptor(cls):
     """
     Grab the acceptable variations on the file extension and return 
     in the format required by the wx system for file dialogs.
     """
     descriptor = 'TIFF Images'
     extensions = vtk.vtkTIFFReader().GetFileExtensions().split(' ')
     extensions.extend([item.upper() for item in extensions])
     extensions = ['*'+item for item in extensions]
     
     return '|'.join([descriptor, ';'.join(extensions)])
示例#12
0
def VtkRead(filepath, t):
    if not const.VTK_WARNING:
        log_path = os.path.join(const.USER_LOG_DIR, 'vtkoutput.txt')
        fow = vtk.vtkFileOutputWindow()
        fow.SetFileName(log_path.encode(const.FS_ENCODE))
        ow = vtk.vtkOutputWindow()
        ow.SetInstance(fow)

    global no_error

    if t == "bmp":
        reader = vtk.vtkBMPReader()

    elif t == "tiff" or t == "tif":
        reader = vtk.vtkTIFFReader()

    elif t == "png":
        reader = vtk.vtkPNGReader()

    elif t == "jpeg" or t == "jpg":
        reader = vtk.vtkJPEGReader()

    else:
        return False

    print ">>>> bmp reader", type(filepath)

    reader.AddObserver("ErrorEvent", VtkErrorToPy)
    reader.SetFileName(filepath.encode(const.FS_ENCODE))
    reader.Update()

    if no_error:
        image = reader.GetOutput()
        dim = image.GetDimensions()

        if reader.GetNumberOfScalarComponents() > 1:
            luminanceFilter = vtk.vtkImageLuminance()
            luminanceFilter.SetInputData(image)
            luminanceFilter.Update()

            image = vtk.vtkImageData()
            image.DeepCopy(luminanceFilter.GetOutput())

        img_array = numpy_support.vtk_to_numpy(
            image.GetPointData().GetScalars())
        img_array.shape = (dim[1], dim[0])

        return img_array
    else:
        no_error = True
        return False
示例#13
0
def VtkRead(filepath, t):
    if not const.VTK_WARNING:
        log_path = os.path.join(inv_paths.USER_LOG_DIR, 'vtkoutput.txt')
        fow = vtk.vtkFileOutputWindow()
        fow.SetFileName(log_path.encode(const.FS_ENCODE))
        ow = vtk.vtkOutputWindow()
        ow.SetInstance(fow)

    global no_error

    if t == "bmp":
        reader = vtk.vtkBMPReader()

    elif t == "tiff" or t == "tif":
        reader = vtk.vtkTIFFReader()

    elif t == "png":
        reader = vtk.vtkPNGReader()
    
    elif t == "jpeg" or t == "jpg":
        reader = vtk.vtkJPEGReader()

    else:
        return False

    reader.AddObserver("ErrorEvent", VtkErrorToPy)
    reader.SetFileName(filepath)
    reader.Update()
    
    if no_error:
        image = reader.GetOutput()
        dim = image.GetDimensions()
       
        if reader.GetNumberOfScalarComponents() > 1:
            luminanceFilter = vtk.vtkImageLuminance()
            luminanceFilter.SetInputData(image)
            luminanceFilter.Update()

            image = vtk.vtkImageData()
            image.DeepCopy(luminanceFilter.GetOutput())

        img_array = numpy_support.vtk_to_numpy(image.GetPointData().GetScalars())
        img_array.shape = (dim[1], dim[0])

        return img_array
    else:
        no_error = True
        return False
示例#14
0
def do_conversion(file_attributes, working_directory):

    reader = vtk.vtkTIFFReader()
    reader.SetFileName(file_attributes["FileName"])
    reader.Update()

    image_data = reader.GetOutput()
    image_data.SetExtent(file_attributes["Extents"])
    image_data.SetSpacing(file_attributes["PhysicalSize"])

    out_path = working_directory + "/" + os.path.splitext(
        os.path.basename(file_attributes["FileName"]))[0] + ".vti"
    writer = vtk.vtkXMLImageDataWriter()
    writer.SetInputData(image_data)
    writer.SetFileName(out_path)
    writer.Write()
示例#15
0
    def __init__(self, obj=None):
        vtk.vtkImageActor.__init__(self)
        ActorBase.__init__(self)

        if utils.isSequence(obj) and len(obj):
            iac = vtk.vtkImageAppendComponents()
            for i in range(3):
                #arr = np.flip(np.flip(array[:,:,i], 0), 0).ravel()
                arr = np.flip(obj[:, :, i], 0).ravel()
                varb = numpy_to_vtk(arr,
                                    deep=True,
                                    array_type=vtk.VTK_UNSIGNED_CHAR)
                imgb = vtk.vtkImageData()
                imgb.SetDimensions(obj.shape[1], obj.shape[0], 1)
                imgb.GetPointData().SetScalars(varb)
                iac.AddInputData(0, imgb)
            iac.Update()
            img = iac.GetOutput()
            self.SetInputData(img)

        elif isinstance(obj, vtk.vtkImageData):
            self.SetInputData(obj)
            img = obj

        elif isinstance(obj, str):
            if ".png" in obj:
                picr = vtk.vtkPNGReader()
            elif ".jpg" in obj or ".jpeg" in obj:
                picr = vtk.vtkJPEGReader()
            elif ".bmp" in obj:
                picr = vtk.vtkBMPReader()
            elif ".tif" in obj:
                picr = vtk.vtkTIFFReader()
            else:
                colors.printc("Cannot understand picture format", obj, c=1)

            picr.SetFileName(obj)
            picr.Update()
            img = picr.GetOutput()
            self.SetInputData(img)

        else:
            img = vtk.vtkImageData()
            self.SetInputData(img)

        self._imagedata = img
        self._mapper = self.GetMapper()
示例#16
0
 def ReadTIFFImageFile(self):
     if (self.InputFileName == '') & (self.InputFilePrefix == ''):
         self.PrintError('Error: no InputFileName or InputFilePrefix.')
     self.PrintLog('Reading TIFF image file.')
     reader = vtk.vtkTIFFReader()
     if self.InputFileName != '':
         reader.SetFileName(self.InputFileName)
     else:
         reader.SetFilePrefix(self.InputFilePrefix)
         if self.InputFilePattern != '':
             reader.SetFilePattern(self.InputFilePattern)
         else:
             reader.SetFilePattern("%s%04d.png")
         reader.SetDataExtent(self.DataExtent)
         reader.SetDataSpacing(self.DataSpacing)
         reader.SetDataOrigin(self.DataOrigin)
     reader.Update()
     self.Image = reader.GetOutput()
示例#17
0
 def ReadTIFFImageFile(self):
     if (self.InputFileName == '') & (self.InputFilePrefix == ''):
         self.PrintError('Error: no InputFileName or InputFilePrefix.')
     self.PrintLog('Reading TIFF image file.')
     reader = vtk.vtkTIFFReader()
     if self.InputFileName != '':
         reader.SetFileName(self.InputFileName)
     else:
         reader.SetFilePrefix(self.InputFilePrefix)
         if self.InputFilePattern != '':
             reader.SetFilePattern(self.InputFilePattern)
         else:
             reader.SetFilePattern("%s%04d.png")
         reader.SetDataExtent(self.DataExtent)
         reader.SetDataSpacing(self.DataSpacing)
         reader.SetDataOrigin(self.DataOrigin)
     reader.Update()
     self.Image = reader.GetOutput()
示例#18
0
def loadImageData(filename, spacing=[]):

    if not os.path.isfile(filename):
        vc.printc('File not found:', filename, c=1)
        return None

    if '.tif' in filename.lower():
        reader = vtk.vtkTIFFReader()
    elif '.slc' in filename.lower():
        reader = vtk.vtkSLCReader()
        if not reader.CanReadFile(filename):
            vc.printc('Sorry bad SLC/TIFF file ' + filename, c=1)
            exit(1)
    reader.SetFileName(filename)
    reader.Update()
    image = reader.GetOutput()
    if len(spacing) == 3:
        image.SetSpacing(spacing[0], spacing[1], spacing[2])
    vc.printc('voxel spacing is', image.GetSpacing(), c='b', bold=0)
    return image
示例#19
0
    def test_write_tiff_unsigned_long(self):
        '''Can write tiff file with type unsigned long'''
        extension = '.tiff'
        filename = os.path.join(self.test_dir, 'file' + extension)
        scalar_type = vtk.VTK_UNSIGNED_LONG

        source = self.generate_image(scalar_type)
        writer = vtk.vtkTIFFWriter()
        writer.SetInputConnection(source.GetOutputPort())
        writer.SetFileName(filename)

        handle_filetype_writing_special_cases(writer)

        writer.Update()
        self.assertTrue(os.path.isfile(filename))

        reader = vtk.vtkTIFFReader()
        reader.SetFileName(filename)
        reader.Update()

        self.assertEqual(reader.GetOutput().GetScalarType(), vtk.VTK_FLOAT)
示例#20
0
def loadImageData(filename, spacing=[]):

    if not os.path.isfile(filename):
        colors.printc('File not found:', filename, c=1)
        return None

    if '.tif' in filename.lower():
        reader = vtk.vtkTIFFReader()
    elif '.slc' in filename.lower():
        reader = vtk.vtkSLCReader()
        if not reader.CanReadFile(filename):
            colors.printc('Sorry bad slc file ' + filename, c=1)
            exit(1)
    elif '.vti' in filename.lower():
        reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(filename)
    reader.Update()
    image = reader.GetOutput()
    if len(spacing) == 3:
        image.SetSpacing(spacing[0], spacing[1], spacing[2])
    return image
示例#21
0
    def readTiff(self):
        if self._directory is None:
            raise NameError("Please set image directory")

        # Accumulate file names
        filenames = vtkStringArray()
        dir_list = os.listdir(self._directory)
        dir_list.sort()
        for filename in dir_list:
            filenames.InsertNextValue(os.path.join(self._directory, filename))

        with open(os.path.join(self._directory, "meta_data.json")) as meta_data_file:
            self._metaData = json.load(meta_data_file)

        # Create reader object with filenames
        reader = vtkTIFFReader()
        reader.SetFileNames(filenames)
        reader.SetDataSpacing(self._metaData["pixelSpacing"])
        reader.Update()
        self._reader = reader
        return self._reader
示例#22
0
    def LoadVolume(self):
        """ loads the volume - this only happens once during the lifetime of the application """

        if len(sys.argv) < 2:
            print " Error - please provide a file name (.vtk)"
            exit

        fileName = sys.argv[1]

        extension = fileName.split('.')[-1]
        if extension == "vtk":
            reader = vtk.vtkStructuredPointsReader()
            reader.SetFileName( fileName )
            reader.Update()
        elif extension == "tif":
            reader = vtk.vtkTIFFReader()
            reader.SetFileName( fileName )
            reader.Update()
        else:
            print " Unknown file type ", extension

        return reader.GetOutput()
示例#23
0
文件: Renderer.py 项目: Praz-3/AnuViz
 def readImgStack(self, loadedDataInfo):
     #def readVolume(self):
     # This function fetches the info of the image stack from PLoadStack object and reads it using the TiffReader
     self.reader = vtk.vtkTIFFReader()
     self.reader.SetFilePrefix(
         str(loadedDataInfo.dirPath + loadedDataInfo.filePrefix))
     self.reader.SetFilePattern("%s%0" + str(loadedDataInfo.getDigits()) +
                                "d.tif")
     self.reader.SetFileNameSliceOffset(loadedDataInfo.offset)
     ex = loadedDataInfo.getExtent()
     self.reader.SetDataExtent(0, ex[1], 0, ex[3], 0,
                               loadedDataInfo.imageNo - 1)
     self.reader.SetDataSpacing(loadedDataInfo.xSpace,
                                loadedDataInfo.ySpace,
                                loadedDataInfo.zSpace)
     self.reader.Update()
     # cMin,cMax default value for color resolution used in histogram and alpha function plot
     self.cMin = 0
     if self.reader.GetOutput().GetScalarRange()[1] > 255:
         self.cMax = 65535
     else:
         self.cMax = 255
     """self.reader.SetFilePrefix("/home/pssarkar/Pranav/Small Data/reconstructed/img_Image")		# for default sample images # testing
示例#24
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        self._reader = vtk.vtkTIFFReader()
        self._reader.SetFileDimensionality(3)

        module_utils.setup_vtk_object_progress(self, self._reader,
                                           'Reading TIFF images.')

        self._config.file_pattern = '%03d.tif'
        self._config.first_slice = 0
        self._config.last_slice = 1
        self._config.spacing = (1,1,1)
        self._config.file_lower_left = False

        configList = [
            ('File pattern:', 'file_pattern', 'base:str', 'filebrowser',
             'Filenames will be built with this.  See module help.',
             {'fileMode' : WX_OPEN,
              'fileMask' :
              'TIFF files (*.tif or *.tiff)|*.tif;*.tiff|All files (*.*)|*.*'}),
            ('First slice:', 'first_slice', 'base:int', 'text',
             '%d will iterate starting at this number.'),
            ('Last slice:', 'last_slice', 'base:int', 'text',
             '%d will iterate and stop at this number.'),
            ('Spacing:', 'spacing', 'tuple:float,3', 'text',
             'The 3-D spacing of the resultant dataset.'),
            ('Lower left:', 'file_lower_left', 'base:bool', 'checkbox',
             'Image origin at lower left? (vs. upper left)')]

        ScriptedConfigModuleMixin.__init__(
            self, configList,
            {'Module (self)' : self,
             'vtkTIFFReader' : self._reader})

        self.sync_module_logic_with_config()
示例#25
0
文件: gfx.py 项目: ggoret/VEDA
	def set_open_img_on_off(self):
		if not self.isstarton:
			self.axes.VisibilityOff()
			self.camera.SetFocalPoint(145, 61, 0)
			self.camera.SetPosition(145, 61, 529)
			reader = vtk.vtkTIFFReader()
			reader.SetFileName(self.vedadir + 'doc/veda.tif')
			reader.SetOrientationType(4)
			self.ia = vtk.vtkImageActor()
			self.ia.SetInput(reader.GetOutput())
			self.renderer.AddActor(self.ia)
			self.renwin.Render()
			self.isstarton = 1
		else :
			self.axes.VisibilityOn()
			self.camera.SetFocalPoint(0, 0, 0)
			self.camera.SetPosition(0, 0, 400)
			self.camera.SetViewUp(0, 0, 0)
			self.camera.Elevation(0)
			self.camera.Roll(0)
			self.camera.Azimuth(0)
			self.renderer.RemoveActor(self.ia)
			self.renwin.Render()
			self.isstarton=0
示例#26
0
 def set_open_img_on_off(self):
     if not self.isstarton:
         self.axes.VisibilityOff()
         self.camera.SetFocalPoint(145, 61, 0)
         self.camera.SetPosition(145, 61, 529)
         reader = vtk.vtkTIFFReader()
         reader.SetFileName(self.vedadir + 'doc/veda.tif')
         reader.SetOrientationType(4)
         self.ia = vtk.vtkImageActor()
         self.ia.SetInput(reader.GetOutput())
         self.renderer.AddActor(self.ia)
         self.renwin.Render()
         self.isstarton = 1
     else:
         self.axes.VisibilityOn()
         self.camera.SetFocalPoint(0, 0, 0)
         self.camera.SetPosition(0, 0, 400)
         self.camera.SetViewUp(0, 0, 0)
         self.camera.Elevation(0)
         self.camera.Roll(0)
         self.camera.Azimuth(0)
         self.renderer.RemoveActor(self.ia)
         self.renwin.Render()
         self.isstarton = 0
示例#27
0
    def _makeSTL(self):
        local_dir = self._gray_dir
        surface_dir = self._vol_dir+'_surfaces'+self._path_dlm
        try:
            os.mkdir(surface_dir)
        except:
            pass
        files = fnmatch.filter(sorted(os.listdir(local_dir)),'*.tif')
        counter = re.search("[0-9]*\.tif", files[0]).group()
        prefix = self._path_dlm+string.replace(files[0],counter,'')
        counter = str(len(counter)-4)
        prefixImageName = local_dir + prefix

        ### Create the renderer, the render window, and the interactor. The renderer
        # The following reader is used to read a series of 2D slices (images)
        # that compose the volume. The slice dimensions are set, and the
        # pixel spacing. The data Endianness must also be specified. The reader
        v16=vtk.vtkTIFFReader()

        v16.SetFilePrefix(prefixImageName)
        v16.SetDataExtent(0,100,0,100,1,len(files))
        v16.SetFilePattern("%s%0"+counter+"d.tif")
        v16.Update()

        im = v16.GetOutput()
        im.SetSpacing(self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2])

        v = vte.vtkImageExportToArray()
        v.SetInputData(im)

        n = np.float32(v.GetArray())
        idx = np.argwhere(n)
        (ystart,xstart,zstart), (ystop,xstop,zstop) = idx.min(0),idx.max(0)+1
        I,J,K = n.shape
        if ystart > 5:
            ystart -= 5
        else:
            ystart = 0
        if ystop < I-5:
            ystop += 5
        else:
            ystop = I
        if xstart > 5:
            xstart -= 5
        else:
            xstart = 0
        if xstop < J-5:
            xstop += 5
        else:
            xstop = J
        if zstart > 5:
            zstart -= 5
        else:
            zstart = 0
        if zstop < K-5:
            zstop += 5
        else:
            zstop = K

        a = n[ystart:ystop,xstart:xstop,zstart:zstop]
        itk_img = sitk.GetImageFromArray(a)
        itk_img.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        
        print "\n"
        print "-------------------------------------------------------"
        print "-- Applying Patch Based Denoising - this can be slow --"
        print "-------------------------------------------------------"
        print "\n"
        pb = sitk.PatchBasedDenoisingImageFilter()
        pb.KernelBandwidthEstimationOn()
        pb.SetNoiseModel(3) #use a Poisson noise model since this is confocal
        pb.SetNoiseModelFidelityWeight(1)
        pb.SetNumberOfSamplePatches(20)
        pb.SetPatchRadius(4)
        pb.SetNumberOfIterations(10)

        fimg = pb.Execute(itk_img)
        b = sitk.GetArrayFromImage(fimg)
        intensity = b.max()

        #grad = sitk.GradientMagnitudeRecursiveGaussianImageFilter()
        #grad.SetSigma(0.05)
        gf = sitk.GradientMagnitudeImageFilter()
        gf.UseImageSpacingOn()
        grad = gf.Execute(fimg)
        edge = sitk.Cast(sitk.BoundedReciprocal( grad ),sitk.sitkFloat32)


        print "\n"
        print "-------------------------------------------------------"
        print "---- Thresholding to deterimine initial level sets ----"
        print "-------------------------------------------------------"
        print "\n"
        t = 0.5
        seed = sitk.BinaryThreshold(fimg,t*intensity)
        #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius)
        seed = sitk.BinaryMorphologicalOpening(seed,2)
        seed = sitk.BinaryFillhole(seed!=0)
        #Get connected regions
        r = sitk.ConnectedComponent(seed)
        labels = sitk.GetArrayFromImage(r)
        ids = sorted(np.unique(labels))
        N = len(ids)
        if N > 2:
            i = np.copy(N)
            while i == N and (t-self._tratio)>-1e-7:
                t -= 0.01
                seed = sitk.BinaryThreshold(fimg,t*intensity)
                #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius)
                seed = sitk.BinaryMorphologicalOpening(seed,2)
                seed = sitk.BinaryFillhole(seed!=0)
                #Get connected regions
                r = sitk.ConnectedComponent(seed)
                labels = sitk.GetArrayFromImage(r)
                i = len(np.unique(labels))
                if i > N:
                    N = np.copy(i)
            t+=0.01
        else:
            t = np.copy(self._tratio)
        seed = sitk.BinaryThreshold(fimg,t*intensity)
        #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius)
        seed = sitk.BinaryMorphologicalOpening(seed,2)
        seed = sitk.BinaryFillhole(seed!=0)
        #Get connected regions
        r = sitk.ConnectedComponent(seed)
        labels = sitk.GetArrayFromImage(r)
        labels = np.unique(labels)[1:]

        '''
        labels[labels==0] = -1
        labels = sitk.GetImageFromArray(labels)
        labels.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        #myshow3d(labels,zslices=range(20))
        #plt.show()
        ls = sitk.ScalarChanAndVeseDenseLevelSetImageFilter()
        ls.UseImageSpacingOn()
        ls.SetLambda2(1.5)
        #ls.SetCurvatureWeight(1.0)
        ls.SetAreaWeight(1.0)
        #ls.SetReinitializationSmoothingWeight(1.0)
        ls.SetNumberOfIterations(100)
        seg = ls.Execute(sitk.Cast(labels,sitk.sitkFloat32),sitk.Cast(fimg,sitk.sitkFloat32))
        seg = sitk.Cast(seg,sitk.sitkUInt8)
        seg = sitk.BinaryMorphologicalOpening(seg,1)
        seg = sitk.BinaryFillhole(seg!=0)
        #Get connected regions
        #r = sitk.ConnectedComponent(seg)
        contours = sitk.BinaryContour(seg)
        myshow3d(sitk.LabelOverlay(sitk.Cast(fimg,sitk.sitkUInt8),contours),zslices=range(fimg.GetSize()[2]))
        plt.show()
        '''

        segmentation = sitk.Image(r.GetSize(),sitk.sitkUInt8)
        segmentation.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        for l in labels:
            d = sitk.SignedMaurerDistanceMap(r==l,insideIsPositive=False,squaredDistance=True,useImageSpacing=True)
            #d = sitk.BinaryThreshold(d,-1000,0)
            #d = sitk.Cast(d,edge.GetPixelIDValue() )*-1+0.5
            #d = sitk.Cast(d,edge.GetPixelIDValue() )
            seg = sitk.GeodesicActiveContourLevelSetImageFilter()
            seg.SetPropagationScaling(1.0)
            seg.SetAdvectionScaling(1.0)
            seg.SetCurvatureScaling(0.5)
            seg.SetMaximumRMSError(0.01)
            levelset = seg.Execute(d,edge)
            levelset = sitk.BinaryThreshold(levelset,-1000,0)
            segmentation = sitk.Add(segmentation,levelset)
            print ("RMS Change for Cell %d: "% l,seg.GetRMSChange())
            print ("Elapsed Iterations for Cell %d: "% l, seg.GetElapsedIterations())
        '''
        contours = sitk.BinaryContour(segmentation)
        myshow3d(sitk.LabelOverlay(sitk.Cast(fimg,sitk.sitkUInt8),contours),zslices=range(fimg.GetSize()[2]))
        plt.show()
        '''

        n[ystart:ystop,xstart:xstop,zstart:zstop] = sitk.GetArrayFromImage(segmentation)*100

        i = vti.vtkImageImportFromArray()
        i.SetDataSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]])
        i.SetDataExtent([0,100,0,100,1,len(files)])
        i.SetArray(n)
        i.Update()

        thres=vtk.vtkImageThreshold()
        thres.SetInputData(i.GetOutput())
        thres.ThresholdByLower(0)
        thres.ThresholdByUpper(101)

        iso=vtk.vtkImageMarchingCubes()
        iso.SetInputConnection(thres.GetOutputPort())
        iso.SetValue(0,1)

        regions = vtk.vtkConnectivityFilter()
        regions.SetInputConnection(iso.GetOutputPort())
        regions.SetExtractionModeToAllRegions()
        regions.ColorRegionsOn()
        regions.Update()

        N = regions.GetNumberOfExtractedRegions()
        for i in xrange(N):
            r = vtk.vtkConnectivityFilter()
            r.SetInputConnection(iso.GetOutputPort())
            r.SetExtractionModeToSpecifiedRegions()
            r.AddSpecifiedRegion(i)
            g = vtk.vtkExtractUnstructuredGrid()
            g.SetInputConnection(r.GetOutputPort())
            geo = vtk.vtkGeometryFilter()
            geo.SetInputConnection(g.GetOutputPort())
            geo.Update()
            t = vtk.vtkTriangleFilter()
            t.SetInputConnection(geo.GetOutputPort())
            t.Update()
            cleaner = vtk.vtkCleanPolyData()
            cleaner.SetInputConnection(t.GetOutputPort())
            s = vtk.vtkSmoothPolyDataFilter()
            s.SetInputConnection(cleaner.GetOutputPort())
            s.SetNumberOfIterations(50)
            dl = vtk.vtkDelaunay3D()
            dl.SetInputConnection(s.GetOutputPort())
            dl.Update()

            self.cells.append(dl)

        for i in xrange(N):
            g = vtk.vtkGeometryFilter()
            g.SetInputConnection(self.cells[i].GetOutputPort())
            t = vtk.vtkTriangleFilter()
            t.SetInputConnection(g.GetOutputPort())

            #get the surface points of the cells and save to points attribute
            v = t.GetOutput()
            points = []
            for j in xrange(v.GetNumberOfPoints()):
                p = [0,0,0]
                v.GetPoint(j,p)
                points.append(p)
            self.points.append(points)

            #get the volume of the cell
            vo = vtk.vtkMassProperties()
            vo.SetInputConnection(t.GetOutputPort())
            self.volumes.append(vo.GetVolume())

            stl = vtk.vtkSTLWriter()
            stl.SetInputConnection(t.GetOutputPort())
            stl.SetFileName(surface_dir+'cell%02d.stl' % (i+self._counter))
            stl.Write()

        if self._display:
            skinMapper = vtk.vtkDataSetMapper()
            skinMapper.SetInputConnection(regions.GetOutputPort())
            skinMapper.SetScalarRange(regions.GetOutput().GetPointData().GetArray("RegionId").GetRange())
            skinMapper.SetColorModeToMapScalars()
            #skinMapper.ScalarVisibilityOff()
            skinMapper.Update()

            skin = vtk.vtkActor()
            skin.SetMapper(skinMapper)
            #skin.GetProperty().SetColor(0,0,255)

            # An outline provides context around the data.
            #
            outlineData = vtk.vtkOutlineFilter()
            outlineData.SetInputConnection(v16.GetOutputPort())

            mapOutline = vtk.vtkPolyDataMapper()
            mapOutline.SetInputConnection(outlineData.GetOutputPort())

            outline = vtk.vtkActor()
            #outline.SetMapper(mapOutline)
            #outline.GetProperty().SetColor(0,0,0)

            colorbar = vtk.vtkScalarBarActor()
            colorbar.SetLookupTable(skinMapper.GetLookupTable())
            colorbar.SetTitle("Cells")
            colorbar.SetNumberOfLabels(N)


            # Create the renderer, the render window, and the interactor. The renderer
            # draws into the render window, the interactor enables mouse- and 
            # keyboard-based interaction with the data within the render window.
            #
            aRenderer = vtk.vtkRenderer()
            renWin = vtk.vtkRenderWindow()
            renWin.AddRenderer(aRenderer)
            iren = vtk.vtkRenderWindowInteractor()
            iren.SetRenderWindow(renWin)

            # It is convenient to create an initial view of the data. The FocalPoint
            # and Position form a vector direction. Later on (ResetCamera() method)
            # this vector is used to position the camera to look at the data in
            # this direction.
            aCamera = vtk.vtkCamera()
            aCamera.SetViewUp (0, 0, -1)
            aCamera.SetPosition (0, 1, 0)
            aCamera.SetFocalPoint (0, 0, 0)
            aCamera.ComputeViewPlaneNormal()

            # Actors are added to the renderer. An initial camera view is created.
            # The Dolly() method moves the camera towards the FocalPoint,
            # thereby enlarging the image.
            aRenderer.AddActor(outline)
            aRenderer.AddActor(skin)
            aRenderer.AddActor(colorbar)
            aRenderer.SetActiveCamera(aCamera)
            aRenderer.ResetCamera ()
            aCamera.Dolly(1.5)

            # Set a background color for the renderer and set the size of the
            # render window (expressed in pixels).
            aRenderer.SetBackground(0.0,0.0,0.0)
            renWin.SetSize(800, 600)

            # Note that when camera movement occurs (as it does in the Dolly()
            # method), the clipping planes often need adjusting. Clipping planes
            # consist of two planes: near and far along the view direction. The 
            # near plane clips out objects in front of the plane the far plane
            # clips out objects behind the plane. This way only what is drawn
            # between the planes is actually rendered.
            aRenderer.ResetCameraClippingRange()

            im=vtk.vtkWindowToImageFilter()
            im.SetInput(renWin)

            iren.Initialize();
            iren.Start();

        #remove gray directory
        shutil.rmtree(local_dir)
示例#28
0
 def FileExtensions(cls):
     extensions = vtk.vtkTIFFReader().GetFileExtensions().split(' ')
     extensions.extend([item.upper() for item in extensions])
     return extensions
示例#29
0
    def testAllBlends(self):

        # This script calculates the luminance of an image

        renWin = vtk.vtkRenderWindow()
        renWin.SetSize(512, 256)

        # Image pipeline

        image1 = vtk.vtkTIFFReader()
        image1.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")

        # "beach.tif" image contains ORIENTATION tag which is
        # ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
        # reader parses this tag and sets the internal TIFF image
        # orientation accordingly.  To overwrite this orientation with a vtk
        # convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
        # SetOrientationType method with parameter value of 4.
        image1.SetOrientationType(4)

        image2 = vtk.vtkBMPReader()
        image2.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")

        # shrink the images to a reasonable size

        color = vtk.vtkImageShrink3D()
        color.SetInputConnection(image1.GetOutputPort())
        color.SetShrinkFactors(2, 2, 1)

        backgroundColor = vtk.vtkImageShrink3D()
        backgroundColor.SetInputConnection(image2.GetOutputPort())
        backgroundColor.SetShrinkFactors(2, 2, 1)

        # create a greyscale version

        luminance = vtk.vtkImageLuminance()
        luminance.SetInputConnection(color.GetOutputPort())

        backgroundLuminance = vtk.vtkImageLuminance()
        backgroundLuminance.SetInputConnection(backgroundColor.GetOutputPort())

        # create an alpha mask

        table = vtk.vtkLookupTable()
        table.SetTableRange(220, 255)
        table.SetValueRange(1, 0)
        table.SetSaturationRange(0, 0)
        table.Build()

        alpha = vtk.vtkImageMapToColors()
        alpha.SetInputConnection(luminance.GetOutputPort())
        alpha.SetLookupTable(table)
        alpha.SetOutputFormatToLuminance()

        # make luminanceAlpha and colorAlpha versions

        luminanceAlpha = vtk.vtkImageAppendComponents()
        luminanceAlpha.AddInputConnection(luminance.GetOutputPort())
        luminanceAlpha.AddInputConnection(alpha.GetOutputPort())

        colorAlpha = vtk.vtkImageAppendComponents()
        colorAlpha.AddInputConnection(color.GetOutputPort())
        colorAlpha.AddInputConnection(alpha.GetOutputPort())

        foregrounds = ["luminance", "luminanceAlpha", "color", "colorAlpha"]
        backgrounds = ["backgroundColor", "backgroundLuminance"]

        deltaX = 1.0 / 4.0
        deltaY = 1.0 / 2.0

        blend = dict()
        mapper = dict()
        actor = dict()
        imager = dict()

        for row, bg in enumerate(backgrounds):
            for column, fg in enumerate(foregrounds):
                blend.update({bg:{fg:vtk.vtkImageBlend()}})
                blend[bg][fg].AddInputConnection(eval(bg + '.GetOutputPort()'))
                if bg == "backgroundColor" or fg == "luminance" or fg == "luminanceAlpha":
                    blend[bg][fg].AddInputConnection(eval(fg + '.GetOutputPort()'))
                    blend[bg][fg].SetOpacity(1, 0.8)

                mapper.update({bg:{fg:vtk.vtkImageMapper()}})
                mapper[bg][fg].SetInputConnection(blend[bg][fg].GetOutputPort())
                mapper[bg][fg].SetColorWindow(255)
                mapper[bg][fg].SetColorLevel(127.5)

                actor.update({bg:{fg:vtk.vtkActor2D()}})
                actor[bg][fg].SetMapper(mapper[bg][fg])

                imager.update({bg:{fg:vtk.vtkRenderer()}})
                imager[bg][fg].AddActor2D(actor[bg][fg])
                imager[bg][fg].SetViewport(column * deltaX, row * deltaY, (column + 1) * deltaX, (row + 1) * deltaY)

                renWin.AddRenderer(imager[bg][fg])

                column += 1

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "TestAllBlends.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
示例#30
0
def renderIBC(filePrefix, imgLow, imgHigh):
    global picker, redCone, greenCone
    #
    # This example reads a volume dataset, extracts an isosurface that
    # represents the skin and displays it.
    #
    
    
    # The following reader is used to read a series of 2D slices (images)
    # that compose the volume. The slice dimensions are set, and the
    # pixel spacing. The data Endianness must also be specified. The reader
    # usese the FilePrefix in combination with the slice number to construct
    # filenames using the format FilePrefix.%d. (In this case the FilePrefix
    # is the root name of the file: quarter.)
    #vtkVolume16Reader v13R
    #  v13R SetDataDimensions 1388 1040
    #  v13R SetDataByteOrderToBigEndian 
    #  v13R SetFilePrefix  "IBC146h.R_s"
    #  v13R SetImageRange 0  44
    #  v13R SetDataSpacing  1 1 2
      
    # Image reader
    v13G = vtk.vtkTIFFReader()
    v13G.SetDataExtent(1, 1380, 1, 1030, imgLow, imgHigh)
    v13G.SetDataByteOrderToLittleEndian() 
    v13G.SetFilePrefix(filePrefix)
    v13G.SetDataSpacing(0.1, 0.1, 0.6)
    
    # Gaussian Smoothing
    gaus_v13G = vtk.vtkImageGaussianSmooth()
    gaus_v13G.SetDimensionality(3)
    gaus_v13G.SetStandardDeviation(1)
    gaus_v13G.SetRadiusFactors(1, 1, 1)
    gaus_v13G.SetInput(v13G.GetOutput())
    
    
    # Set up the volume rendering
    volumeMapper = vtk.vtkVolumeTextureMapper3D()
    volumeMapper.SetInput(v13G.GetOutput())
    
    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    
    
    # Surface rendering
    bactExtractor = vtk.vtkMarchingCubes()
    bactExtractor.SetInputConnection(gaus_v13G.GetOutputPort())
    bactExtractor.SetValue(0,20000)
    
#    bactNormals = vtk.vtkPolyDataNormals()
#    bactNormals.SetInputConnection(bactExtractor.GetOutputPort())
#    bactNormals.SetFeatureAngle(90.0)
#    
#    bactStripper = vtk.vtkStripper()
#    bactStripper.SetInputConnection(bactNormals.GetOutputPort())
#    
    bactLocator = vtk.vtkCellLocator()
    bactLocator.SetDataSet(bactExtractor.GetOutput())
    bactLocator.LazyEvaluationOn()
#    
#    bactMapper = vtk.vtkPolyDataMapper()
#    bactMapper.SetInputConnection(bactStripper.GetOutputPort())
#    bactMapper.ScalarVisibilityOff()
    
    
#    skinE_v13G = vtk.vtkContourFilter()
##    skinE_v13G = vtk.vtkMarchingCubes()
#    skinE_v13G.UseScalarTreeOn()
#    skinE_v13G.SetInput(gaus_v13G.GetOutput())
#    skinE_v13G.SetValue(0, 10000)
#    
    smooth_v13G = vtk.vtkSmoothPolyDataFilter()
    smooth_v13G.SetInput(bactExtractor.GetOutput())
    smooth_v13G.SetNumberOfIterations(50)
    
    deci_v13G = vtk.vtkDecimatePro()
    deci_v13G.SetInput(smooth_v13G.GetOutput())
    deci_v13G.SetTargetReduction(0.5)
    deci_v13G.PreserveTopologyOn()
    
    smoother_v13G = vtk.vtkSmoothPolyDataFilter()
    smoother_v13G.SetInput(deci_v13G.GetOutput())
    smoother_v13G.SetNumberOfIterations(50)
    
    skinNormals_v13G = vtk.vtkPolyDataNormals()
    skinNormals_v13G.SetInput(deci_v13G.GetOutput())
    skinNormals_v13G.SetFeatureAngle(60.0)
    
    
    skinStripper_v13G = vtk.vtkStripper()
    skinStripper_v13G.SetInput(skinNormals_v13G.GetOutput())
    
    
    skinMapper_v13G = vtk.vtkPolyDataMapper()
    skinMapper_v13G.SetInput(skinStripper_v13G.GetOutput())
    skinMapper_v13G.ScalarVisibilityOff()
    
    skin_v13G = vtk.vtkActor()
    skin_v13G.SetMapper(skinMapper_v13G)
    skin_v13G.GetProperty().SetDiffuseColor(0.2, 1, 0.2)
    skin_v13G.GetProperty().SetSpecular(.1)
    skin_v13G.GetProperty().SetSpecularPower(5)
    skin_v13G.GetProperty().SetOpacity(0.9)
    
    
    # It is convenient to create an initial view of the data. The FocalPoint
    # and Position form a vector direction. Later on (ResetCamera() method)
    # this vector is used to position the camera to look at the data in
    # this direction.
    aCamera = vtk.vtkCamera()
    aCamera.SetViewUp(0, 0, -1)
    aCamera.SetPosition(0, 1.1, 2)
    aCamera.SetFocalPoint(0, -0.25, 0)
    aCamera.ComputeViewPlaneNormal()
    
    
    
    # Actors are added to the renderer. An initial camera view is created.
    # The Dolly() method moves the camera towards the FocalPoint,
    # thereby enlarging the image.
    #aRenderer AddActor skin_v13R
    ren.AddActor(skin_v13G)
    ren.SetActiveCamera(aCamera)
    ren.ResetCamera() 
    aCamera.Dolly(1.0)
   
    
    # Note that when camera movement occurs (as it does in the Dolly()
    # method), the clipping planes often need adjusting. Clipping planes
    # consist of two planes: near and far along the view direction. The 
    # near plane clips out objects in front of the plane the far plane
    # clips out objects behind the plane. This way only what is drawn
    # between the planes is actually rendered.
    ren.ResetCameraClippingRange()
    
    
    # render
    renWin.Render()
    
    # CONE PICKER RENDER
    
    #---------------------------------------------------------
    # the cone points along the -x axis
    coneSource = vtk.vtkConeSource()
    coneSource.CappingOn()
    coneSource.SetHeight(2)
    coneSource.SetRadius(1)
    coneSource.SetResolution(11)
    coneSource.SetCenter(1,0,0)
    coneSource.SetDirection(-1,0,0)
    
    coneMapper = vtk.vtkDataSetMapper()
    coneMapper.SetInputConnection(coneSource.GetOutputPort())
    
    redCone = vtk.vtkActor()
    redCone.PickableOff()
    redCone.SetMapper(coneMapper)
    redCone.GetProperty().SetColor(1,0,0)
    
    greenCone = vtk.vtkActor()
    greenCone.PickableOff()
    greenCone.SetMapper(coneMapper)
    greenCone.GetProperty().SetColor(0,1,0)
    
    # Add the two cones (or just one, if you want)
    ren.AddViewProp(redCone)
    ren.AddViewProp(greenCone)
    
    #---------------------------------------------------------
    # the picker
    picker = vtk.vtkVolumePicker()
    picker.SetTolerance(1e-6)
    picker.SetVolumeOpacityIsovalue(0.1)
    # locator is optional, but improves performance for large polydata
    picker.AddLocator(bactLocator)
    
    #---------------------------------------------------------
    # custom interaction
    iren.AddObserver("MouseMoveEvent", MoveCursor)

    
    # END CONE PICKER RENDER
    
    # initialize and start the interactor
    iren.Initialize()
    iren.Start()
示例#31
0
view.SetAreaSizeArrayName("num_in_vertex")
view.SetAreaColorArrayName("level")
view.SetAreaLabelArrayName("vertex_ids")
view.SetLabelPriorityArrayName("scale")
view.SetAreaLabelVisibility(True)
view.SetAreaHoverArrayName("vertex_ids")
view.SetDisplayHoverText(True)
view.SetShrinkPercentage(SHRINK)
view.SetLayerThickness(ICEHEIGHT)
view.UseGradientColoringOff()
view.Update()

# print view.GetRepresentation(0)

# TESTING
pnmReader = vtk.vtkTIFFReader()
pnmReader.SetFileName("/Users/emonson/Programming/Python/VTK/VSItext2c.tif")
# pnmReader.SetFileName("/Users/emonson/Programming/VTK_cvs/VTKData/Data/beach.tif")
pnmReader.SetOrientationType(4)
# pnmReader.Update()
# END TESTING

tex = vtk.vtkTexture()
# tex.SetInput(WCimageData)
tex.SetInputConnection(pnmReader.GetOutputPort())
# tex.SetLookupTable(lut)

# Apply texture to polydata in vtkTexturedTreeAreaRepresentation through View
view.SetTexture(tex)

# Apply a theme to the views
示例#32
0
def loadVolume(filename, c, alpha, wire, bc, edges, legend, texture, smoothing,
               threshold, connectivity, scaling):
    '''Return vtkActor from a TIFF stack or SLC file'''
    if not os.path.exists(filename):
        vc.printc(('Error in loadVolume: Cannot find file', filename), c=1)
        return None

    print('..reading file:', filename)
    if '.tif' in filename.lower():
        reader = vtk.vtkTIFFReader()
    elif '.slc' in filename.lower():
        reader = vtk.vtkSLCReader()
        if not reader.CanReadFile(filename):
            vc.printc('Sorry bad SLC file ' + filename, 1)
            exit(1)
    reader.SetFileName(filename)
    reader.Update()
    image = reader.GetOutput()

    if smoothing:
        print('  gaussian smoothing data with volume_smoothing =', smoothing)
        smImg = vtk.vtkImageGaussianSmooth()
        smImg.SetDimensionality(3)
        vu.setInput(smImg, image)
        smImg.SetStandardDeviations(smoothing, smoothing, smoothing)
        smImg.Update()
        image = smImg.GetOutput()

    scrange = image.GetScalarRange()
    if not threshold:
        threshold = (2 * scrange[0] + scrange[1]) / 3.
        a = '  isosurfacing volume with automatic iso_threshold ='
    else:
        a = '  isosurfacing volume with iso_threshold ='
    print(a, round(threshold, 2), scrange)
    cf = vtk.vtkContourFilter()
    vu.setInput(cf, image)
    cf.UseScalarTreeOn()
    cf.ComputeScalarsOff()
    cf.SetValue(0, threshold)
    cf.Update()

    clp = vtk.vtkCleanPolyData()
    vu.setInput(clp, cf.GetOutput())
    clp.Update()
    image = clp.GetOutput()

    if connectivity:
        print('  applying connectivity filter, select largest region')
        conn = vtk.vtkPolyDataConnectivityFilter()
        conn.SetExtractionModeToLargestRegion()
        vu.setInput(conn, image)
        conn.Update()
        image = conn.GetOutput()

    if scaling:
        print('  scaling xyz by factors', scaling)
        tf = vtk.vtkTransformPolyDataFilter()
        vu.setInput(tf, image)
        trans = vtk.vtkTransform()
        trans.Scale(scaling)
        tf.SetTransform(trans)
        tf.Update()
        image = tf.GetOutput()
    return vu.makeActor(image, c, alpha, wire, bc, edges, legend, texture)
示例#33
0
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Test the merging of points with texture data.
# Points should only be merged if they have identical
# geometric positions and data (in this case texture
# coordinates).

# The texture map
cheers = vtk.vtkTIFFReader()
cheers.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")

imageTexture = vtk.vtkTexture()
imageTexture.InterpolateOn()
imageTexture.SetInputConnection(cheers.GetOutputPort())

# Create four planes with some coincident points. Some of
# points have identical texture coordinates, some do not.
# First plane patch.
pd0 = vtk.vtkPolyData()
p0 = vtk.vtkPoints()
polys0 = vtk.vtkCellArray()
pd0.SetPoints(p0)
pd0.SetPolys(polys0)

p0.SetNumberOfPoints(9)
p0.SetPoint(0, 0,4,0)
p0.SetPoint(1, 1,4,0)
p0.SetPoint(2, 2,4,0)
示例#34
0
 def __init__(self, filepaths):
     VolumeImageReader.__init__(self, filepaths)
     self.reader = vtk.vtkTIFFReader()
示例#35
0
from vtk.util.misc import vtkGetDataRoot, vtkGetTempDir

gotWarning = False
gotError = False


def WarningCallback(obj, evt):
    global gotWarning
    gotWarning = True


VTK_DATA_ROOT = vtkGetDataRoot()
VTK_TEMP_DIR = vtkGetTempDir()

# Image pipeline
image1 = vtk.vtkTIFFReader()
image1.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")
# "beach.tif" image contains ORIENTATION tag which is
# ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
# reader parses this tag and sets the internal TIFF image
# orientation accordingly.  To overwrite this orientation with a vtk
# convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
# SetOrientationType method with parameter value of 4.
image1.SetOrientationType(4)
image1.Update()

filename = VTK_TEMP_DIR + "/" + "pngw1.png"
testKey = "test key"
testValue = "test value"
longKey = "0123456789012345678901234567890123456789"\
          "0123456789012345678901234567890123456789"
示例#36
0
文件: main.py 项目: zibneuro/convert
if not os.path.isdir(input_folder_name):
  print("Error: input directory '" + input_folder_name + "' does not exist")
  exit()

# Check if the output directory exists
if not os.path.isdir(output_folder_name):
  print("Error: output directory '" + output_folder_name + "' does not exist")
  exit()

# Very important! The following values are for the virtual fish project
voxel_size = [0.798, 0.798, 2.0]
print("\nIMPORTANT: using the following voxel size: " + str(voxel_size[0]) + ", " + str(voxel_size[1]) + ", " + str(voxel_size[2]))
print("the meshes will be saved in " + output_folder_name)

# The VTK stuff
img_reader = vtk.vtkTIFFReader()
# Gaussian image filter
img_smoother = vtk.vtkImageGaussianSmooth()
img_smoother.SetDimensionality(3)
img_smoother.SetRadiusFactor(3)
# Marching cubes
marching_cubes = vtk.vtkImageMarchingCubes()
marching_cubes.SetValue(0, 128)
# Mesh writer
mesh_writer = vtk.vtkPLYWriter()

# First of all, we collect the names of the tiff files
tiff_file_names = list()

# Get the file names of the tif images in the provided folder
for file_name in os.listdir(input_folder_name):
示例#37
0
    def img2dcm(self, input_img, output, img_type, img_number): 

        if img_type == "jpg":
            print "JPG"
            image = vtk.vtkJPEGReader()
            image.SetFileName(input_img)
            image.Update()
            
        elif img_type == "tif":
            print "TIF"
            image = vtk.vtkTIFFReader()
            image.SetFileName(input_img)
            image.Update()
            
        elif img_type == "bmp":
            print "BMP"
            image = vtk.vtkBMPReader()
            image.SetFileName(input_img)
            image.Allow8BitBMPOn()
            image.Update()
            
        elif img_type == "png": 
            print "PNG"
            image = vtk.vtkPNGReader()
            image.SetFileName(input_img)
            image.SetDataSpacing(self.spacing)
            image.Update()

        elif img_type == "vti": 
            print "VTI"
            image = vtk.vtkXMLImageDataReader()
            image.SetFileName(input_img)
            image.Update()
        
            #if (orientation == 0):
        image_pos = img_number * self.spacing[2]
        image_localization = image_pos

        # print image_pos, img_number, image.GetOutput().GetScalarRange()

        img_clone = vtk.vtkImageData()
        img_clone.DeepCopy(image.GetOutput())
        img_clone.SetSpacing(self.spacing)
        img_clone.Update()

        # v = vtk.vtkImageViewer()
        # v.SetInput(image.GetOutput())
        # v.SetColorLevel(500)
        # v.SetColorWindow(240)
        # v.Render()

        # time.sleep(3)

        # a = vtk.vtkImageCast()
        # a.SetOutputScalarTypeToUnsignedChar()
        # a.SetInput(image.GetOutput())
        # a.ClampOverflowOn()
        # a.Update()

        #b = vtk.vtkJPEGWriter()
        #b.SetFileName("C:\\teste.jpg")
        #b.SetInput(a.GetOutput())
        #b.writer()

        #spacing = image.GetOutput().GetSpacing()
        #elif (orientation == 1):
        #    image_pos[0] =  image_pos[0] + thickness
        #    image_localization = image_localization + thickness
        #    img_number = img_number + 1
        
        #elif (orientation == 2):
        #    image_pos[1] =  image_pos[1] + thickness
        #    image_localization = image_localization + thickness
        #    img_number = img_number + 1
        pos = 0, 0, image_pos
        print pos

        # transform = vtk.vtkTransform()
        # transform.Translate(pos)

        # transform_filter = vtk.vtkImageReslice()
        # transform_filter.SetInput(image.GetOutput())
        # transform_filter.SetResliceTransform(transform)
        # transform_filter.Update()

        properties = vtk.vtkMedicalImageProperties()
        properties.SetModality(self.modality)
        properties.SetInstitutionName(self.institution)
        properties.SetPatientName(self.patient)
        properties.SetSliceThickness(str(self.spacing[2]))
        properties.SetSeriesNumber(str(self.serie))
        properties.SetImageNumber(str(img_number))
        properties.SetPatientID(self.patient_id)
        properties.SetStudyID(self.study_id)
        properties.AddUserDefinedValue("Image Position (Patient)", "%.5f\\%.5f\\%.5f" %
                                       (pos[0], pos[1], pos[2]))
        properties.AddUserDefinedValue("Instance Number", str(img_number))
        print str(img_number), properties.GetNumberOfUserDefinedValues()

        writer = vtkgdcm.vtkGDCMImageWriter()
        writer.SetInput(img_clone)
        writer.SetStudyUID(self.study_uid)
        writer.SetSeriesUID(self.series_uid)
        writer.SetMedicalImageProperties(properties)
        writer.SetFileName(output)
        # writer.SetImageFormat(vtk.VTK_LUMINANCE)
        writer.SetFileDimensionality(3)
        writer.Write()
               
        reader = gdcm.Reader()
        reader.SetFileName(output)
        reader.Read()

        anon = gdcm.Anonymizer()
        anon.SetFile(reader.GetFile())
        anon.Replace(gdcm.Tag(0x0020, 0x0013), str(img_number))
        anon.Replace(gdcm.Tag(0x0028, 0x0030), "%.6f\\%.6f" % (self.spacing[0],
                                                               self.spacing[1]))

        writer = gdcm.Writer()
        writer.SetFile(reader.GetFile())
        writer.SetFileName(output)
        writer.Write()    

        # print spacing, pos, image.GetOutput().GetScalarRange()

        # writer = ivDicom.DicomWriter()
        # writer.SetFileName(output)
        # writer.SaveIsNew(image.GetOutput())
        # 
        # writer.SetAcquisitionModality(self.modality)
        # writer.SetInstitutionName(self.institution)
        # writer.SetStudyID(self.study_uid)
        # writer.SetPatientID(self.patient_id)
        # writer.SetPatientName(self.patient)
        # writer.SetImageThickness(self.spacing[2])
        # writer.SetImageSeriesNumber(self.serie)
        # writer.SetImageNumber(img_number)
        # writer.SetImagePosition(pos)
        # writer.SetImageLocation(image_localization)
        # writer.SetPixelSpacing(self.spacing[:2])
        # writer.Save()

        print "Written", input_img, "->", output
示例#38
0
#!/usr/bin/env python
import os
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Image pipeline
image1 = vtk.vtkTIFFReader()
image1.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")
# "beach.tif" image contains ORIENTATION tag which is
# ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
# reader parses this tag and sets the internal TIFF image
# orientation accordingly.  To overwrite this orientation with a vtk
# convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
# SetOrientationType method with parameter value of 4.
image1.SetOrientationType(4)
image1.Update()

sp = vtk.vtkStructuredPoints()
sp.SetDimensions(image1.GetOutput().GetDimensions())
sp.SetExtent(image1.GetOutput().GetExtent())
sp.SetScalarType(
  image1.GetOutput().GetScalarType(), image1.GetOutputInformation(0))
sp.SetNumberOfScalarComponents(
  image1.GetOutput().GetNumberOfScalarComponents(),
  image1.GetOutputInformation(0))
sp.GetPointData().SetScalars(image1.GetOutput().GetPointData().GetScalars())

luminance = vtk.vtkImageLuminance()
luminance.SetInputData(sp)
示例#39
0
def loadTifImage(filename):

    step = 1.0

    import os, os.path
    dir = os.path.split(filename)[0]
    name = os.path.split(filename)[1]

    for file in os.listdir(dir):
        if os.path.splitext(file)[1] == '.log':
            logfile = file
            break

    print 'logfile', dir + '/' + logfile

    inFile = open(dir + '/' + logfile, 'r')
    line = inFile.readline().split()

    eof = False
    while not eof:
        if len(line) == 0:
            line = inFile.readline().split()
            if len(line) == 0:
                eof = True
        if (len(line) == 4) and line[0] == 'Result' and line[
                1] == 'Image' and line[2] == 'Width':
            resultimagewidth = line[3]
        if (len(line) == 4) and line[0] == 'Result' and line[
                1] == 'Image' and line[2] == 'Height':
            resultimageheight = line[3]
        if (len(line) == 3) and line[0] == 'Pixel' and line[1] == 'Size':
            pixelsize = line[2]
        line = inFile.readline().split()

    resultimagewidth = int(resultimagewidth.partition('=')[2])
    resultimageheight = int(resultimageheight.partition('=')[2])
    spacing = float(pixelsize.partition('=')[2])

    if pixelsize.partition('=')[0] == '(um)':
        spacing = spacing * 0.001

    names = os.listdir(dir)
    nboffiles = len(names) - 2
    nameonly = os.path.splitext(name)[0]
    fileprefix = os.path.join(dir, nameonly.rpartition('_')[0] + '_')

    reader = vtk.vtkTIFFReader()
    reader.SetFileDimensionality(2)
    reader.SetNumberOfScalarComponents(1)

    print 'spacing: ', spacing, spacing, spacing * step
    print 'dimensions: ', resultimagewidth, resultimageheight, nboffiles
    print 'extent: ', 0, resultimagewidth - 1, 0, resultimageheight - 1, 0, nboffiles - 1
    print 'bounds: ', 0, resultimagewidth * spacing, 0, resultimageheight * spacing, 0, nboffiles * spacing * step

    reader.SetFilePrefix(fileprefix)
    if len(nameonly.rpartition('_')[2]) == 2:
        reader.SetFilePattern("%s%02d.tif")
    elif len(nameonly.rpartition('_')[2]) == 3:
        reader.SetFilePattern("%s%03d.tif")
    reader.SetDataSpacing(
        1.0, 1.0, step
    )  # bizarre: si je mets (spacing,spacing,spacing*step) et remplace par (1.0,1.0,spacing*step) -> vtkImageChangeInformation
    reader.SetDataExtent(0, resultimagewidth - 1, 0, resultimageheight - 1, 0,
                         nboffiles - 1)
    reader.Update()

    rescale = vtk.vtkImageChangeInformation()
    rescale.SetInput(reader.GetOutput())
    rescale.SetOutputOrigin(0.0, 0.0, 0.0)
    rescale.SetSpacingScale(spacing, spacing, spacing)
    rescale.Update()

    return rescale.GetOutput()
示例#40
0
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create the RenderWindow, Renderer and Interactor
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

imageIn = vtk.vtkTIFFReader()
imageIn.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")
# "beach.tif" image contains ORIENTATION tag which is
# ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
# reader parses this tag and sets the internal TIFF image
# orientation accordingly.  To overwrite this orientation with a vtk
# convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
# SetOrientationType method with parameter value of 4.
imageIn.SetOrientationType(4)
imageIn.GetExecutive().SetReleaseDataFlag(0, 0)
imageIn.Update()


def PowerOfTwo(amt):
    ''' Finds the first power of two >= amt. '''
    pow = 0
    amt -= 1
示例#41
0
    def testAllMaskBits(self):

        # This script calculates the luminance of an image

        renWin = vtk.vtkRenderWindow()


        # Image pipeline

        image1 = vtk.vtkTIFFReader()
        image1.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")

        # "beach.tif" image contains ORIENTATION tag which is
        # ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
        # reader parses this tag and sets the internal TIFF image
        # orientation accordingly.  To overwrite this orientation with a vtk
        # convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
        # SetOrientationType method with parameter value of 4.
        image1.SetOrientationType(4)

        shrink = vtk.vtkImageShrink3D()
        shrink.SetInputConnection(image1.GetOutputPort())
        shrink.SetShrinkFactors(2, 2, 1)

        operators = ["ByPass", "And", "Nand", "Xor", "Or", "Nor"]

        operator = dict()
        mapper = dict()
        actor = dict()
        imager = dict()

        for idx, op in enumerate(operators):
            if op != "ByPass":
                operator.update({idx: vtk.vtkImageMaskBits()})
                operator[idx].SetInputConnection(shrink.GetOutputPort())
                eval('operator[' + str(idx) + '].SetOperationTo' + op + '()')
                operator[idx].SetMasks(255, 255, 0)

            mapper.update({idx: vtk.vtkImageMapper()})
            if op != "ByPass":
                mapper[idx].SetInputConnection(operator[idx].GetOutputPort())
            else:
                mapper[idx].SetInputConnection(shrink.GetOutputPort())
            mapper[idx].SetColorWindow(255)
            mapper[idx].SetColorLevel(127.5)

            actor.update({idx: vtk.vtkActor2D()})
            actor[idx].SetMapper(mapper[idx])

            imager.update({idx: vtk.vtkRenderer()})
            imager[idx].AddActor2D(actor[idx])

            renWin.AddRenderer(imager[idx])


        column = 0
        row = 0
        deltaX = 1.0 / 3.0
        deltaY = 1.0 / 2.0

        for idx in range(len(operators)):
            imager[idx].SetViewport(column * deltaX, row * deltaY, (column + 1) * deltaX, (row + 1) * deltaY)
            column += 1
            if column > 2:
                column = 0
                row += 1

        renWin.SetSize(384, 256)

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "TestAllMaskBits.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
示例#42
0
def main():
    # Initialize argument and constant variables
    parser = ArgumentParser("Create isosurfacing of object")
    parser.add_argument("infections")
    parser.add_argument("recovered")
    parser.add_argument("deaths")
    parser.add_argument("density")
    parser.add_argument("climate_max")
    parser.add_argument("climate_min")
    parser.add_argument("location")
    parser.add_argument("migration")
    parser.add_argument("sat")
    parser.add_argument("--camera",
                        type=str,
                        help="Optional camera settings file")

    args = parser.parse_args()

    global sat_x
    global sat_y
    global max_cases
    global max_radius

    global infections_color
    global recovered_color
    global deaths_color

    global infections_opacity
    global recovered_opacity
    global deaths_opacity

    global infections_data
    global recovered_data
    global deaths_data

    global legend_circle_actors
    global legend_text_actors

    global max_weight

    global ren

    app = QApplication([])
    window = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(window)

    # Read in data for global confirmed cases
    with open(args.infections) as csvDataFile:
        csv_reader = csv.reader(csvDataFile)
        for row in csv_reader:
            # We do not need country/province name, so we remove the first two columns
            if (row[2] != 0 or row[3] != 0):
                infections_data.append(row[2:])
    infections_data = infections_data[1:]

    # Read in data for global deaths
    with open(args.deaths) as csvDataFile:
        csv_reader = csv.reader(csvDataFile)
        for row in csv_reader:
            if (row[2] != 0 or row[3] != 0):
                deaths_data.append(row[2:])
    deaths_data = deaths_data[1:]

    # Read in data for global recovered cases
    with open(args.recovered) as csvDataFile:
        csv_reader = csv.reader(csvDataFile)
        for row in csv_reader:
            if (row[2] != 0 or row[3] != 0):
                recovered_data.append(row[2:])
    recovered_data = recovered_data[1:]

    numDates = len(infections_data[0]) - 3
    max_cases = compute_max(date)

    # Create reader for density file
    density_reader = vtk.vtkTIFFReader()
    density_reader.SetFileName(args.density)
    density_reader.Update()

    density_log = vtk.vtkImageLogarithmicScale()
    density_log.SetInputConnection(density_reader.GetOutputPort())
    density_log.SetConstant(0.435)
    density_log.Update()
    density_range = density_log.GetOutput().GetScalarRange()

    climate_max_reader = vtk.vtkTIFFReader()
    climate_max_reader.SetFileName(args.climate_max + "-" +
                                   str(initial_date.month.real).zfill(2) +
                                   ".tif")
    climate_max_reader.Update()
    climate_max_range = [-40, 45]

    climate_min_reader = vtk.vtkTIFFReader()
    climate_min_reader.SetFileName(args.climate_min + "-" +
                                   str(initial_date.month.real).zfill(2) +
                                   ".tif")
    climate_min_reader.Update()
    climate_min_range = [-50, 30]

    sat_reader = vtk.vtkJPEGReader()
    sat_reader.SetFileName(args.sat)
    sat_reader.Update()
    sat_dimensions = sat_reader.GetOutput().GetDimensions()
    sat_x = sat_dimensions[0]
    sat_y = sat_dimensions[1]

    # Read in data for migration
    location_map = create_long_lat(args.location)
    migrations = []
    for filename in os.listdir(args.migration):
        if filename.endswith(".csv"):
            with open(args.migration + "\\" + filename) as csvDataFile:
                country = filename.split(".")[0]
                if country not in location_map:
                    continue
                loc_dst = location_map[country]
                csv_reader = csv.reader(csvDataFile)
                for row in csv_reader:
                    if row[2] not in location_map:
                        continue
                    loc_src = location_map[row[2]]
                    try:
                        migrations.append(
                            add_migration_info(loc_src, loc_dst, int(row[9])))
                    except ValueError:
                        continue

    line_actors = process_migration_actors(migrations)

    # Create a plane to map the satellite image onto
    plane = vtk.vtkPlaneSource()
    plane.SetCenter(0.0, 0.0, 0.0)
    plane.SetNormal(0.0, 0.0, 1.0)
    plane.SetPoint1(sat_x, 0, 0)
    plane.SetPoint2(0, sat_y, 0)

    # Create satellite image texture
    texture = vtk.vtkTexture()
    texture.SetInputConnection(sat_reader.GetOutputPort())

    # Map satellite texture to plane
    texturePlane = vtk.vtkTextureMapToPlane()
    texturePlane.SetInputConnection(plane.GetOutputPort())

    max_val = 100
    color_count = 1000

    density_ctf = vtk.vtkColorTransferFunction()
    density_ctf.AddRGBPoint(0, 0, 0, 0)
    density_ctf.AddRGBPoint(10, 0, 0, 1)
    density_ctf.AddRGBPoint(30, 0, 1, 1)
    density_ctf.AddRGBPoint(50, 1, 1, 0)
    density_ctf.AddRGBPoint(65, 1, 0.5, 0)
    density_ctf.AddRGBPoint(80, 1, 0, 0)

    density_lut = vtk.vtkLookupTable()
    density_lut.SetNumberOfTableValues(color_count)
    density_lut.Build()

    rgb = list(density_ctf.GetColor(0)) + [0]
    density_lut.SetTableValue(0, rgb)
    for i in range(1, color_count):
        rgb = list(density_ctf.GetColor(
            max_val * float(i) / color_count)) + [1]
        density_lut.SetTableValue(i, rgb)

    climate_ctf = vtk.vtkColorTransferFunction()
    climate_ctf.AddRGBPoint(5, 0, 0, 1)
    climate_ctf.AddRGBPoint(35, 0, 1, 1)
    climate_ctf.AddRGBPoint(65, 1, 1, 0)
    climate_ctf.AddRGBPoint(95, 1, 0, 0)

    climate_lut = vtk.vtkLookupTable()
    climate_lut.SetNumberOfTableValues(color_count)
    climate_lut.Build()

    for i in range(0, color_count):
        rgb = list(climate_ctf.GetColor(
            max_val * float(i) / color_count)) + [1]
        climate_lut.SetTableValue(i, rgb)

    # Create mappers
    density_mapper = vtk.vtkDataSetMapper()
    density_mapper.SetInputConnection(density_log.GetOutputPort())
    density_mapper.SetLookupTable(density_lut)
    density_mapper.SetScalarRange([0, density_range[1]])
    density_mapper.Update()

    climate_max_mapper = vtk.vtkDataSetMapper()
    climate_max_mapper.SetInputConnection(climate_max_reader.GetOutputPort())
    climate_max_mapper.SetLookupTable(climate_lut)
    climate_max_mapper.SetScalarRange(climate_max_range)
    climate_max_mapper.Update()

    climate_min_mapper = vtk.vtkDataSetMapper()
    climate_min_mapper.SetInputConnection(climate_min_reader.GetOutputPort())
    climate_min_mapper.SetLookupTable(climate_lut)
    climate_min_mapper.SetScalarRange(climate_min_range)
    climate_min_mapper.Update()

    sat_mapper = vtk.vtkPolyDataMapper()
    sat_mapper.SetInputConnection(texturePlane.GetOutputPort())

    density_actor = vtk.vtkActor()
    density_actor.SetMapper(density_mapper)
    density_actor.GetProperty().SetOpacity(0.99)
    density_actor.VisibilityOn()

    climate_max_actor = vtk.vtkActor()
    climate_max_actor.SetMapper(climate_max_mapper)
    climate_max_actor.GetProperty().SetOpacity(0.6)
    climate_max_actor.VisibilityOff()

    climate_min_actor = vtk.vtkActor()
    climate_min_actor.SetMapper(climate_min_mapper)
    climate_min_actor.GetProperty().SetOpacity(0.6)
    climate_min_actor.VisibilityOff()

    sat_actor = vtk.vtkActor()
    sat_actor.SetMapper(sat_mapper)
    sat_actor.SetTexture(texture)
    sat_actor.GetProperty().SetOpacity(0.6)

    # Make satellite image same size as contour map
    crange = sat_actor.GetXRange()[0] - sat_actor.GetXRange()[1]
    mrange = density_actor.GetXRange()[0] - density_actor.GetXRange()[1]
    density_actor.SetScale(crange / mrange)

    crange = sat_actor.GetXRange()[0] - sat_actor.GetXRange()[1]
    mrange = climate_max_actor.GetXRange()[0] - climate_max_actor.GetXRange(
    )[1]
    climate_max_actor.SetScale(crange / mrange)
    climate_min_actor.SetScale(crange / mrange)

    # Initialize renderer and place actors
    ren = vtk.vtkRenderer()

    ren.AddActor(density_actor)
    ren.AddActor(climate_max_actor)
    ren.AddActor(climate_min_actor)

    # Add legend actors
    add_legend_actors()

    # Add infections, recovered, and deaths actors
    infections_actors = []
    if (ui.infections_check.isChecked()):
        add_case_actors(date, infections_data, infections_actors,
                        infections_color, infections_opacity)

    recovered_actors = []
    if (ui.recovered_check.isChecked()):
        add_case_actors(date, recovered_data, recovered_actors,
                        recovered_color, recovered_opacity)

    deaths_actors = []
    if (ui.deaths_check.isChecked()):
        add_case_actors(date, deaths_data, deaths_actors, deaths_color,
                        deaths_opacity)

    for line_actor in line_actors:
        line_actor.VisibilityOn()
        ren.AddActor(line_actor)

    ren.AddActor(sat_actor)
    ren.ResetCamera()
    ren.SetBackground(0, 0, 0)

    # Initialize camera settings
    cam1 = ren.GetActiveCamera()
    cam1.Azimuth(0)
    cam1.Elevation(0)
    cam1.Roll(360)
    cam1.Zoom(1.5)

    ren.ResetCameraClippingRange()

    if args.camera:
        reader = open(args.camera, "r")
        line = reader.readline().split(",")
        cam1.SetPosition(float(line[0]), float(line[1]), float(line[2]))
        line = reader.readline().split(",")
        cam1.SetFocalPoint(float(line[0]), float(line[1]), float(line[2]))
        line = reader.readline().split(",")
        cam1.SetViewUp(float(line[0]), float(line[1]), float(line[2]))
        line = reader.readline().split(",")
        cam1.SetClippingRange(float(line[0]), float(line[1]))
        line = reader.readline().split(",")
        cam1.SetViewAngle(float(line[0]))
        line = reader.readline().split(",")
        cam1.SetParallelScale(float(line[0]))

    # Initialize PyQT5 UI and link to renderer
    ui.vtkWidget.GetRenderWindow().AddRenderer(ren)
    ui.vtkWidget.GetRenderWindow().SetSize(1280, 720)

    ui.vtkWidget.GetRenderWindow().AddRenderer(ren)
    ui.vtkWidget.GetRenderWindow().SetAlphaBitPlanes(True)
    ui.vtkWidget.GetRenderWindow().SetMultiSamples(False)
    iren = ui.vtkWidget.GetRenderWindow().GetInteractor()

    # create the scalar_bar
    density_scalar_bar = vtk.vtkScalarBarActor()
    density_scalar_bar.SetOrientationToHorizontal()
    density_scalar_bar.SetMaximumNumberOfColors(color_count)
    density_scalar_bar.SetLookupTable(density_lut)
    density_scalar_bar.SetTitle("Density (Log 10)")

    # create the scalar_bar_widget
    density_scalar_bar_widget = vtk.vtkScalarBarWidget()
    density_scalar_bar_widget.SetInteractor(iren)
    density_scalar_bar_widget.SetScalarBarActor(density_scalar_bar)
    density_scalar_bar_widget.On()

    # create the scalar_bar
    climate_scalar_bar = vtk.vtkScalarBarActor()
    climate_scalar_bar.SetOrientationToHorizontal()
    climate_scalar_bar.SetMaximumNumberOfColors(color_count)
    climate_scalar_bar.SetLookupTable(climate_lut)
    climate_scalar_bar.SetTitle("Temparature (Celsius)")

    # create the scalar_bar_widget
    climate_scalar_bar_widget = vtk.vtkScalarBarWidget()
    climate_scalar_bar_widget.SetInteractor(iren)
    climate_scalar_bar_widget.SetScalarBarActor(climate_scalar_bar)
    climate_scalar_bar_widget.Off()

    # Function to initialize slider settings
    def slider_setup(slider, val, bounds, interv):
        slider.setOrientation(QtCore.Qt.Horizontal)
        slider.setValue(float(val))
        slider.setSliderPosition(val)
        slider.setTracking(False)
        slider.setTickInterval(interv)
        slider.setTickPosition(QSlider.TicksAbove)
        slider.setRange(bounds[0], bounds[1])

    slider_setup(ui.time_slider, 0, [0, numDates], 1)

    window.show()
    window.setWindowState(Qt.WindowMaximized)
    iren.Initialize()

    def time_slider_callback(val):
        global max_cases
        global date
        date = val
        new_date = initial_date + timedelta(val)
        if new_date.month.real != ui.curr_month:
            ui.curr_month = new_date.month.real
            climate_max_reader.SetFileName(args.climate_max + "-" +
                                           str(ui.curr_month).zfill(2) +
                                           ".tif")
            climate_max_reader.Update()
            climate_min_reader.SetFileName(args.climate_min + "-" +
                                           str(ui.curr_month).zfill(2) +
                                           ".tif")
            climate_min_reader.Update()
        ui.date_label.setText("Date (" + new_date.strftime('%m/%d/%Y') + "):")

        # Remove old infections, recovered, and deaths actors
        remove_case_actors(infections_actors)
        remove_case_actors(recovered_actors)
        remove_case_actors(deaths_actors)
        remove_legend_actors()

        # Recompute max cases
        max_cases = compute_max(date)

        # Add infections, recovered, and deaths actors
        if (ui.infections_check.isChecked()):
            add_case_actors(date, infections_data, infections_actors,
                            infections_color, infections_opacity)
        if (ui.recovered_check.isChecked()):
            add_case_actors(date, recovered_data, recovered_actors,
                            recovered_color, recovered_opacity)
        if (ui.deaths_check.isChecked()):
            add_case_actors(date, deaths_data, deaths_actors, deaths_color,
                            deaths_opacity)
        add_legend_actors()

        ui.vtkWidget.GetRenderWindow().Render()

    def infections_callback():
        if (ui.infections_check.isChecked()):
            add_case_actors(date, infections_data, infections_actors,
                            infections_color, infections_opacity)
        else:
            remove_case_actors(infections_actors)

        ui.vtkWidget.GetRenderWindow().Render()

    def recovered_callback():
        if (ui.recovered_check.isChecked()):
            add_case_actors(date, recovered_data, recovered_actors,
                            recovered_color, recovered_opacity)
        else:
            remove_case_actors(recovered_actors)

        ui.vtkWidget.GetRenderWindow().Render()

    def deaths_callback():
        if (ui.deaths_check.isChecked()):
            add_case_actors(date, deaths_data, deaths_actors, deaths_color,
                            deaths_opacity)
        else:
            remove_case_actors(deaths_actors)

        ui.vtkWidget.GetRenderWindow().Render()

    def density_callback():
        if ui.density_check.isChecked():
            ui.climate_max_check.setChecked(False)
            ui.climate_min_check.setChecked(False)
            density_actor.VisibilityOn()
            density_scalar_bar_widget.On()
            ui.vtkWidget.GetRenderWindow().Render()
        else:
            density_actor.VisibilityOff()
            density_scalar_bar_widget.Off()
            ui.vtkWidget.GetRenderWindow().Render()

    def climate_max_callback():
        if ui.climate_max_check.isChecked():
            ui.density_check.setChecked(False)
            ui.climate_min_check.setChecked(False)
            climate_max_actor.VisibilityOn()
            climate_scalar_bar_widget.On()
            ui.vtkWidget.GetRenderWindow().Render()
        else:
            climate_max_actor.VisibilityOff()
            climate_scalar_bar_widget.Off()
            ui.vtkWidget.GetRenderWindow().Render()

    def climate_min_callback():
        if ui.climate_min_check.isChecked():
            ui.density_check.setChecked(False)
            ui.climate_max_check.setChecked(False)
            climate_min_actor.VisibilityOn()
            climate_scalar_bar_widget.On()
            ui.vtkWidget.GetRenderWindow().Render()
        else:
            climate_min_actor.VisibilityOff()
            climate_scalar_bar_widget.Off()
            ui.vtkWidget.GetRenderWindow().Render()

    def migration_callback():
        if ui.migration_check.isChecked():
            for line_actor in line_actors:
                line_actor.VisibilityOn()
            ui.vtkWidget.GetRenderWindow().Render()
        else:
            for line_actor in line_actors:
                line_actor.VisibilityOff()
            ui.vtkWidget.GetRenderWindow().Render()

    # Handle screenshot button event
    def screenshot_callback():
        save_frame(ren.GetActiveCamera(), ui.vtkWidget.GetRenderWindow(),
                   ui.log)

    # Handle show camera settings button event
    def camera_callback():
        print_camera_settings(ren.GetActiveCamera(), ui.camera_info, ui.log)

    # Handle quit button event
    def quit_callback():
        sys.exit()

    # Register callbacks to UI
    ui.time_slider.valueChanged.connect(time_slider_callback)
    ui.push_screenshot.clicked.connect(screenshot_callback)
    ui.push_camera.clicked.connect(camera_callback)
    ui.push_quit.clicked.connect(quit_callback)

    ui.infections_check.stateChanged.connect(infections_callback)
    ui.recovered_check.stateChanged.connect(recovered_callback)
    ui.deaths_check.stateChanged.connect(deaths_callback)
    ui.density_check.stateChanged.connect(density_callback)
    ui.climate_max_check.stateChanged.connect(climate_max_callback)
    ui.climate_min_check.stateChanged.connect(climate_min_callback)
    ui.migration_check.stateChanged.connect(migration_callback)

    # Terminate setup for PyQT5 interface
    sys.exit(app.exec_())
示例#43
0
    def createImageData(main_window,
                        image_files,
                        output_image,
                        *finish_fn_args,
                        info_var=None,
                        convert_numpy=False,
                        convert_raw=True,
                        resample=False,
                        target_size=0.125,
                        crop_image=False,
                        origin=(0, 0, 0),
                        target_z_extent=(0, 0),
                        tempfolder=None,
                        finish_fn=None,
                        **finish_fn_kwargs):
        # print("Create image data")
        if len(image_files) == 1:
            image = image_files[0]
            file_extension = os.path.splitext(image)[1]

        else:
            for image in image_files:
                file_extension = imghdr.what(image)
                if file_extension != 'tiff':
                    main_window.e(
                        '', '',
                        'When reading multiple files, all files must TIFF formatted.'
                    )
                    error_title = "Read Error"
                    error_text = "Error reading file: ({filename})".format(
                        filename=image)
                    displayFileErrorDialog(main_window,
                                           message=error_text,
                                           title=error_title)
                    return

        if file_extension in ['.mha', '.mhd']:
            createProgressWindow(main_window, "Converting", "Converting Image")
            image_worker = Worker(loadMetaImage, main_window, image,
                                  output_image, info_var, resample,
                                  target_size, crop_image, origin,
                                  target_z_extent, convert_numpy, convert_raw,
                                  tempfolder)

        elif file_extension in ['.npy']:
            createProgressWindow(main_window, "Converting", "Converting Image")
            image_worker = Worker(loadNpyImage, image, output_image, info_var,
                                  resample, target_size, crop_image, origin,
                                  target_z_extent)

        elif file_extension in ['tif', 'tiff', '.tif', '.tiff']:
            reader = vtk.vtkTIFFReader()
            reader.AddObserver("ErrorEvent", main_window.e)
            createProgressWindow(main_window, "Converting", "Converting Image")
            image_worker = Worker(loadTif, image_files, reader, output_image,
                                  convert_numpy, info_var)

        elif file_extension in ['.raw']:
            if 'file_type' in info_var and info_var['file_type'] == 'raw':
                createConvertRawImageWorker(main_window, image, output_image,
                                            info_var, resample, target_size,
                                            crop_image, origin,
                                            target_z_extent, finish_fn)
                return
            else:  #if we aren't given the image dimensions etc, the user needs to enter them
                main_window.raw_import_dialog = createRawImportDialog(
                    main_window, image, output_image, info_var, resample,
                    target_size, crop_image, origin, target_z_extent,
                    finish_fn)
                dialog = main_window.raw_import_dialog['dialog'].show()
                return

        else:
            main_window.e(
                '', '',
                'File format is not supported. Accepted formats include: .mhd, .mha, .npy, .tif, .raw'
            )
            error_title = "Error"
            error_text = "Error reading file: ({filename})".format(
                filename=image)
            displayFileErrorDialog(main_window,
                                   message=error_text,
                                   title=error_title)
            return

        main_window.progress_window.setValue(10)

        image_worker.signals.progress.connect(
            partial(progress, main_window.progress_window))
        if finish_fn is not None:
            image_worker.signals.finished.connect(
                lambda: finish_fn(*finish_fn_args, **finish_fn_kwargs))
        main_window.threadpool = QThreadPool()
        main_window.threadpool.start(image_worker)
        print("Started worker")
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Set up the pipeline
reader = vtk.vtkTIFFReader()
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/beach.tif")
# "beach.tif" image contains ORIENTATION tag which is
# ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
# reader parses this tag and sets the internal TIFF image
# orientation accordingly.  To overwrite this orientation with a vtk
# convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
# SetOrientationType method with parameter value of 4.
reader.SetOrientationType(4)
ia = vtk.vtkImageActor()
ia.GetMapper().SetInputConnection(reader.GetOutputPort())
ren = vtk.vtkRenderer()
ren.AddActor(ia)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetSize(400, 400)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
rbz = vtk.vtkInteractorStyleRubberBandZoom()
rbz.SetInteractor(iren)
iren.SetInteractorStyle(rbz)
renWin.Render()
# Test style
iren.SetEventInformationFlipY(250, 250, 0, 0, "0", 0, "0")
示例#45
0
文件: clipArt.py 项目: 151706061/VTK
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create the RenderWindow, Renderer and Interactor
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
imageIn = vtk.vtkTIFFReader()
imageIn.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/beach.tif")
# "beach.tif" image contains ORIENTATION tag which is
# ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
# reader parses this tag and sets the internal TIFF image
# orientation accordingly.  To overwrite this orientation with a vtk
# convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
# SetOrientationType method with parameter value of 4.
imageIn.SetOrientationType(4)
imageIn.GetExecutive().SetReleaseDataFlag(0,0)
imageIn.Update()
def PowerOfTwo (amt,__vtk__temp0=0,__vtk__temp1=0):
    pow = 0
    amt = amt + -1
    while 1:
        amt = expr.expr(globals(), locals(),["amt",">>","1"])
        pow = pow + 1
        if (amt <= 0):
示例#46
0
    def testAllBlendsFloat(self):

        # This script blends images that consist of float data

        renWin = vtk.vtkRenderWindow()
        renWin.SetSize(512, 256)

        # Image pipeline

        inputImage = vtk.vtkTIFFReader()
        inputImage.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")

        # "beach.tif" image contains ORIENTATION tag which is
        # ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
        # reader parses this tag and sets the internal TIFF image
        # orientation accordingly.  To overwrite this orientation with a vtk
        # convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
        # SetOrientationType method with parameter value of 4.
        inputImage.SetOrientationType(4)

        inputImage2 = vtk.vtkBMPReader()
        inputImage2.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp")

        # shrink the images to a reasonable size

        shrink1 = vtk.vtkImageShrink3D()
        shrink1.SetInputConnection(inputImage.GetOutputPort())
        shrink1.SetShrinkFactors(2, 2, 1)

        shrink2 = vtk.vtkImageShrink3D()
        shrink2.SetInputConnection(inputImage2.GetOutputPort())
        shrink2.SetShrinkFactors(2, 2, 1)

        color = vtk.vtkImageShiftScale()
        color.SetOutputScalarTypeToFloat()
        color.SetShift(0)
        color.SetScale(1.0 / 255)
        color.SetInputConnection(shrink1.GetOutputPort())

        backgroundColor = vtk.vtkImageShiftScale()
        backgroundColor.SetOutputScalarTypeToFloat()
        backgroundColor.SetShift(0)
        backgroundColor.SetScale(1.0 / 255)
        backgroundColor.SetInputConnection(shrink2.GetOutputPort())

        # create a greyscale version

        luminance = vtk.vtkImageLuminance()
        luminance.SetInputConnection(color.GetOutputPort())

        backgroundLuminance = vtk.vtkImageLuminance()
        backgroundLuminance.SetInputConnection(backgroundColor.GetOutputPort())

        # create an alpha mask

        alpha = vtk.vtkImageThreshold()
        alpha.SetInputConnection(luminance.GetOutputPort())
        alpha.ThresholdByLower(0.9)
        alpha.SetInValue(1.0)
        alpha.SetOutValue(0.0)

        # make luminanceAlpha and colorAlpha versions

        luminanceAlpha = vtk.vtkImageAppendComponents()
        luminanceAlpha.AddInputConnection(luminance.GetOutputPort())
        luminanceAlpha.AddInputConnection(alpha.GetOutputPort())

        colorAlpha = vtk.vtkImageAppendComponents()
        colorAlpha.AddInputConnection(color.GetOutputPort())
        colorAlpha.AddInputConnection(alpha.GetOutputPort())

        foregrounds = ["luminance", "luminanceAlpha", "color", "colorAlpha"]
        backgrounds = ["backgroundColor", "backgroundLuminance"]

        deltaX = 1.0 / 4.0
        deltaY = 1.0 / 2.0

        blend = dict()
        mapper = dict()
        actor = dict()
        imager = dict()

        for row, bg in enumerate(backgrounds):
            for column, fg in enumerate(foregrounds):
                blend.update({bg:{fg:vtk.vtkImageBlend()}})
                blend[bg][fg].AddInputConnection(eval(bg + '.GetOutputPort()'))
                if bg == "backgroundColor" or fg == "luminance" or fg == "luminanceAlpha":
                    blend[bg][fg].AddInputConnection(eval(fg + '.GetOutputPort()'))
                    blend[bg][fg].SetOpacity(1, 0.8)

                mapper.update({bg:{fg:vtk.vtkImageMapper()}})
                mapper[bg][fg].SetInputConnection(blend[bg][fg].GetOutputPort())
                mapper[bg][fg].SetColorWindow(1.0)
                mapper[bg][fg].SetColorLevel(0.5)

                actor.update({bg:{fg:vtk.vtkActor2D()}})
                actor[bg][fg].SetMapper(mapper[bg][fg])

                imager.update({bg:{fg:vtk.vtkRenderer()}})
                imager[bg][fg].AddActor2D(actor[bg][fg])
                imager[bg][fg].SetViewport(column * deltaX, row * deltaY, (column + 1) * deltaX, (row + 1) * deltaY)

                renWin.AddRenderer(imager[bg][fg])

        # render and interact with data

        iRen = vtk.vtkRenderWindowInteractor()
        iRen.SetRenderWindow(renWin);
        renWin.Render()

        img_file = "TestAllBlendsFloat.png"
        vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25)
        vtk.test.Testing.interact()
示例#47
0
文件: demo3d.py 项目: anilkunwar/OOF2
    def __init__(self,imagetype,prefix,extent):

        if imagetype == "jpg":
            reader = vtk.vtkJPEGReader()
        elif imagetype == "pnm":
            reader = vtk.vtkPNMReader()
        elif imagetype == "tif":
            reader = vtk.vtkTIFFReader()
        # todo: add more image types
        else:
            print "unknown type!"
            sys.exit()

        reader.SetDataExtent(extent)
        #reader.SetFilePrefix(prefix)
        reader.SetFilePattern(prefix)
        reader.SetDataSpacing(1,1,1)
        imageoriginal = reader.GetOutput()

        # pad the image with extra voxels because of vtk off by 1
        # annoyance in calculating image bounds
#         extentcopy = extent[:]
#         for i in xrange(1,7,2):
#             extentcopy[i] += 1
#         padder = vtk.vtkImageConstantPad()
#         padder.SetInput(imageoriginal)
#         padder.SetOutputWholeExtent(extentcopy) 
#         padder.SetConstant(255) # arbitrary
#         self.image = padder.GetOutput()
#         self.image.Update()
        self.image = imageoriginal
        self.image.Update()

        # must use this particular mapper so color images work, also
        # handles off by 1 annoyance in a slightly better way.
        mapper = vtk.vtkFixedPointVolumeRayCastMapper()
        mapper.IntermixIntersectingGeometryOn()
        min_extent = min(extent[1:6:2])
        # todo: can use a built in function for this
        # for very small images we need to reset the sample distance
        if min_extent < 50:
            mapper.SetSampleDistance(float(min_extent)/100)
            mapper.SetInteractiveSampleDistance(float(min_extent)/50)
        mapper.SetInput(self.image)

        volproperty = vtk.vtkVolumeProperty()
        volproperty.IndependentComponentsOff()

        # we initially set the opacity to a constant value of 1, but
        # we need the function so we can change it later
        self.opacity = vtk.vtkPiecewiseFunction()
        self.opacity.AddSegment(0,1,255,1)

        # the type of color function we use depends on how many
        # components the image has, 3 for a color image, 1 for a black
        # and white image
        num_components = self.image.GetNumberOfScalarComponents()
        
        if num_components == 1:
            color = vtk.vtkPiecewiseFunction()
            color.AddSegment(0,0,255,1)
            volproperty.SetColor(color)
            volproperty.SetScalarOpacity(self.opacity)
        elif num_components == 4:
##             red = vtk.vtkColorTransferFunction()
##             red.AddRGBSegment(0,0,0,0,255,1,0,0)
##             green = vtk.vtkColorTransferFunction()
##             green.AddRGBSegment(0,0,0,0,255,0,1,0)
##             blue = vtk.vtkColorTransferFunction()
##             blue.AddRGBSegment(0,0,0,0,255,0,0,1)
##             volproperty.SetColor(0,red)
##             volproperty.SetColor(1,green)
##             volproperty.SetColor(2,blue)
            volproperty.SetScalarOpacity(self.opacity)
##             volproperty.SetScalarOpacity(1,self.opacity)
##             volproperty.SetScalarOpacity(2,self.opacity)
        else:
            pass
        print num_components

        volume = vtk.vtkVolume()
        volume.SetMapper(mapper)
        volume.SetProperty(volproperty)

        self.ren = vtk.vtkRenderer()
        self.ren.AddActor(volume)
        # on mac, this shows only the cone
        #self.DrawCone()
        #print self.ren.VisibleActorCount()
        #print self.ren.VisibleVolumeCount()
        self.ren.ResetCamera()