def GetRawDICOMData(filenames,fileID):
  print filenames,fileID
  vtkRealDcmReader = vtk.vtkDICOMImageReader()
  vtkRealDcmReader.SetFileName("%s/%s"%(rootdir,filenames[0]) )
  vtkRealDcmReader.Update()
  vtkRealData = vtk.vtkImageCast()
  vtkRealData.SetOutputScalarTypeToFloat()
  vtkRealData.SetInput( vtkRealDcmReader.GetOutput() )
  vtkRealData.Update( )
  real_image = vtkRealData.GetOutput().GetPointData() 
  real_array = vtkNumPy.vtk_to_numpy(real_image.GetArray(0)) 

  vtkImagDcmReader = vtk.vtkDICOMImageReader()
  vtkImagDcmReader.SetFileName("%s/%s"%(rootdir,filenames[1]) )
  vtkImagDcmReader.Update()
  vtkImagData = vtk.vtkImageCast()
  vtkImagData.SetOutputScalarTypeToFloat()
  vtkImagData.SetInput( vtkImagDcmReader.GetOutput() )
  vtkImagData.Update( )
  imag_image = vtkImagData.GetOutput().GetPointData() 
  imag_array = vtkNumPy.vtk_to_numpy(imag_image.GetArray(0)) 

  vtkAppend = vtk.vtkImageAppendComponents()
  vtkAppend.SetInput( 0,vtkRealDcmReader.GetOutput() )
  vtkAppend.SetInput( 1,vtkImagDcmReader.GetOutput() )
  vtkAppend.Update( )

  vtkDcmWriter = vtk.vtkDataSetWriter()
  vtkDcmWriter.SetFileName("rawdata.%04d.vtk" % fileID )
  vtkDcmWriter.SetInput(vtkAppend.GetOutput())
  vtkDcmWriter.Update()

  return (real_array,imag_array)
Exemplo n.º 2
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageAppendComponents(), 'Processing.',
         ('vtkImageData', 'vtkImageData', 'vtkImageData', 'vtkImageData', 'vtkImageData'), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Exemplo n.º 3
0
def _get_img(obj, flip=False):

    obj = np.asarray(obj)

    if obj.ndim == 3: # has shape (nx,ny, ncolor_alpha_chan)
        iac = vtk.vtkImageAppendComponents()
        nchan = obj.shape[2] # get number of channels in inputimage (L/LA/RGB/RGBA)
        for i in range(nchan):
            if flip:
                arr = np.flip(np.flip(obj[:,:,i], 0), 0).ravel()
            else:
                arr = np.flip(obj[:,:,i], 0).ravel()
            varb = numpy_to_vtk(arr, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
            varb.SetName("RGBA")
            imgb = vtk.vtkImageData()
            imgb.SetDimensions(obj.shape[1], obj.shape[0], 1)
            imgb.GetPointData().AddArray(varb)
            imgb.GetPointData().SetActiveScalars("RGBA")
            iac.AddInputData(imgb)
        iac.Update()
        img = iac.GetOutput()

    elif obj.ndim == 2: # black and white
        if flip:
            arr = np.flip(obj[:,:], 0).ravel()
        else:
            arr = obj.ravel()
        varb = numpy_to_vtk(arr, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
        varb.SetName("RGBA")
        img = vtk.vtkImageData()
        img.SetDimensions(obj.shape[1], obj.shape[0], 1)
        img.GetPointData().AddArray(varb)
        img.GetPointData().SetActiveScalars("RGBA")
    return img
Exemplo n.º 4
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()
            self.SetInputData(iac.GetOutput())
            #self.mirror()

        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()
            picr.SetFileName(obj)
            picr.Update()
            self.SetInputData(picr.GetOutput())
Exemplo n.º 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()
Exemplo n.º 6
0
    def __init__(self):
        super(camphorBlendedStacks, self).__init__()

        self.blender = vtk.vtkImageBlend()
        self.sliceBlender = vtk.vtkImageBlend()

        self.output = self.blender
        self.sliceOutput = self.sliceBlender

        self.stack = [camphorStack() for i in range(2)]
        self.append = vtk.vtkImageAppendComponents()
        self.slice = [vtk.vtkImageReslice() for i in range(2)]
        self.sliceAppend = vtk.vtkImageAppendComponents()

        # Display mode: raw fluorescence or dF/F
        self.displayMode = 0

        self.numberOfTimeFrames = 0
        self.currentTimeFrame = None
def computeImageHessian(
        image=None,
        image_filename=None,
        verbose=0):

    myVTK.myPrint(verbose, "*** computeImageHessian ***")

    image = myVTK.initImage(image, image_filename, verbose-1)

    image_dimensionality = myVTK.computeImageDimensionality(
        image=image,
        verbose=verbose-1)

    image_gradient = vtk.vtkImageGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        image_gradient.SetInputData(image)
    else:
        image_gradient.SetInput(image)
    image_gradient.SetDimensionality(image_dimensionality)
    image_gradient.Update()
    image_w_gradient = image_gradient.GetOutput()

    image_append_components = vtk.vtkImageAppendComponents()
    for k_dim in xrange(image_dimensionality):
        image_extract_components = vtk.vtkImageExtractComponents()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_extract_components.SetInputData(image_w_gradient)
        else:
            image_extract_components.SetInput(image_w_gradient)
        image_extract_components.SetComponents(k_dim)
        image_extract_components.Update()
        image_w_gradient_component = image_extract_components.GetOutput()

        image_gradient = vtk.vtkImageGradient()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_gradient.SetInputData(image_w_gradient_component)
        else:
            image_gradient.SetInput(image_w_gradient_component)
        image_gradient.SetDimensionality(image_dimensionality)
        image_gradient.Update()
        image_w_hessian_component = image_gradient.GetOutput()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_append_components.AddInputData(image_w_hessian_component)
        else:
            image_append_components.AddInput(image_w_hessian_component)

    image_append_components.Update()
    image_w_hessian = image_append_components.GetOutput()

    name = image.GetPointData().GetScalars().GetName()
    image.GetPointData().AddArray(image_w_gradient.GetPointData().GetArray(name+"Gradient"))
    image.GetPointData().AddArray(image_w_hessian.GetPointData().GetArray(name+"GradientGradient"))
    image.GetPointData().SetActiveScalars(name+"GradientGradient")

    return image
Exemplo n.º 8
0
def computeImageHessian(image=None, image_filename=None, verbose=0):

    myVTK.myPrint(verbose, "*** computeImageHessian ***")

    image = myVTK.initImage(image, image_filename, verbose - 1)

    image_dimensionality = myVTK.computeImageDimensionality(image=image,
                                                            verbose=verbose -
                                                            1)

    image_gradient = vtk.vtkImageGradient()
    if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
        image_gradient.SetInputData(image)
    else:
        image_gradient.SetInput(image)
    image_gradient.SetDimensionality(image_dimensionality)
    image_gradient.Update()
    image_w_gradient = image_gradient.GetOutput()

    image_append_components = vtk.vtkImageAppendComponents()
    for k_dim in xrange(image_dimensionality):
        image_extract_components = vtk.vtkImageExtractComponents()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_extract_components.SetInputData(image_w_gradient)
        else:
            image_extract_components.SetInput(image_w_gradient)
        image_extract_components.SetComponents(k_dim)
        image_extract_components.Update()
        image_w_gradient_component = image_extract_components.GetOutput()

        image_gradient = vtk.vtkImageGradient()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_gradient.SetInputData(image_w_gradient_component)
        else:
            image_gradient.SetInput(image_w_gradient_component)
        image_gradient.SetDimensionality(image_dimensionality)
        image_gradient.Update()
        image_w_hessian_component = image_gradient.GetOutput()
        if (vtk.vtkVersion.GetVTKMajorVersion() >= 6):
            image_append_components.AddInputData(image_w_hessian_component)
        else:
            image_append_components.AddInput(image_w_hessian_component)

    image_append_components.Update()
    image_w_hessian = image_append_components.GetOutput()

    name = image.GetPointData().GetScalars().GetName()
    image.GetPointData().AddArray(
        image_w_gradient.GetPointData().GetArray(name + "Gradient"))
    image.GetPointData().AddArray(
        image_w_hessian.GetPointData().GetArray(name + "GradientGradient"))
    image.GetPointData().SetActiveScalars(name + "GradientGradient")

    return image
Exemplo n.º 9
0
    def __init__(self, comedi, cfg_dict):
        self._comedi = comedi
        self._cfg = cfg_dict

        # we'll store our local bindings here
        self._d1 = None
        self._d2m = None
        self._conf = None
        self._cmap_range = [-1024, 3072]
        self._cmap_type = CMAP_BLUE_TO_YELLOW_PL

        # color scales thingy
        self._color_scales = vtk_kit.color_scales.ColorScales()

        # instantiate us a slice viewer
        rwi,ren = comedi.get_compvis_vtk()
        self._sv = comedi_utils.CMSliceViewer(rwi, ren)
        # now make our own MapToColors
        ct = 32
        lut = self._sv.ipws[0].GetLookupTable()
        self._cmaps = [vtktudoss.vtkCVImageMapToColors() for _ in range(3)]
        for i,cmap in enumerate(self._cmaps):
            cmap.SetLookupTable(lut)
            cmap.SetConfidenceThreshold(ct)
            self._sv.ipws[i].SetColorMap(cmap)

        self._set_confidence_threshold_ui(ct)


        comedi.sync_slice_viewers.add_slice_viewer(self._sv)

        # now build up the VTK pipeline #############################
        # we'll use these to scale data between 0 and max.
        self._ss1 = vtk.vtkImageShiftScale()
        self._ss1.SetOutputScalarTypeToShort()
        self._ss2 = vtk.vtkImageShiftScale()
        self._ss2.SetOutputScalarTypeToShort()

        # we have to cast the confidence to shorts as well
        self._ssc = vtk.vtkImageShiftScale()
        self._ssc.SetOutputScalarTypeToShort()

        self._iac = vtk.vtkImageAppendComponents()
        # data1 will form the context
        self._iac.SetInput(0, self._ss1.GetOutput())
        # subtraction will form the focus
        self._iac.SetInput(1, self._ss2.GetOutput())
        # third input will be the confidence
        self._iac.SetInput(2, self._ssc.GetOutput())

        # event bindings ############################################
        self._bind_events()
Exemplo n.º 10
0
def GetRawDICOMData(filenames,fileID):
  print filenames,fileID
  vtkRealDcmReader = vtk.vtkDICOMImageReader()
  vtkRealDcmReader.SetFileName("%s/%s"%(rootdir,filenames[0]) )
  vtkRealDcmReader.Update()
  vtkRealData = vtk.vtkImageCast()
  vtkRealData.SetOutputScalarTypeToFloat()
  vtkRealData.SetInput( vtkRealDcmReader.GetOutput() )
  vtkRealData.Update( )
  real_image = vtkRealData.GetOutput().GetPointData() 
  real_array = vtkNumPy.vtk_to_numpy(real_image.GetArray(0)) 

  vtkImagDcmReader = vtk.vtkDICOMImageReader()
  vtkImagDcmReader.SetFileName("%s/%s"%(rootdir,filenames[1]) )
  vtkImagDcmReader.Update()
  vtkImagData = vtk.vtkImageCast()
  vtkImagData.SetOutputScalarTypeToFloat()
  vtkImagData.SetInput( vtkImagDcmReader.GetOutput() )
  vtkImagData.Update( )
  imag_image = vtkImagData.GetOutput().GetPointData() 
  imag_array = vtkNumPy.vtk_to_numpy(imag_image.GetArray(0)) 

  vtkAppend = vtk.vtkImageAppendComponents()
  vtkAppend.SetInput( 0,vtkRealDcmReader.GetOutput() )
  vtkAppend.SetInput( 1,vtkImagDcmReader.GetOutput() )
  vtkAppend.Update( )

  # write raw data
  vtkRawData = vtkAppend.GetOutput()
  vtkRawData.SetSpacing( spacing )
  vtkDcmWriter = vtk.vtkDataSetWriter()
  vtkDcmWriter.SetFileTypeToBinary()
  vtkDcmWriter.SetFileName("s%d/rawdata.%04d.vtk" % (dirID,fileID) )
  vtkDcmWriter.SetInput( vtkRawData )
  vtkDcmWriter.Update()

  # write raw phase data
  vtkPhase = vtk.vtkImageMathematics()
  vtkPhase.SetInput1( vtkRealData.GetOutput() )
  vtkPhase.SetInput2( vtkImagData.GetOutput() )
  vtkPhase.SetOperationToATAN2( )
  vtkPhase.Update( )
  vtkPhaseData = vtkPhase.GetOutput()
  vtkPhaseData.SetSpacing( spacing )
  vtkDcmWriter = vtk.vtkDataSetWriter()
  vtkDcmWriter.SetFileTypeToBinary()
  vtkDcmWriter.SetFileName("s%d/phase.%04d.vtk" % (dirID,fileID) )
  vtkDcmWriter.SetInput( vtkPhaseData)
  vtkDcmWriter.Update()

  return (real_array,imag_array)
Exemplo n.º 11
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()
Exemplo n.º 12
0
    def __init__(self):
        super(camphorBlendedVOIs, self).__init__()

        # data objects
        self.data = []  # reference to the data array

        # Blenders
        self.blender = vtk.vtkImageBlend()
        self.sliceBlender = vtk.vtkImageBlend()

        # Other objects
        self.image = []
        self.append = vtk.vtkImageAppendComponents()
        self.luminance = vtk.vtkImageLuminance()

        # Output objects
        self.output = self.blender
        self.sliceOutput = self.append
    def __init__(self, ren, renWin, iren):
        self.ren = ren
        self.renWin = renWin
        self.iren = iren

        # Create a gaussian
        gs = vtk.vtkImageGaussianSource()
        gs.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs.SetMaximum(255.0)
        gs.SetStandardDeviation(5)
        gs.SetCenter(15, 15, 15)

        # threshold to leave a gap that should show up for
        # gradient opacity
        t = vtk.vtkImageThreshold()
        t.SetInputConnection(gs.GetOutputPort())
        t.ReplaceInOn()
        t.SetInValue(0)
        t.ThresholdBetween(150, 200)

        # Use a shift scale to convert to unsigned char
        ss = vtk.vtkImageShiftScale()
        ss.SetInputConnection(t.GetOutputPort())
        ss.SetOutputScalarTypeToUnsignedChar()

        # grid will be used for two component dependent
        grid0 = vtk.vtkImageGridSource()
        grid0.SetDataScalarTypeToUnsignedChar()
        grid0.SetGridSpacing(10, 10, 10)
        grid0.SetLineValue(200)
        grid0.SetFillValue(10)
        grid0.SetDataExtent(0, 30, 0, 30, 0, 30)

        # use dilation to thicken the grid
        d = vtk.vtkImageContinuousDilate3D()
        d.SetInputConnection(grid0.GetOutputPort())
        d.SetKernelSize(3, 3, 3)

        # Now make a two component dependent
        iac = vtk.vtkImageAppendComponents()
        iac.AddInputConnection(d.GetOutputPort())
        iac.AddInputConnection(ss.GetOutputPort())

        # Some more gaussians for the four component indepent case
        gs1 = vtk.vtkImageGaussianSource()
        gs1.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs1.SetMaximum(255.0)
        gs1.SetStandardDeviation(4)
        gs1.SetCenter(5, 5, 5)

        t1 = vtk.vtkImageThreshold()
        t1.SetInputConnection(gs1.GetOutputPort())
        t1.ReplaceInOn()
        t1.SetInValue(0)
        t1.ThresholdBetween(150, 256)

        gs2 = vtk.vtkImageGaussianSource()
        gs2.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs2.SetMaximum(255.0)
        gs2.SetStandardDeviation(4)
        gs2.SetCenter(12, 12, 12)

        gs3 = vtk.vtkImageGaussianSource()
        gs3.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs3.SetMaximum(255.0)
        gs3.SetStandardDeviation(4)
        gs3.SetCenter(19, 19, 19)

        t3 = vtk.vtkImageThreshold()
        t3.SetInputConnection(gs3.GetOutputPort())
        t3.ReplaceInOn()
        t3.SetInValue(0)
        t3.ThresholdBetween(150, 256)

        gs4 = vtk.vtkImageGaussianSource()
        gs4.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs4.SetMaximum(255.0)
        gs4.SetStandardDeviation(4)
        gs4.SetCenter(26, 26, 26)

        # we need a few append filters ...
        iac1 = vtk.vtkImageAppendComponents()
        iac1.AddInputConnection(t1.GetOutputPort())
        iac1.AddInputConnection(gs2.GetOutputPort())

        iac2 = vtk.vtkImageAppendComponents()
        iac2.AddInputConnection(iac1.GetOutputPort())
        iac2.AddInputConnection(t3.GetOutputPort())

        iac3 = vtk.vtkImageAppendComponents()
        iac3.AddInputConnection(iac2.GetOutputPort())
        iac3.AddInputConnection(gs4.GetOutputPort())

        # create the four component dependend -
        # use lines in x, y, z for colors
        gridR = vtk.vtkImageGridSource()
        gridR.SetDataScalarTypeToUnsignedChar()
        gridR.SetGridSpacing(10, 100, 100)
        gridR.SetLineValue(250)
        gridR.SetFillValue(100)
        gridR.SetDataExtent(0, 30, 0, 30, 0, 30)

        dR = vtk.vtkImageContinuousDilate3D()
        dR.SetInputConnection(gridR.GetOutputPort())
        dR.SetKernelSize(2, 2, 2)

        gridG = vtk.vtkImageGridSource()
        gridG.SetDataScalarTypeToUnsignedChar()
        gridG.SetGridSpacing(100, 10, 100)
        gridG.SetLineValue(250)
        gridG.SetFillValue(100)
        gridG.SetDataExtent(0, 30, 0, 30, 0, 30)

        dG = vtk.vtkImageContinuousDilate3D()
        dG.SetInputConnection(gridG.GetOutputPort())
        dG.SetKernelSize(2, 2, 2)

        gridB = vtk.vtkImageGridSource()
        gridB.SetDataScalarTypeToUnsignedChar()
        gridB.SetGridSpacing(100, 100, 10)
        gridB.SetLineValue(0)
        gridB.SetFillValue(250)
        gridB.SetDataExtent(0, 30, 0, 30, 0, 30)

        dB = vtk.vtkImageContinuousDilate3D()
        dB.SetInputConnection(gridB.GetOutputPort())
        dB.SetKernelSize(2, 2, 2)

        # need some appending
        iacRG = vtk.vtkImageAppendComponents()
        iacRG.AddInputConnection(dR.GetOutputPort())
        iacRG.AddInputConnection(dG.GetOutputPort())

        iacRGB = vtk.vtkImageAppendComponents()
        iacRGB.AddInputConnection(iacRG.GetOutputPort())
        iacRGB.AddInputConnection(dB.GetOutputPort())

        iacRGBA = vtk.vtkImageAppendComponents()
        iacRGBA.AddInputConnection(iacRGB.GetOutputPort())
        iacRGBA.AddInputConnection(ss.GetOutputPort())

        # We need a bunch of opacity functions

        # this one is a simple ramp to .2
        rampPoint2 = vtk.vtkPiecewiseFunction()
        rampPoint2.AddPoint(0, 0.0)
        rampPoint2.AddPoint(255, 0.2)

        # this one is a simple ramp to 1
        ramp1 = vtk.vtkPiecewiseFunction()
        ramp1.AddPoint(0, 0.0)
        ramp1.AddPoint(255, 1.0)

        # this one shows a sharp surface
        surface = vtk.vtkPiecewiseFunction()
        surface.AddPoint(0, 0.0)
        surface.AddPoint(10, 0.0)
        surface.AddPoint(50, 1.0)
        surface.AddPoint(255, 1.0)


        # this one is constant 1
        constant1 = vtk.vtkPiecewiseFunction()
        constant1.AddPoint(0, 1.0)
        constant1.AddPoint(255, 1.0)

        # this one is used for gradient opacity
        gop = vtk.vtkPiecewiseFunction()
        gop.AddPoint(0, 0.0)
        gop.AddPoint(20, 0.0)
        gop.AddPoint(60, 1.0)
        gop.AddPoint(255, 1.0)


        # We need a bunch of color functions

        # This one is a simple rainbow
        rainbow = vtk.vtkColorTransferFunction()
        rainbow.SetColorSpaceToHSV()
        rainbow.HSVWrapOff()
        rainbow.AddHSVPoint(0, 0.1, 1.0, 1.0)
        rainbow.AddHSVPoint(255, 0.9, 1.0, 1.0)

        # this is constant red
        red = vtk.vtkColorTransferFunction()
        red.AddRGBPoint(0, 1, 0, 0)
        red.AddRGBPoint(255, 1, 0, 0)

        # this is constant green
        green = vtk.vtkColorTransferFunction()
        green.AddRGBPoint(0, 0, 1, 0)
        green.AddRGBPoint(255, 0, 1, 0)

        # this is constant blue
        blue = vtk.vtkColorTransferFunction()
        blue.AddRGBPoint(0, 0, 0, 1)
        blue.AddRGBPoint(255, 0, 0, 1)

        # this is constant yellow
        yellow = vtk.vtkColorTransferFunction()
        yellow.AddRGBPoint(0, 1, 1, 0)
        yellow.AddRGBPoint(255, 1, 1, 0)


        #ren = vtk.vtkRenderer()
        #renWin = vtk.vtkRenderWindow()
        self.renWin.AddRenderer(self.ren)
        self.renWin.SetSize(500, 500)
        #iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renWin)

        self.ren.GetCullers().InitTraversal()
        culler = self.ren.GetCullers().GetNextItem()
        culler.SetSortingStyleToBackToFront()

        # We need 25 mapper / actor pairs which we will render
        # in a grid. Going down we will vary the input data
        # with the top row unsigned char, then float, then
        # two dependent components, then four dependent components
        # then four independent components. Going across we
        # will vary the rendering method with MIP, Composite,
        # Composite Shade, Composite GO, and Composite GO Shade.

        # Create the 5 by 5 grids
        self.volumeProperty = [[0 for col in range(0, 5)] for row in range(0, 5)]
        self.volumeMapper = [[0 for col in range(0, 5)] for row in range(0, 5)]
        volume = [[0 for col in range(0, 5)] for row in range(0, 5)]

        for i in range(0, 5):
            for j in range(0, 5):

                self.volumeProperty[i][j] = vtk.vtkVolumeProperty()
                self.volumeMapper[i][j] = vtk.vtkFixedPointVolumeRayCastMapper()
                self.volumeMapper[i][j].SetSampleDistance(0.25)

                volume[i][j] = vtk.vtkVolume()
                volume[i][j].SetMapper(self.volumeMapper[i][j])
                volume[i][j].SetProperty(self.volumeProperty[i][j])

                volume[i][j].AddPosition(i * 30, j * 30, 0)

                self.ren.AddVolume(volume[i][j])



        for i in range(0, 5):

            self.volumeMapper[0][i].SetInputConnection(t.GetOutputPort())
            self.volumeMapper[1][i].SetInputConnection(ss.GetOutputPort())
            self.volumeMapper[2][i].SetInputConnection(iac.GetOutputPort())
            self.volumeMapper[3][i].SetInputConnection(iac3.GetOutputPort())
            self.volumeMapper[4][i].SetInputConnection(iacRGBA.GetOutputPort())

            self.volumeMapper[i][0].SetBlendModeToMaximumIntensity()
            self.volumeMapper[i][1].SetBlendModeToComposite()
            self.volumeMapper[i][2].SetBlendModeToComposite()
            self.volumeMapper[i][3].SetBlendModeToComposite()
            self.volumeMapper[i][4].SetBlendModeToComposite()

            self.volumeProperty[0][i].IndependentComponentsOn()
            self.volumeProperty[1][i].IndependentComponentsOn()
            self.volumeProperty[2][i].IndependentComponentsOff()
            self.volumeProperty[3][i].IndependentComponentsOn()
            self.volumeProperty[4][i].IndependentComponentsOff()

            self.volumeProperty[0][i].SetColor(rainbow)
            self.volumeProperty[0][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[0][i].SetGradientOpacity(constant1)

            self.volumeProperty[1][i].SetColor(rainbow)
            self.volumeProperty[1][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[1][i].SetGradientOpacity(constant1)

            self.volumeProperty[2][i].SetColor(rainbow)
            self.volumeProperty[2][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[2][i].SetGradientOpacity(constant1)

            self.volumeProperty[3][i].SetColor(0, red)
            self.volumeProperty[3][i].SetColor(1, green)
            self.volumeProperty[3][i].SetColor(2, blue)
            self.volumeProperty[3][i].SetColor(3, yellow)
            self.volumeProperty[3][i].SetScalarOpacity(0, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(1, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(2, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(3, rampPoint2)
            self.volumeProperty[3][i].SetGradientOpacity(0, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(1, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(2, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(3, constant1)
            self.volumeProperty[3][i].SetComponentWeight(0, 1)
            self.volumeProperty[3][i].SetComponentWeight(1, 1)
            self.volumeProperty[3][i].SetComponentWeight(2, 1)
            self.volumeProperty[3][i].SetComponentWeight(3, 1)

            self.volumeProperty[4][i].SetColor(rainbow)
            self.volumeProperty[4][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[4][i].SetGradientOpacity(constant1)

            self.volumeProperty[i][2].ShadeOn()
            self.volumeProperty[i][4].ShadeOn(0)
            self.volumeProperty[i][4].ShadeOn(1)
            self.volumeProperty[i][4].ShadeOn(2)
            self.volumeProperty[i][4].ShadeOn(3)


        self.volumeProperty[0][0].SetScalarOpacity(ramp1)
        self.volumeProperty[1][0].SetScalarOpacity(ramp1)
        self.volumeProperty[2][0].SetScalarOpacity(ramp1)
        self.volumeProperty[3][0].SetScalarOpacity(0, surface)
        self.volumeProperty[3][0].SetScalarOpacity(1, surface)
        self.volumeProperty[3][0].SetScalarOpacity(2, surface)
        self.volumeProperty[3][0].SetScalarOpacity(3, surface)
        self.volumeProperty[4][0].SetScalarOpacity(ramp1)

        self.volumeProperty[0][2].SetScalarOpacity(surface)
        self.volumeProperty[1][2].SetScalarOpacity(surface)
        self.volumeProperty[2][2].SetScalarOpacity(surface)
        self.volumeProperty[3][2].SetScalarOpacity(0, surface)
        self.volumeProperty[3][2].SetScalarOpacity(1, surface)
        self.volumeProperty[3][2].SetScalarOpacity(2, surface)
        self.volumeProperty[3][2].SetScalarOpacity(3, surface)
        self.volumeProperty[4][2].SetScalarOpacity(surface)

        self.volumeProperty[0][4].SetScalarOpacity(surface)
        self.volumeProperty[1][4].SetScalarOpacity(surface)
        self.volumeProperty[2][4].SetScalarOpacity(surface)
        self.volumeProperty[3][4].SetScalarOpacity(0, surface)
        self.volumeProperty[3][4].SetScalarOpacity(1, surface)
        self.volumeProperty[3][4].SetScalarOpacity(2, surface)
        self.volumeProperty[3][4].SetScalarOpacity(3, surface)
        self.volumeProperty[4][4].SetScalarOpacity(surface)

        self.volumeProperty[0][3].SetGradientOpacity(gop)
        self.volumeProperty[1][3].SetGradientOpacity(gop)
        self.volumeProperty[2][3].SetGradientOpacity(gop)
        self.volumeProperty[3][3].SetGradientOpacity(0, gop)
        self.volumeProperty[3][3].SetGradientOpacity(2, gop)
        self.volumeProperty[4][3].SetGradientOpacity(gop)

        self.volumeProperty[3][3].SetScalarOpacity(0, ramp1)
        self.volumeProperty[3][3].SetScalarOpacity(2, ramp1)

        self.volumeProperty[0][4].SetGradientOpacity(gop)
        self.volumeProperty[1][4].SetGradientOpacity(gop)
        self.volumeProperty[2][4].SetGradientOpacity(gop)
        self.volumeProperty[3][4].SetGradientOpacity(0, gop)
        self.volumeProperty[3][4].SetGradientOpacity(2, gop)
        self.volumeProperty[4][4].SetGradientOpacity(gop)

        self.renWin.Render()

        self.ren.GetActiveCamera().Dolly(1.3)
        self.ren.GetActiveCamera().Azimuth(15)
        self.ren.GetActiveCamera().Elevation(5)
        self.ren.ResetCameraClippingRange()
Exemplo n.º 14
0
# component is a constant, the mapper decides the whole thing is
# translucent.  Our trick around this is to set the padding voxels to
# have a value of 255 in the alpha channel, representing total
# transparency while the rest of the fourth channel is set to be
# totally opaque, until we decide to mess with it.
ellipsoid.SetInValue(100)
ellipsoid.SetOutValue(255)

# Testing if a smoothly varying translucency works.  Seems to, to an extent.
smoother = vtk.vtkImageGaussianSmooth()
smoother.SetInput(ellipsoid.GetOutput())
smoother.SetRadiusFactors(50,50,50)
smoother.SetStandardDeviation(5,5,5)
smoother.SetDimensionality(3)

appender = vtk.vtkImageAppendComponents()
appender.AddInput(image)
#appender.AddInput(extractor.GetOutput())
#appender.AddInput(ellipsoid.GetOutput())
appender.AddInput(smoother.GetOutput())
image4comp = appender.GetOutput()
image4comp.Update()
#image4comp = imagepadded

# when we fill the fourth component "IndependentComponentsOff"
# rendering no longer works. On the other hand, we can't get opacity
# to work at all with "IndependentComponentsOn"
image4comp.GetPointData().GetScalars().FillComponent(3,0)

print image4comp.GetScalarComponentAsFloat(50,50,50,3)
print image4comp.GetScalarComponentAsFloat(5,5,5,3)
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
gs1 = vtk.vtkImageGaussianSource()
gs1.SetWholeExtent(0,31,0,31,0,31)
gs1.SetCenter(10,16,16)
gs1.SetMaximum(1000)
gs1.SetStandardDeviation(7)
gs2 = vtk.vtkImageGaussianSource()
gs2.SetWholeExtent(0,31,0,31,0,31)
gs2.SetCenter(22,16,16)
gs2.SetMaximum(1000)
gs2.SetStandardDeviation(7)
iac = vtk.vtkImageAppendComponents()
iac.AddInputConnection(gs1.GetOutputPort())
iac.AddInputConnection(gs2.GetOutputPort())
cf1 = vtk.vtkContourFilter()
cf1.SetInputConnection(iac.GetOutputPort())
cf1.SetValue(0,500)
cf1.SetArrayComponent(0)
cf2 = vtk.vtkContourFilter()
cf2.SetInputConnection(iac.GetOutputPort())
cf2.SetValue(0,500)
cf2.SetArrayComponent(1)
mapper1 = vtk.vtkPolyDataMapper()
mapper1.SetInputConnection(cf1.GetOutputPort())
mapper1.SetImmediateModeRendering(1)
mapper1.SetScalarRange(0,1)
mapper1.SetScalarVisibility(0)
Exemplo n.º 16
0
    def _buildPipeline(self):
        """Build underlying pipeline and configure rest of pipeline-dependent
        UI. 
        """
        
        # add the renderer
        self._renderer = vtk.vtkRenderer()
        self._renderer.SetBackground(0.5, 0.5, 0.5)
        self._viewFrame.rwi.GetRenderWindow().AddRenderer(
            self._renderer)
 
        self._histogram = vtkdevide.vtkImageHistogram2D()

        # make sure the user can't do anything entirely stupid
        istyle = vtk.vtkInteractorStyleImage()
        self._viewFrame.rwi.SetInteractorStyle(istyle)

        # we'll use this to keep track of our ImagePlaneWidget
        self._ipw = None
        self._overlayipw = None
        self._scalarBarWidget = None

        #
        self._appendPD = vtk.vtkAppendPolyData()

        self._extrude = vtk.vtkLinearExtrusionFilter()
        self._extrude.SetInput(self._appendPD.GetOutput())
        self._extrude.SetScaleFactor(1)
        self._extrude.SetExtrusionTypeToNormalExtrusion()
        self._extrude.SetVector(0,0,1)

        self._pdToImageStencil = vtk.vtkPolyDataToImageStencil()
        self._pdToImageStencil.SetInput(self._extrude.GetOutput())

        # stupid trick to make image with all ones, but as large as its
        # input
        
        self._allOnes = vtk.vtkImageThreshold()
        self._allOnes.ThresholdByLower(0.0)
        self._allOnes.ThresholdByUpper(0.0)
        self._allOnes.SetInValue(1.0)
        self._allOnes.SetOutValue(1.0)
        self._allOnes.SetInput(self._histogram.GetOutput())

        self._stencil = vtk.vtkImageStencil()
        self._stencil.SetInput(self._allOnes.GetOutput())
        #self._stencil.SetStencil(self._pdToImageStencil.GetOutput())
        self._stencil.ReverseStencilOff()
        self._stencil.SetBackgroundValue(0)

        self._lookupAppend = vtk.vtkImageAppendComponents()

        self._lookup = vtkdevide.vtkHistogramLookupTable()
        self._lookup.SetInput1(self._lookupAppend.GetOutput())        
        self._lookup.SetInput2(self._stencil.GetOutput())

        module_utils.create_standard_object_introspection(
            self, self._viewFrame, self._viewFrame.viewFramePanel,
            {'Module (self)' : self,
             'vtkHistogram2D' : self._histogram,
             'vtkRenderer' : self._renderer},
            self._renderer.GetRenderWindow())

        # add the ECASH buttons
        module_utils.create_eoca_buttons(self, self._viewFrame,
                                      self._viewFrame.viewFramePanel)
Exemplo n.º 17
0
    def showLayer(self):
        if self.volume != Null:
            self.ren.RemoveVolume(self.volume)
        
        sliceNumber = self.sliceNumber.text()
        sliceIntArray = sliceNumber.toUInt()
        sliceInt = sliceIntArray[0]
        
        print "cool, it is done"
        fr=gzip.open(self.fname[:-3]+"voxr","rb")
        dataRed=pickle.load(fr)
        self.data_matrix_red=numpy.uint8(dataRed)
        self.data_matrix_red=self.data_matrix_red[sliceInt-1:sliceInt+1,:,:]
        with file('layerView.txt', 'w') as outfile:
            for data_slice in self.data_matrix_red:

        # The formatting string indicates that I'm writing out
        # the values in left-justified columns 7 characters in width
        # with 2 decimal places.  
                numpy.savetxt(outfile, data_slice,fmt='%-7.1f')

        # Writing out a break to indicate different slices...
                outfile.write('# New slice\n')
        
        
        self.dataImporterR = vtk.vtkImageImport()
        data_string = self.data_matrix_red.tostring()
        self.dataImporterR.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterR.SetDataScalarTypeToUnsignedChar()
        self.dataImporterR.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_red.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterR.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterR.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        
        fg=gzip.open(self.fname[:-3]+"voxg","rb")
        dataGreen=pickle.load(fg)
        self.data_matrix_green=numpy.uint8(dataGreen)
        self.data_matrix_green = self.data_matrix_green[sliceInt-1:sliceInt+1,:,:] 
        self.dataImporterG = vtk.vtkImageImport()
        data_string = self.data_matrix_green.tostring()
        self.dataImporterG.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterG.SetDataScalarTypeToUnsignedChar()
        self.dataImporterG.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_green.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterG.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterG.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        
        
        fb=gzip.open(self.fname[:-3]+"voxb","rb")
        dataBlue=pickle.load(fb)
        self.data_matrix_blue=numpy.uint8(dataBlue)
        self.data_matrix_blue = self.data_matrix_blue[sliceInt-1:sliceInt+1,:,:] 
        self.dataImporterB = vtk.vtkImageImport()
        data_string = self.data_matrix_blue.tostring()
        self.dataImporterB.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterB.SetDataScalarTypeToUnsignedChar()
        self.dataImporterB.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_blue.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterB.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterB.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)

        
        self.append = vtk.vtkImageAppendComponents() 
        self.append.SetInputConnection(self.dataImporterR.GetOutputPort()) 
        self.append.AddInputConnection(self.dataImporterG.GetOutputPort()) 
        self.append.AddInputConnection(self.dataImporterB.GetOutputPort()) 
        self.append.Update() 
        
        volumeMapper = vtk.vtkSmartVolumeMapper()
        volumeMapper.SetInputConnection(self.append.GetOutputPort())
        
        volumeProperty = vtk.vtkVolumeProperty() 
        volumeProperty.ShadeOff()
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.IndependentComponentsOn()
        
        opacityTF1 = vtk.vtkPiecewiseFunction() 
        opacityTF1.AddPoint(   0.0,  0.0 ) 
        opacityTF1.AddPoint(   1.0,  0.33)
        opacityTF1.AddPoint(   128.0, 0.33) 
        opacityTF1.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(0,opacityTF1) 
        
        colourTF1 = vtk.vtkColorTransferFunction() 
        colourTF1.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF1.AddRGBPoint(   1.0,  0.0, 0.0, 0.1 )
        colourTF1.AddRGBPoint(   128.0, 0.0, 0.0, 0.5 ) 
        colourTF1.AddRGBPoint(   255.0, 0.0, 0.0, 1.0 ) 
        volumeProperty.SetColor(0,colourTF1)
        
        opacityTF2 = vtk.vtkPiecewiseFunction() 
        opacityTF2.AddPoint(   0.0,  0.0 ) 
        opacityTF2.AddPoint(   1.0,  0.33 ) 
        opacityTF2.AddPoint(   128.0, 0.33)
        opacityTF2.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(1,opacityTF2) 
        
        colourTF2 = vtk.vtkColorTransferFunction() 
        colourTF2.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF2.AddRGBPoint(   1.0,  0.0, 0.1, 0.0 )
        colourTF2.AddRGBPoint(   128.0, 0.0, 0.5, 0.0 ) 
        colourTF2.AddRGBPoint(   255.0, 0.0, 1.0, 0.0 ) 
        volumeProperty.SetColor(1,colourTF2)
        
        opacityTF3 = vtk.vtkPiecewiseFunction() 
        opacityTF3.AddPoint(   0.0,  0.0 ) 
        opacityTF3.AddPoint(   1.0,  0.33 ) 
        opacityTF3.AddPoint(   128.0, 0.33)
        opacityTF3.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(2,opacityTF3) 
        
        colourTF3 = vtk.vtkColorTransferFunction() 
        colourTF3.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF3.AddRGBPoint(   1.0,  0.1, 0.0, 0.0 )
        colourTF3.AddRGBPoint(   128.0, 0.5, 0.0, 0.0 ) 
        colourTF3.AddRGBPoint(   255.0, 1.0, 0.0, 0.0 ) 
        volumeProperty.SetColor(2,colourTF3)
   
        self.volume.SetMapper(volumeMapper)
        self.volume.SetProperty(volumeProperty)
                    
        #self.ren.RemoveActor(self.actor)
                    
        self.ren.AddVolume(self.volume)
        self.ren.SetBackground(0, 0, 0)
        # A simple function to be called when the user decides to quit the application.
        def exitCheck(obj, event):
            if obj.GetEventPending() != 0:
                obj.SetAbortRender(1)
                                     
            # Tell the application to use the function as an exit check.
        light = vtk.vtkLight()
        #light.SetColor(1, 1, 1)
        light.SwitchOff()
        self.ren.AddLight(light)
        
        renderWin = self.vtkWidget.GetRenderWindow()
        renderWin.AddObserver("AbortCheckEvent", exitCheck)
                    
        self.iren.Initialize()
        self.iren.Start()
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
gs1 = vtk.vtkImageGaussianSource()
gs1.SetWholeExtent(0, 31, 0, 31, 0, 31)
gs1.SetCenter(10, 16, 16)
gs1.SetMaximum(1000)
gs1.SetStandardDeviation(7)
gs2 = vtk.vtkImageGaussianSource()
gs2.SetWholeExtent(0, 31, 0, 31, 0, 31)
gs2.SetCenter(22, 16, 16)
gs2.SetMaximum(1000)
gs2.SetStandardDeviation(7)
iac = vtk.vtkImageAppendComponents()
iac.AddInputConnection(gs1.GetOutputPort())
iac.AddInputConnection(gs2.GetOutputPort())
cf1 = vtk.vtkContourFilter()
cf1.SetInputConnection(iac.GetOutputPort())
cf1.SetValue(0, 500)
cf1.SetArrayComponent(0)
cf2 = vtk.vtkContourFilter()
cf2.SetInputConnection(iac.GetOutputPort())
cf2.SetValue(0, 500)
cf2.SetArrayComponent(1)
mapper1 = vtk.vtkPolyDataMapper()
mapper1.SetInputConnection(cf1.GetOutputPort())
mapper1.SetImmediateModeRendering(1)
mapper1.SetScalarRange(0, 1)
mapper1.SetScalarVisibility(0)
Exemplo n.º 19
0
    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
            obj = np.asarray(obj)

            if len(obj.shape) == 3:  # has shape (nx,ny, ncolor_alpha_chan)
                iac = vtk.vtkImageAppendComponents()
                nchan = obj.shape[
                    2]  # get number of channels in inputimage (L/LA/RGB/RGBA)
                for i in range(nchan):
                    if flip:
                        arr = np.flip(np.flip(obj[:, :, i], 0), 0).ravel()
                    else:
                        arr = np.flip(obj[:, :, i], 0).ravel()
                    varb = numpy_to_vtk(arr,
                                        deep=True,
                                        array_type=vtk.VTK_UNSIGNED_CHAR)
                    varb.SetName("RGBA")
                    imgb = vtk.vtkImageData()
                    imgb.SetDimensions(obj.shape[1], obj.shape[0], 1)
                    imgb.GetPointData().AddArray(varb)
                    imgb.GetPointData().SetActiveScalars("RGBA")
                    iac.AddInputData(imgb)
                iac.Update()
                img = iac.GetOutput()

            elif len(obj.shape) == 2:  # black and white
                if flip:
                    arr = np.flip(obj[:, :], 0).ravel()
                else:
                    arr = obj.ravel()
                varb = numpy_to_vtk(arr,
                                    deep=True,
                                    array_type=vtk.VTK_UNSIGNED_CHAR)
                varb.SetName("RGBA")
                img = vtk.vtkImageData()
                img.SetDimensions(obj.shape[1], obj.shape[0], 1)
                img.GetPointData().AddArray(varb)
                img.GetPointData().SetActiveScalars("RGBA")

        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()
def scatterPlot(imagedata1, imagedata2, z, countVoxels=True, wholeVolume=True, logarithmic=True, bitDepth=8):
    """
	Create scatterplot
	"""
    imagedata1.SetUpdateExtent(imagedata1.GetWholeExtent())
    imagedata2.SetUpdateExtent(imagedata1.GetWholeExtent())

    imagedata1.Update()
    imagedata2.Update()
    range1 = imagedata1.GetScalarRange()
    range2 = imagedata2.GetScalarRange()

    n = 255
    # n = min(max(sc1max,sc2max),255)
    # d = (n+1) / float(2**bitDepth)
    if bitDepth is None:
        spacing1 = float(abs(range1[1] - range1[0])) / (n + 1)
        spacing2 = float(abs(range2[1] - range2[0])) / (n + 1)
    else:
        spacing1 = float(2 ** bitDepth) / (n + 1)
        spacing2 = float(2 ** bitDepth) / (n + 1)

    app = vtk.vtkImageAppendComponents()
    app.AddInput(imagedata1)
    app.AddInput(imagedata2)

    # shiftscale = vtk.vtkImageShiftScale()
    # shiftscale.SetOutputScalarTypeToUnsignedChar()
    # shiftscale.SetScale(d)
    # shiftscale.SetInputConnection(app.GetOutputPort())

    acc = vtk.vtkImageAccumulate()
    acc.SetComponentExtent(0, n, 0, n, 0, 0)
    acc.SetComponentOrigin(range1[0], range2[0], 0)
    acc.SetComponentSpacing(spacing1, spacing2, 0)
    # acc.SetInputConnection(shiftscale.GetOutputPort())
    acc.SetInputConnection(app.GetOutputPort())
    acc.Update()

    data = acc.GetOutput()
    origData = data

    originalRange = data.GetScalarRange()

    if logarithmic:
        Logging.info("Scaling scatterplot logarithmically", kw="imageop")
        logscale = vtk.vtkImageLogarithmicScale()
        logscale.SetInputConnection(acc.GetOutputPort())
        logscale.Update()
        data = logscale.GetOutput()

    x0, x1 = data.GetScalarRange()
    if countVoxels:
        Logging.info("Scalar range of scatterplot = ", x0, x1, kw="imageop")
        ctf = fire(x0, x1)
        ctf = equalize(data, ctf, x1)
        maptocolor = vtk.vtkImageMapToColors()
        maptocolor.SetInputConnection(data.GetProducerPort())
        maptocolor.SetLookupTable(ctf)
        maptocolor.SetOutputFormatToRGB()
        maptocolor.Update()
        data = maptocolor.GetOutput()
        ctf.originalRange = originalRange

    Logging.info("Scatterplot has dimensions: ", data.GetDimensions(), data.GetExtent(), kw="imageop")
    data.SetWholeExtent(data.GetExtent())
    img = vtkImageDataToWxImage(data)
    # w, h = img.GetWidth(), img.GetHeight()
    # if w < 255 or h < 255:
    # 	dh = 255-h
    # 	img.Resize((255, 255),(0, 0), 0,0,0)
    return img, ctf, origData
Exemplo n.º 21
0
    def _buildPipeline(self):
        """Build underlying pipeline and configure rest of pipeline-dependent
        UI. 
        """

        # add the renderer
        self._renderer = vtk.vtkRenderer()
        self._renderer.SetBackground(0.5, 0.5, 0.5)
        self._viewFrame.rwi.GetRenderWindow().AddRenderer(self._renderer)

        self._histogram = vtkdevide.vtkImageHistogram2D()

        # make sure the user can't do anything entirely stupid
        istyle = vtk.vtkInteractorStyleImage()
        self._viewFrame.rwi.SetInteractorStyle(istyle)

        # we'll use this to keep track of our ImagePlaneWidget
        self._ipw = None
        self._overlayipw = None
        self._scalarBarWidget = None

        #
        self._appendPD = vtk.vtkAppendPolyData()

        self._extrude = vtk.vtkLinearExtrusionFilter()
        self._extrude.SetInput(self._appendPD.GetOutput())
        self._extrude.SetScaleFactor(1)
        self._extrude.SetExtrusionTypeToNormalExtrusion()
        self._extrude.SetVector(0, 0, 1)

        self._pdToImageStencil = vtk.vtkPolyDataToImageStencil()
        self._pdToImageStencil.SetInput(self._extrude.GetOutput())

        # stupid trick to make image with all ones, but as large as its
        # input

        self._allOnes = vtk.vtkImageThreshold()
        self._allOnes.ThresholdByLower(0.0)
        self._allOnes.ThresholdByUpper(0.0)
        self._allOnes.SetInValue(1.0)
        self._allOnes.SetOutValue(1.0)
        self._allOnes.SetInput(self._histogram.GetOutput())

        self._stencil = vtk.vtkImageStencil()
        self._stencil.SetInput(self._allOnes.GetOutput())
        # self._stencil.SetStencil(self._pdToImageStencil.GetOutput())
        self._stencil.ReverseStencilOff()
        self._stencil.SetBackgroundValue(0)

        self._lookupAppend = vtk.vtkImageAppendComponents()

        self._lookup = vtkdevide.vtkHistogramLookupTable()
        self._lookup.SetInput1(self._lookupAppend.GetOutput())
        self._lookup.SetInput2(self._stencil.GetOutput())

        module_utils.create_standard_object_introspection(
            self,
            self._viewFrame,
            self._viewFrame.viewFramePanel,
            {"Module (self)": self, "vtkHistogram2D": self._histogram, "vtkRenderer": self._renderer},
            self._renderer.GetRenderWindow(),
        )

        # add the ECASH buttons
        module_utils.create_eoca_buttons(self, self._viewFrame, self._viewFrame.viewFramePanel)
Exemplo n.º 22
0
    def renderFig(self, direction):
        print "cool, it is done"
        fr=gzip.open(self.fname[:-3]+"voxr","rb")
        dataRed=pickle.load(fr)
        self.data_matrix_red=numpy.uint8(dataRed) 
        self.dataImporterR = vtk.vtkImageImport()
        data_string = self.data_matrix_red.tostring()
        self.dataImporterR.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterR.SetDataScalarTypeToUnsignedChar()
        self.dataImporterR.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_red.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterR.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterR.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        
        fg=gzip.open(self.fname[:-3]+"voxg","rb")
        dataGreen=pickle.load(fg)
        self.data_matrix_green=numpy.uint8(dataGreen) 
        self.dataImporterG = vtk.vtkImageImport()
        data_string = self.data_matrix_green.tostring()
        self.dataImporterG.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterG.SetDataScalarTypeToUnsignedChar()
        self.dataImporterG.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_green.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterG.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterG.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        
        fb=gzip.open(self.fname[:-3]+"voxb","rb")
        dataBlue=pickle.load(fb)
        self.data_matrix_blue=numpy.uint8(dataBlue) 
        self.dataImporterB = vtk.vtkImageImport()
        data_string = self.data_matrix_blue.tostring()
        self.dataImporterB.CopyImportVoidPointer(data_string, len(data_string))
        self.dataImporterB.SetDataScalarTypeToUnsignedChar()
        self.dataImporterB.SetNumberOfScalarComponents(1)
        xdim,ydim,zdim=self.data_matrix_blue.shape
        #self.dataImporter.SetDataExtent(0, zdim-1, 0, vtkPiecewiseFunctionb-1, 0, xdim-1)
        self.dataImporterB.SetDataExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        #self.dataImporter.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)
        self.dataImporterB.SetWholeExtent(0, zdim-1, 0, ydim-1, 0, xdim-1)

        """Append the output to VTK"""
        self.append = vtk.vtkImageAppendComponents() 
        self.append.SetInputConnection(self.dataImporterR.GetOutputPort()) 
        self.append.AddInputConnection(self.dataImporterG.GetOutputPort()) 
        self.append.AddInputConnection(self.dataImporterB.GetOutputPort()) 
        self.append.Update() 
        
        """Set the mapper in VTK"""
        # This class describes how the volume is rendered (through ray tracing).
        #compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
        # We can finally create our volume. We also have to specify the data for it, as well as how the data will be rendered.
        #volumeMapper = vtk.vtkVolumeRayCastMapper()
        volumeMapper = vtk.vtkSmartVolumeMapper()
        #volumeMapper.SetVolumeRayCastFunction(compositeFunction)
        #volumeMapper.SetBlendModeToComposite()
        #volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()   
        volumeMapper.SetInputConnection(self.append.GetOutputPort())
        
        """Set the property of the volume"""            
        volumeProperty = vtk.vtkVolumeProperty() 
        volumeProperty.ShadeOff()
        volumeProperty.SetInterpolationTypeToLinear()
        #volumeProperty.SetIndependentComponents(3)
        volumeProperty.IndependentComponentsOn()
        
        """Set the color and opacity of each output"""
        opacityTF1 = vtk.vtkPiecewiseFunction() 
        opacityTF1.AddPoint(   0.0,  0.0 ) 
        opacityTF1.AddPoint(   1.0,  0.33)
        opacityTF1.AddPoint(   128.0, 0.33) 
        opacityTF1.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(0,opacityTF1) 
        
        colourTF1 = vtk.vtkColorTransferFunction() 
        colourTF1.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF1.AddRGBPoint(   1.0,  0.0, 0.0, 0.1 )
        colourTF1.AddRGBPoint(   128.0, 0.0, 0.0, 0.5 ) 
        colourTF1.AddRGBPoint(   255.0, 0.0, 0.0, 1.0 ) 
        volumeProperty.SetColor(0,colourTF1)
        
        opacityTF2 = vtk.vtkPiecewiseFunction() 
        opacityTF2.AddPoint(   0.0,  0.0 ) 
        opacityTF2.AddPoint(   1.0,  0.33 ) 
        opacityTF2.AddPoint(   128.0, 0.33)
        opacityTF2.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(1,opacityTF2) 
        
        colourTF2 = vtk.vtkColorTransferFunction() 
        colourTF2.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF2.AddRGBPoint(   1.0,  0.0, 0.1, 0.0 )
        colourTF2.AddRGBPoint(   128.0, 0.0, 0.5, 0.0 ) 
        colourTF2.AddRGBPoint(   255.0, 0.0, 1.0, 0.0 ) 
        volumeProperty.SetColor(1,colourTF2)
        
        opacityTF3 = vtk.vtkPiecewiseFunction() 
        opacityTF3.AddPoint(   0.0,  0.0 ) 
        opacityTF3.AddPoint(   1.0,  0.33 ) 
        opacityTF3.AddPoint(   128.0, 0.33)
        opacityTF3.AddPoint(   255.0,  0.33 ) 
        volumeProperty.SetScalarOpacity(2,opacityTF3) 
        
        colourTF3 = vtk.vtkColorTransferFunction() 
        colourTF3.AddRGBPoint(   0.0,  0.0, 0.0, 0.0 ) 
        colourTF3.AddRGBPoint(   1.0,  0.1, 0.0, 0.0 )
        colourTF3.AddRGBPoint(   128.0, 0.5, 0.0, 0.0 ) 
        colourTF3.AddRGBPoint(   255.0, 1.0, 0.0, 0.0 ) 
        volumeProperty.SetColor(2,colourTF3)

        #volumeProperty.SetIndependentComponents(4)    
        
        
        #volumeProperty = vtk.vtkVolumeProperty()
        #volprop.SetColor(colourTF)
        #volprop.SetScalarOpacity(alphaChannelFunc)
   
        self.volume.SetMapper(volumeMapper)
        self.volume.SetProperty(volumeProperty)
                    
        self.ren.RemoveActor(self.actor)
                    
        self.ren.AddVolume(self.volume)
        self.ren.SetBackground(1, 1, 1)
            
        self.addPicker()
        # A simple function to be called when the user decides to quit the application.
        def exitCheck(obj, event):
            if obj.GetEventPending() != 0:
                obj.SetAbortRender(1)
                                     
            # Tell the application to use the function as an exit check.
        renderWin = self.vtkWidget.GetRenderWindow()
        renderWin.AddObserver("AbortCheckEvent", exitCheck)
                    
        self.iren.Initialize()
        # Initially pick the cell at this location.
        self.picker.Pick(85, 126, 0, self.ren)
        self.iren.Start()
Exemplo n.º 23
0
    def GetRawDICOMData(self, idtime, outDirectoryID):

        # loop until files are ready to be read in
        realImageFilenames = []
        imagImageFilenames = []
        # FIXME: index fun, slice start from 0, echo start from 1
        for idslice in range(self.nslice):
            for idecho in range(1, self.NumberEcho + 1):
                realImageFilenames.append(
                    self.QueryDictionary(idtime, idecho, idslice, 2))
                imagImageFilenames.append(
                    self.QueryDictionary(idtime, idecho, idslice, 3))

        #create local vars
        rootdir = self.dataDirectory
        dim = self.dimensions
        real_array = numpy.zeros(self.FullSize, dtype=numpy.float32)
        imag_array = numpy.zeros(self.FullSize, dtype=numpy.float32)

        vtkAppendReal = vtk.vtkImageAppendComponents()
        vtkAppendImag = vtk.vtkImageAppendComponents()

        for idEchoLoc, (fileNameReal, fileNameImag) in enumerate(
                zip(realImageFilenames, imagImageFilenames)):
            # FIXME: index nightmare
            # FIXME: will be wrong for different ordering
            # arrange such that echo varies fast then x, then y, then z
            # example of how slicing behaves
            #>>> x = range(100)
            #>>> x
            #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
            #>>> x[0:100:10]
            #[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
            #>>> x[1:100:10]
            #[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
            #>>> x[2:100:10]
            #[2, 12, 22, 32, 42, 52, 62, 72, 82, 92]
            #>>> x[3:100:10]
            #[3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
            idEcho = idEchoLoc % dim[3]
            idSlice = idEchoLoc / dim[3]
            beginIndex = dim[0] * dim[1] * dim[3] * idSlice + idEcho
            finalIndex = dim[0] * dim[1] * dim[3] * (idSlice + 1)
            stepIndex = dim[3]

            ## realds = dicom.read_file( "%s/%s"%(rootdir,fileNameReal) )
            ## imagds = dicom.read_file( "%s/%s"%(rootdir,fileNameImag) )
            ## realsliceID = int( round((float(realds.SliceLocation) - float(realds[0x0019,0x1019].value))/ realds.SliceThickness))
            ## imagsliceID = int( round((float(imagds.SliceLocation) - float(imagds[0x0019,0x1019].value))/ imagds.SliceThickness))

            ## print "%03d echo %03d slice %03d slice [%d:%d:%d] %03d %s %03d %s "% (idEchoLoc,idEcho,idSlice,beginIndex,finalIndex,stepIndex,realsliceID,fileNameReal,imagsliceID,fileNameImag )

            vtkRealDcmReader = vtk.vtkDICOMImageReader()
            vtkRealDcmReader.SetFileName("%s/%s" % (rootdir, fileNameReal))
            vtkRealDcmReader.Update()
            vtkRealData = vtk.vtkImageCast()
            vtkRealData.SetOutputScalarTypeToFloat()
            vtkRealData.SetInput(vtkRealDcmReader.GetOutput())
            vtkRealData.Update()
            real_image = vtkRealData.GetOutput().GetPointData()
            real_array[
                beginIndex:finalIndex:stepIndex] = vtkNumPy.vtk_to_numpy(
                    real_image.GetArray(0))

            vtkImagDcmReader = vtk.vtkDICOMImageReader()
            vtkImagDcmReader.SetFileName("%s/%s" % (rootdir, fileNameImag))
            vtkImagDcmReader.Update()
            vtkImagData = vtk.vtkImageCast()
            vtkImagData.SetOutputScalarTypeToFloat()
            vtkImagData.SetInput(vtkImagDcmReader.GetOutput())
            vtkImagData.Update()
            imag_image = vtkImagData.GetOutput().GetPointData()
            imag_array[
                beginIndex:finalIndex:stepIndex] = vtkNumPy.vtk_to_numpy(
                    imag_image.GetArray(0))

            vtkAppendReal.SetInput(idEchoLoc, vtkRealDcmReader.GetOutput())
            vtkAppendImag.SetInput(idEchoLoc, vtkImagDcmReader.GetOutput())
            vtkAppendReal.Update()
            vtkAppendImag.Update()

        vtkRealDcmWriter = vtk.vtkDataSetWriter()
        vtkRealDcmWriter.SetFileName("Processed/%s/realrawdata.%04d.vtk" %
                                     (outDirectoryID, idtime))
        vtkRealDcmWriter.SetInput(vtkAppendReal.GetOutput())
        vtkRealDcmWriter.Update()

        vtkImagDcmWriter = vtk.vtkDataSetWriter()
        vtkImagDcmWriter.SetFileName("Processed/%s/imagrawdata.%04d.vtk" %
                                     (outDirectoryID, idtime))
        vtkImagDcmWriter.SetInput(vtkAppendImag.GetOutput())
        vtkImagDcmWriter.Update()

        # write numpy to disk in matlab
        echoTimes = []
        for idecho in range(1, self.NumberEcho + 1):
            localKey = self.keyTemplate % (idtime, idecho, 0, 2)
            echoTimes.append(self.DicomDataDictionary[localKey][1])
        scipyio.savemat(
            "Processed/%s/rawdata.%04d.mat" % (outDirectoryID, idtime), {
                'dimensions': dim,
                'echoTimes': echoTimes,
                'real': real_array,
                'imag': imag_array
            })

        # end GetRawDICOMData
        return (real_array, imag_array)
Exemplo n.º 24
0
def scatterPlot(imagedata1,
                imagedata2,
                z,
                countVoxels=True,
                wholeVolume=True,
                logarithmic=True,
                bitDepth=8):
    """
	Create scatterplot
	"""
    imagedata1.SetUpdateExtent(imagedata1.GetWholeExtent())
    imagedata2.SetUpdateExtent(imagedata1.GetWholeExtent())

    imagedata1.Update()
    imagedata2.Update()
    range1 = imagedata1.GetScalarRange()
    range2 = imagedata2.GetScalarRange()

    n = 255
    #n = min(max(sc1max,sc2max),255)
    #d = (n+1) / float(2**bitDepth)
    if bitDepth is None:
        spacing1 = float(abs(range1[1] - range1[0])) / (n + 1)
        spacing2 = float(abs(range2[1] - range2[0])) / (n + 1)
    else:
        spacing1 = float(2**bitDepth) / (n + 1)
        spacing2 = float(2**bitDepth) / (n + 1)

    app = vtk.vtkImageAppendComponents()
    app.AddInput(imagedata1)
    app.AddInput(imagedata2)

    #shiftscale = vtk.vtkImageShiftScale()
    #shiftscale.SetOutputScalarTypeToUnsignedChar()
    #shiftscale.SetScale(d)
    #shiftscale.SetInputConnection(app.GetOutputPort())

    acc = vtk.vtkImageAccumulate()
    acc.SetComponentExtent(0, n, 0, n, 0, 0)
    acc.SetComponentOrigin(range1[0], range2[0], 0)
    acc.SetComponentSpacing(spacing1, spacing2, 0)
    #acc.SetInputConnection(shiftscale.GetOutputPort())
    acc.SetInputConnection(app.GetOutputPort())
    acc.Update()

    data = acc.GetOutput()
    origData = data

    originalRange = data.GetScalarRange()

    if logarithmic:
        Logging.info("Scaling scatterplot logarithmically", kw="imageop")
        logscale = vtk.vtkImageLogarithmicScale()
        logscale.SetInputConnection(acc.GetOutputPort())
        logscale.Update()
        data = logscale.GetOutput()

    x0, x1 = data.GetScalarRange()
    if countVoxels:
        Logging.info("Scalar range of scatterplot = ", x0, x1, kw="imageop")
        ctf = fire(x0, x1)
        ctf = equalize(data, ctf, x1)
        maptocolor = vtk.vtkImageMapToColors()
        maptocolor.SetInputConnection(data.GetProducerPort())
        maptocolor.SetLookupTable(ctf)
        maptocolor.SetOutputFormatToRGB()
        maptocolor.Update()
        data = maptocolor.GetOutput()
        ctf.originalRange = originalRange

    Logging.info("Scatterplot has dimensions: ",
                 data.GetDimensions(),
                 data.GetExtent(),
                 kw="imageop")
    data.SetWholeExtent(data.GetExtent())
    img = vtkImageDataToWxImage(data)
    #w, h = img.GetWidth(), img.GetHeight()
    #if w < 255 or h < 255:
    #	dh = 255-h
    #	img.Resize((255, 255),(0, 0), 0,0,0)
    return img, ctf, origData
Exemplo n.º 25
0
# 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()
Exemplo n.º 26
0
def VTKImageTransform(x,dx,dy,numret=False,reverse=False,origsize=None,
      cubic=False,interp=True,scalex=1,scaley=1,constant=0,wrap=False,
      mirror=False):

      maxdx = max([int(max(abs(dx.ravel()))+1),(dx.shape[1]-x.shape[1])])
      maxdy = max([int(max(abs(dy.ravel()))+1),(dx.shape[0]-x.shape[0])])
      dx = dx.astype(np.float32)
      dy = dy.astype(np.float32)
      if scalex > 1:
         xx = np.arange(x.shape[1])
         dx = (xx[np.newaxis,::]+dx).astype(np.float32)
         dy = VTKGrowN(dy,scalex,1,numret=True)
         dx = VTKGrowN(dx,scalex,1,numret=True)
         dx = (dx-np.arange(scalex*x.shape[1])[np.newaxis,::]).\
               astype(np.float32)
      if scaley > 1:
         yy = np.arange(x.shape[0])
         dy = (yy[::,np.newaxis]+dy).astype(np.float32)
         dy = VTKGrowN(dy,1,scaley,numret=True)
         dx = VTKGrowN(dx,1,scaley,numret=True)
         dy = (dy-np.arange(scaley*x.shape[0])[::,np.newaxis]).\
               astype(np.float32)
      if type(x) == np.ndarray: i = NumToVTKImage(x)
      else: i = x
      if type(dx) == np.ndarray: tx = NumToVTKImage(dx)
      else: tx = dx
      if type(dy) == np.ndarray: ty = NumToVTKImage(dy)
      else: ty = dy
      dm = ty.GetDimensions()
      dz = np.zeros(dy.shape,dy.dtype)
      tz = NumToVTKImage(dz)
      a = vtk.vtkImageAppendComponents()
      a.AddInputData(tx)
      a.AddInputData(ty)
      a.AddInputData(tz)
      a.Update()
      t = a.GetOutput()
      r = vtk.vtkGridTransform()
      r.SetDisplacementGridData(t)
      r.Update()
      s = vtk.vtkImageReslice()
      s.WrapOff()
      s.MirrorOn()
      if interp:
         s.InterpolateOn()
         if cubic: s.SetInterpolationModeToCubic()
         else: s.SetInterpolationModeToLinear()
      s.SetOutputDimensionality(2)
      if reverse:
         r.SetInterpolationModeToLinear()
         r.SetInverseTolerance(0.001)
         r.SetInverseIterations(1000)
         r.DebugOff()
         ir = r.GetInverse()
         ir.SetInterpolationModeToLinear()
         ir.SetInverseTolerance(0.001)
         ir.SetInverseIterations(1000)
         ir.GlobalWarningDisplayOff()
         s.SetResliceTransform(ir)
         s.AutoCropOutputOff()
         if origsize: s.SetOutputExtent(0,origsize[1]-1,0,origsize[0]-1,0,0)
         else: s.SetOutputExtent(0,scalex*dm[0]-1,0,scaley*dm[1]-1,0,0)
      else:
         r.SetInterpolationModeToCubic()
         r.SetInverseTolerance(0.001)
         r.SetInverseIterations(1000)
         r.GlobalWarningDisplayOff()
         s.SetOutputExtent(0,scalex*dm[0]-1,0,scaley*dm[1]-1,0,0)
         s.AutoCropOutputOff()
         s.SetResliceTransform(r)
      if mirror: ip = vtk.vtkImageMirrorPad()
      elif wrap: ip = vtk.vtkImageWrapPad()
      else: ip = vtk.vtkImageConstantPad(); ip.SetConstant(constant)
      ip.SetOutputWholeExtent(0-maxdx,dm[0]-1+maxdx,0-maxdy,dm[1]-1+maxdy,0,0)
      ip.SetInputData(i)
      ip.Update()
      s.SetInputData(ip.GetOutput())
      o=s.GetOutput()
      s.Update()
      if numret: ri = VTKImageToNum(o)
      else: ri = o
      return ri
    def __init__(self, ren, renWin, iren):
        self.ren = ren
        self.renWin = renWin
        self.iren = iren

        # Create a gaussian
        gs = vtk.vtkImageGaussianSource()
        gs.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs.SetMaximum(255.0)
        gs.SetStandardDeviation(5)
        gs.SetCenter(15, 15, 15)

        # threshold to leave a gap that should show up for
        # gradient opacity
        t = vtk.vtkImageThreshold()
        t.SetInputConnection(gs.GetOutputPort())
        t.ReplaceInOn()
        t.SetInValue(0)
        t.ThresholdBetween(150, 200)

        # Use a shift scale to convert to unsigned char
        ss = vtk.vtkImageShiftScale()
        ss.SetInputConnection(t.GetOutputPort())
        ss.SetOutputScalarTypeToUnsignedChar()

        # grid will be used for two component dependent
        grid0 = vtk.vtkImageGridSource()
        grid0.SetDataScalarTypeToUnsignedChar()
        grid0.SetGridSpacing(10, 10, 10)
        grid0.SetLineValue(200)
        grid0.SetFillValue(10)
        grid0.SetDataExtent(0, 30, 0, 30, 0, 30)

        # use dilation to thicken the grid
        d = vtk.vtkImageContinuousDilate3D()
        d.SetInputConnection(grid0.GetOutputPort())
        d.SetKernelSize(3, 3, 3)

        # Now make a two component dependent
        iac = vtk.vtkImageAppendComponents()
        iac.AddInputConnection(d.GetOutputPort())
        iac.AddInputConnection(ss.GetOutputPort())

        # Some more gaussians for the four component indepent case
        gs1 = vtk.vtkImageGaussianSource()
        gs1.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs1.SetMaximum(255.0)
        gs1.SetStandardDeviation(4)
        gs1.SetCenter(5, 5, 5)

        t1 = vtk.vtkImageThreshold()
        t1.SetInputConnection(gs1.GetOutputPort())
        t1.ReplaceInOn()
        t1.SetInValue(0)
        t1.ThresholdBetween(150, 256)

        gs2 = vtk.vtkImageGaussianSource()
        gs2.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs2.SetMaximum(255.0)
        gs2.SetStandardDeviation(4)
        gs2.SetCenter(12, 12, 12)

        gs3 = vtk.vtkImageGaussianSource()
        gs3.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs3.SetMaximum(255.0)
        gs3.SetStandardDeviation(4)
        gs3.SetCenter(19, 19, 19)

        t3 = vtk.vtkImageThreshold()
        t3.SetInputConnection(gs3.GetOutputPort())
        t3.ReplaceInOn()
        t3.SetInValue(0)
        t3.ThresholdBetween(150, 256)

        gs4 = vtk.vtkImageGaussianSource()
        gs4.SetWholeExtent(0, 30, 0, 30, 0, 30)
        gs4.SetMaximum(255.0)
        gs4.SetStandardDeviation(4)
        gs4.SetCenter(26, 26, 26)

        # we need a few append filters ...
        iac1 = vtk.vtkImageAppendComponents()
        iac1.AddInputConnection(t1.GetOutputPort())
        iac1.AddInputConnection(gs2.GetOutputPort())

        iac2 = vtk.vtkImageAppendComponents()
        iac2.AddInputConnection(iac1.GetOutputPort())
        iac2.AddInputConnection(t3.GetOutputPort())

        iac3 = vtk.vtkImageAppendComponents()
        iac3.AddInputConnection(iac2.GetOutputPort())
        iac3.AddInputConnection(gs4.GetOutputPort())

        # create the four component dependent -
        # use lines in x, y, z for colors
        gridR = vtk.vtkImageGridSource()
        gridR.SetDataScalarTypeToUnsignedChar()
        gridR.SetGridSpacing(10, 100, 100)
        gridR.SetLineValue(250)
        gridR.SetFillValue(100)
        gridR.SetDataExtent(0, 30, 0, 30, 0, 30)

        dR = vtk.vtkImageContinuousDilate3D()
        dR.SetInputConnection(gridR.GetOutputPort())
        dR.SetKernelSize(2, 2, 2)

        gridG = vtk.vtkImageGridSource()
        gridG.SetDataScalarTypeToUnsignedChar()
        gridG.SetGridSpacing(100, 10, 100)
        gridG.SetLineValue(250)
        gridG.SetFillValue(100)
        gridG.SetDataExtent(0, 30, 0, 30, 0, 30)

        dG = vtk.vtkImageContinuousDilate3D()
        dG.SetInputConnection(gridG.GetOutputPort())
        dG.SetKernelSize(2, 2, 2)

        gridB = vtk.vtkImageGridSource()
        gridB.SetDataScalarTypeToUnsignedChar()
        gridB.SetGridSpacing(100, 100, 10)
        gridB.SetLineValue(0)
        gridB.SetFillValue(250)
        gridB.SetDataExtent(0, 30, 0, 30, 0, 30)

        dB = vtk.vtkImageContinuousDilate3D()
        dB.SetInputConnection(gridB.GetOutputPort())
        dB.SetKernelSize(2, 2, 2)

        # need some appending
        iacRG = vtk.vtkImageAppendComponents()
        iacRG.AddInputConnection(dR.GetOutputPort())
        iacRG.AddInputConnection(dG.GetOutputPort())

        iacRGB = vtk.vtkImageAppendComponents()
        iacRGB.AddInputConnection(iacRG.GetOutputPort())
        iacRGB.AddInputConnection(dB.GetOutputPort())

        iacRGBA = vtk.vtkImageAppendComponents()
        iacRGBA.AddInputConnection(iacRGB.GetOutputPort())
        iacRGBA.AddInputConnection(ss.GetOutputPort())

        # We need a bunch of opacity functions

        # this one is a simple ramp to .2
        rampPoint2 = vtk.vtkPiecewiseFunction()
        rampPoint2.AddPoint(0, 0.0)
        rampPoint2.AddPoint(255, 0.2)

        # this one is a simple ramp to 1
        ramp1 = vtk.vtkPiecewiseFunction()
        ramp1.AddPoint(0, 0.0)
        ramp1.AddPoint(255, 1.0)

        # this one shows a sharp surface
        surface = vtk.vtkPiecewiseFunction()
        surface.AddPoint(0, 0.0)
        surface.AddPoint(10, 0.0)
        surface.AddPoint(50, 1.0)
        surface.AddPoint(255, 1.0)

        # this one is constant 1
        constant1 = vtk.vtkPiecewiseFunction()
        constant1.AddPoint(0, 1.0)
        constant1.AddPoint(255, 1.0)

        # this one is used for gradient opacity
        gop = vtk.vtkPiecewiseFunction()
        gop.AddPoint(0, 0.0)
        gop.AddPoint(20, 0.0)
        gop.AddPoint(60, 1.0)
        gop.AddPoint(255, 1.0)

        # We need a bunch of color functions

        # This one is a simple rainbow
        rainbow = vtk.vtkColorTransferFunction()
        rainbow.SetColorSpaceToHSV()
        rainbow.HSVWrapOff()
        rainbow.AddHSVPoint(0, 0.1, 1.0, 1.0)
        rainbow.AddHSVPoint(255, 0.9, 1.0, 1.0)

        # this is constant red
        red = vtk.vtkColorTransferFunction()
        red.AddRGBPoint(0, 1, 0, 0)
        red.AddRGBPoint(255, 1, 0, 0)

        # this is constant green
        green = vtk.vtkColorTransferFunction()
        green.AddRGBPoint(0, 0, 1, 0)
        green.AddRGBPoint(255, 0, 1, 0)

        # this is constant blue
        blue = vtk.vtkColorTransferFunction()
        blue.AddRGBPoint(0, 0, 0, 1)
        blue.AddRGBPoint(255, 0, 0, 1)

        # this is constant yellow
        yellow = vtk.vtkColorTransferFunction()
        yellow.AddRGBPoint(0, 1, 1, 0)
        yellow.AddRGBPoint(255, 1, 1, 0)

        #ren = vtk.vtkRenderer()
        #renWin = vtk.vtkRenderWindow()
        self.renWin.AddRenderer(self.ren)
        self.renWin.SetSize(500, 500)
        #iren = vtk.vtkRenderWindowInteractor()
        self.iren.SetRenderWindow(self.renWin)

        self.ren.GetCullers().InitTraversal()
        culler = self.ren.GetCullers().GetNextItem()
        culler.SetSortingStyleToBackToFront()

        # We need 25 mapper / actor pairs which we will render
        # in a grid. Going down we will vary the input data
        # with the top row unsigned char, then float, then
        # two dependent components, then four dependent components
        # then four independent components. Going across we
        # will vary the rendering method with MIP, Composite,
        # Composite Shade, Composite GO, and Composite GO Shade.

        # Create the 5 by 5 grids
        self.volumeProperty = [[0 for col in range(0, 5)]
                               for row in range(0, 5)]
        self.volumeMapper = [[0 for col in range(0, 5)] for row in range(0, 5)]
        volume = [[0 for col in range(0, 5)] for row in range(0, 5)]

        for i in range(0, 5):
            for j in range(0, 5):

                self.volumeProperty[i][j] = vtk.vtkVolumeProperty()
                self.volumeMapper[i][j] = vtk.vtkFixedPointVolumeRayCastMapper(
                )
                self.volumeMapper[i][j].SetSampleDistance(0.25)
                self.volumeMapper[i][j].SetNumberOfThreads(1)

                volume[i][j] = vtk.vtkVolume()
                volume[i][j].SetMapper(self.volumeMapper[i][j])
                volume[i][j].SetProperty(self.volumeProperty[i][j])

                volume[i][j].AddPosition(i * 30, j * 30, 0)

                self.ren.AddVolume(volume[i][j])

        for i in range(0, 5):

            self.volumeMapper[0][i].SetInputConnection(t.GetOutputPort())
            self.volumeMapper[1][i].SetInputConnection(ss.GetOutputPort())
            self.volumeMapper[2][i].SetInputConnection(iac.GetOutputPort())
            self.volumeMapper[3][i].SetInputConnection(iac3.GetOutputPort())
            self.volumeMapper[4][i].SetInputConnection(iacRGBA.GetOutputPort())

            self.volumeMapper[i][0].SetBlendModeToMaximumIntensity()
            self.volumeMapper[i][1].SetBlendModeToComposite()
            self.volumeMapper[i][2].SetBlendModeToComposite()
            self.volumeMapper[i][3].SetBlendModeToComposite()
            self.volumeMapper[i][4].SetBlendModeToComposite()

            self.volumeProperty[0][i].IndependentComponentsOn()
            self.volumeProperty[1][i].IndependentComponentsOn()
            self.volumeProperty[2][i].IndependentComponentsOff()
            self.volumeProperty[3][i].IndependentComponentsOn()
            self.volumeProperty[4][i].IndependentComponentsOff()

            self.volumeProperty[0][i].SetColor(rainbow)
            self.volumeProperty[0][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[0][i].SetGradientOpacity(constant1)

            self.volumeProperty[1][i].SetColor(rainbow)
            self.volumeProperty[1][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[1][i].SetGradientOpacity(constant1)

            self.volumeProperty[2][i].SetColor(rainbow)
            self.volumeProperty[2][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[2][i].SetGradientOpacity(constant1)

            self.volumeProperty[3][i].SetColor(0, red)
            self.volumeProperty[3][i].SetColor(1, green)
            self.volumeProperty[3][i].SetColor(2, blue)
            self.volumeProperty[3][i].SetColor(3, yellow)
            self.volumeProperty[3][i].SetScalarOpacity(0, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(1, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(2, rampPoint2)
            self.volumeProperty[3][i].SetScalarOpacity(3, rampPoint2)
            self.volumeProperty[3][i].SetGradientOpacity(0, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(1, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(2, constant1)
            self.volumeProperty[3][i].SetGradientOpacity(3, constant1)
            self.volumeProperty[3][i].SetComponentWeight(0, 1)
            self.volumeProperty[3][i].SetComponentWeight(1, 1)
            self.volumeProperty[3][i].SetComponentWeight(2, 1)
            self.volumeProperty[3][i].SetComponentWeight(3, 1)

            self.volumeProperty[4][i].SetColor(rainbow)
            self.volumeProperty[4][i].SetScalarOpacity(rampPoint2)
            self.volumeProperty[4][i].SetGradientOpacity(constant1)

            self.volumeProperty[i][2].ShadeOn()
            self.volumeProperty[i][4].ShadeOn(0)
            self.volumeProperty[i][4].ShadeOn(1)
            self.volumeProperty[i][4].ShadeOn(2)
            self.volumeProperty[i][4].ShadeOn(3)

        self.volumeProperty[0][0].SetScalarOpacity(ramp1)
        self.volumeProperty[1][0].SetScalarOpacity(ramp1)
        self.volumeProperty[2][0].SetScalarOpacity(ramp1)
        self.volumeProperty[3][0].SetScalarOpacity(0, surface)
        self.volumeProperty[3][0].SetScalarOpacity(1, surface)
        self.volumeProperty[3][0].SetScalarOpacity(2, surface)
        self.volumeProperty[3][0].SetScalarOpacity(3, surface)
        self.volumeProperty[4][0].SetScalarOpacity(ramp1)

        self.volumeProperty[0][2].SetScalarOpacity(surface)
        self.volumeProperty[1][2].SetScalarOpacity(surface)
        self.volumeProperty[2][2].SetScalarOpacity(surface)
        self.volumeProperty[3][2].SetScalarOpacity(0, surface)
        self.volumeProperty[3][2].SetScalarOpacity(1, surface)
        self.volumeProperty[3][2].SetScalarOpacity(2, surface)
        self.volumeProperty[3][2].SetScalarOpacity(3, surface)
        self.volumeProperty[4][2].SetScalarOpacity(surface)

        self.volumeProperty[0][4].SetScalarOpacity(surface)
        self.volumeProperty[1][4].SetScalarOpacity(surface)
        self.volumeProperty[2][4].SetScalarOpacity(surface)
        self.volumeProperty[3][4].SetScalarOpacity(0, surface)
        self.volumeProperty[3][4].SetScalarOpacity(1, surface)
        self.volumeProperty[3][4].SetScalarOpacity(2, surface)
        self.volumeProperty[3][4].SetScalarOpacity(3, surface)
        self.volumeProperty[4][4].SetScalarOpacity(surface)

        self.volumeProperty[0][3].SetGradientOpacity(gop)
        self.volumeProperty[1][3].SetGradientOpacity(gop)
        self.volumeProperty[2][3].SetGradientOpacity(gop)
        self.volumeProperty[3][3].SetGradientOpacity(0, gop)
        self.volumeProperty[3][3].SetGradientOpacity(2, gop)
        self.volumeProperty[4][3].SetGradientOpacity(gop)

        self.volumeProperty[3][3].SetScalarOpacity(0, ramp1)
        self.volumeProperty[3][3].SetScalarOpacity(2, ramp1)

        self.volumeProperty[0][4].SetGradientOpacity(gop)
        self.volumeProperty[1][4].SetGradientOpacity(gop)
        self.volumeProperty[2][4].SetGradientOpacity(gop)
        self.volumeProperty[3][4].SetGradientOpacity(0, gop)
        self.volumeProperty[3][4].SetGradientOpacity(2, gop)
        self.volumeProperty[4][4].SetGradientOpacity(gop)

        self.renWin.Render()

        self.ren.GetActiveCamera().Dolly(1.3)
        self.ren.GetActiveCamera().Azimuth(15)
        self.ren.GetActiveCamera().Elevation(5)
        self.ren.ResetCameraClippingRange()
  def GetRawDICOMData(self,idtime,outDirectoryID):
    
    # loop until files are ready to be read in
    realImageFilenames = []
    imagImageFilenames = []
    # FIXME: index fun, slice start from 0, echo start from 1
    for idslice in range(self.nslice):
      for idecho in range(1,self.NumberEcho+1):
        realImageFilenames.append( self.QueryDictionary( idtime,idecho,idslice,2 ) )  
        imagImageFilenames.append( self.QueryDictionary( idtime,idecho,idslice,3 ) )  
  
    #create local vars
    rootdir = self.dataDirectory
    RawDim  = self.RawDimensions
    real_array=numpy.zeros(self.FullSizeRaw,dtype=numpy.float32)
    imag_array=numpy.zeros(self.FullSizeRaw,dtype=numpy.float32) 

    vtkAppendReal = vtk.vtkImageAppendComponents()
    vtkAppendImag = vtk.vtkImageAppendComponents()

    for idEchoLoc,(fileNameReal,fileNameImag) in enumerate(zip(realImageFilenames,imagImageFilenames)):
      # FIXME: index nightmare
      # FIXME: will be wrong for different ordering
      # arrange such that echo varies fast then x, then y, then z
      # example of how slicing behaves
      #>>> x = range(100)
      #>>> x
      #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
      #>>> x[0:100:10]
      #[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
      #>>> x[1:100:10]
      #[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
      #>>> x[2:100:10]
      #[2, 12, 22, 32, 42, 52, 62, 72, 82, 92]
      #>>> x[3:100:10]
      #[3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
      idEcho  = idEchoLoc % RawDim[3]
      idSlice = idEchoLoc / RawDim[3]
      beginIndex = RawDim[0]*RawDim[1]*RawDim[3]* idSlice   +idEcho
      finalIndex = RawDim[0]*RawDim[1]*RawDim[3]*(idSlice+1)
      stepIndex  = RawDim[3]
  
      ## realds = dicom.read_file( "%s/%s"%(rootdir,fileNameReal) )
      ## imagds = dicom.read_file( "%s/%s"%(rootdir,fileNameImag) )
      ## realsliceID = int( round((float(realds.SliceLocation) - float(realds[0x0019,0x1019].value))/ realds.SliceThickness))
      ## imagsliceID = int( round((float(imagds.SliceLocation) - float(imagds[0x0019,0x1019].value))/ imagds.SliceThickness))
  
      ## print "%03d echo %03d slice %03d slice [%d:%d:%d] %03d %s %03d %s "% (idEchoLoc,idEcho,idSlice,beginIndex,finalIndex,stepIndex,realsliceID,fileNameReal,imagsliceID,fileNameImag )
  
      vtkRealDcmReader = vtk.vtkDICOMImageReader()
      vtkRealDcmReader.SetFileName("%s/%s"%(rootdir,fileNameReal) )
      vtkRealDcmReader.Update()
      vtkRealData = vtk.vtkImageCast()
      vtkRealData.SetOutputScalarTypeToFloat()
      vtkRealData.SetInput( vtkRealDcmReader.GetOutput() )
      vtkRealData.Update( )
      real_image = vtkRealData.GetOutput().GetPointData() 
      real_array[ beginIndex: finalIndex : stepIndex ] = vtkNumPy.vtk_to_numpy(real_image.GetArray(0)) 
  
      vtkImagDcmReader = vtk.vtkDICOMImageReader()
      vtkImagDcmReader.SetFileName("%s/%s"%(rootdir,fileNameImag) )
      vtkImagDcmReader.Update()
      vtkImagData = vtk.vtkImageCast()
      vtkImagData.SetOutputScalarTypeToFloat()
      vtkImagData.SetInput( vtkImagDcmReader.GetOutput() )
      vtkImagData.Update( )
      imag_image = vtkImagData.GetOutput().GetPointData() 
      imag_array[ beginIndex: finalIndex : stepIndex ] = vtkNumPy.vtk_to_numpy(imag_image.GetArray(0)) 
  
      vtkAppendReal.SetInput( idEchoLoc ,vtkRealDcmReader.GetOutput() )
      vtkAppendImag.SetInput( idEchoLoc ,vtkImagDcmReader.GetOutput() )
      vtkAppendReal.Update( )
      vtkAppendImag.Update( )
    if (SetFalseToReduceFileSystemUsage):
      vtkRealDcmWriter = vtk.vtkDataSetWriter()
      vtkRealDcmWriter.SetFileName("Processed/%s/realrawdata.%04d.vtk" % (outDirectoryID,idtime) )
      vtkRealDcmWriter.SetInput(vtkAppendReal.GetOutput())
      vtkRealDcmWriter.Update()
  
    if (SetFalseToReduceFileSystemUsage):
      vtkImagDcmWriter = vtk.vtkDataSetWriter()
      vtkImagDcmWriter.SetFileName("Processed/%s/imagrawdata.%04d.vtk" % (outDirectoryID,idtime) )
      vtkImagDcmWriter.SetInput(vtkAppendImag.GetOutput())
      vtkImagDcmWriter.Update()
  
    # write numpy to disk in matlab
    echoTimes = []
    for idecho in range(1,self.NumberEcho+1):
       localKey = self.keyTemplate % ( idtime,idecho,0,2 )
       echoTimes.append(self.DicomDataDictionary[localKey][1])
    if (SetFalseToReduceFileSystemUsage):
      scipyio.savemat("Processed/%s/rawdata.%04d.mat"%(outDirectoryID,idtime), {'dimensions':RawDim,'echoTimes':echoTimes,'real':real_array,'imag':imag_array})
  
    # end GetRawDICOMData
    return ((real_array,imag_array),echoTimes)
Exemplo n.º 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()
Exemplo n.º 30
0
# component is a constant, the mapper decides the whole thing is
# translucent.  Our trick around this is to set the padding voxels to
# have a value of 255 in the alpha channel, representing total
# transparency while the rest of the fourth channel is set to be
# totally opaque, until we decide to mess with it.
ellipsoid.SetInValue(100)
ellipsoid.SetOutValue(255)

# Testing if a smoothly varying translucency works.  Seems to, to an extent.
smoother = vtk.vtkImageGaussianSmooth()
smoother.SetInput(ellipsoid.GetOutput())
smoother.SetRadiusFactors(50, 50, 50)
smoother.SetStandardDeviation(5, 5, 5)
smoother.SetDimensionality(3)

appender = vtk.vtkImageAppendComponents()
appender.AddInput(image)
#appender.AddInput(extractor.GetOutput())
#appender.AddInput(ellipsoid.GetOutput())
appender.AddInput(smoother.GetOutput())
image4comp = appender.GetOutput()
image4comp.Update()
#image4comp = imagepadded

# when we fill the fourth component "IndependentComponentsOff"
# rendering no longer works. On the other hand, we can't get opacity
# to work at all with "IndependentComponentsOn"
image4comp.GetPointData().GetScalars().FillComponent(3, 0)

print image4comp.GetScalarComponentAsFloat(50, 50, 50, 3)
print image4comp.GetScalarComponentAsFloat(5, 5, 5, 3)
Exemplo n.º 31
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()
Exemplo n.º 32
0
# 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())

# create pseudo alpha values for background
bmask = vtk.vtkImageCanvasSource2D()
bmask.SetScalarTypeToUnsignedChar()
bmask.SetNumberOfScalarComponents(1)
bmask.SetExtent(0, 127, 0, 127, 0, 0)
bmask.SetDrawColor(0, 0, 0, 0)
bmask.FillBox(0, 127, 0, 127)
bmask.SetDrawColor(255, 0, 0, 0)