def keypressCallback(obj, ev): key = obj.GetKeySym() if key == "s": filter.Modified() filter.SetInputBufferTypeToZBuffer() filter.Update() scale = vtk.vtkImageShiftScale() scale.SetOutputScalarTypeToUnsignedChar() scale.SetInputConnection(filter.GetOutputPort()) scale.SetShift(0) scale.SetScale(-300) scale2 = vtk.vtkImageShiftScale() scale2.SetOutputScalarTypeToUnsignedChar() scale2.SetInputConnection(scale.GetOutputPort()) scale2.SetShift(255) global iteration iteration = iteration + 1 file_name = "/home/vishnusanjay/cmpt764/Final project/last_examples/depthimages_1/chair_" + \ str(iteration) + ".bmp" imageWriter = vtk.vtkBMPWriter() imageWriter.SetFileName(file_name) imageWriter.SetInputConnection(scale2.GetOutputPort()) imageWriter.Write()
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.MapRanges: if self.InputRange == [0.0, 0.0]: self.InputRange = self.Image.GetScalarRange() if self.InputRange[1] == self.InputRange[0]: self.PrintError( 'Error: Input range has zero width. Cannot map values') self.Shift = -self.InputRange[0] self.Scale = (self.OutputRange[1] - self.OutputRange[0]) / ( self.InputRange[1] - self.InputRange[0]) shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputData(self.Image) shiftScale.SetShift(self.Shift) shiftScale.SetScale(self.Scale) if self.OutputType == 'double': shiftScale.SetOutputScalarTypeToDouble() elif self.OutputType == 'uchar': shiftScale.SetOutputScalarTypeToUnsignedChar() elif self.OutputType == 'char': shiftScale.SetOutputScalarTypeToChar() elif self.OutputType == 'ushort': shiftScale.SetOutputScalarTypeToUnsignedShort() elif self.OutputType == 'short': shiftScale.SetOutputScalarTypeToShort() elif self.OutputType == 'ulong': shiftScale.SetOutputScalarTypeToUnsignedLong() elif self.OutputType == 'long': shiftScale.SetOutputScalarTypeToLong() elif self.OutputType == 'uint': shiftScale.SetOutputScalarTypeToUnsignedInt() elif self.OutputType == 'int': shiftScale.SetOutputScalarTypeToInt() elif self.OutputType == 'float': shiftScale.SetOutputScalarTypeToFloat() if self.OutputType != 'unchanged': if self.ClampOverflowOn: shiftScale.ClampOverflowOn() shiftScale.ClampOverflowOff() shiftScale.Update() self.Image = shiftScale.GetOutput() if self.MapRanges and self.OutputRange[0] != 0.0: shiftScale2 = vtk.vtkImageShiftScale() shiftScale2.SetInputData(self.Image) shiftScale2.SetShift(self.OutputRange[0]) shiftScale2.SetScale(1.0) shiftScale2.Update() self.Image = shiftScale2.GetOutput()
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.MapRanges: if self.InputRange == [0.0,0.0]: self.InputRange = self.Image.GetScalarRange() if self.InputRange[1] == self.InputRange[0]: self.PrintError('Error: Input range has zero width. Cannot map values') self.Shift = -self.InputRange[0] self.Scale = (self.OutputRange[1] - self.OutputRange[0]) / (self.InputRange[1] - self.InputRange[0]) shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInput(self.Image) shiftScale.SetShift(self.Shift) shiftScale.SetScale(self.Scale) if self.OutputType == 'double': shiftScale.SetOutputScalarTypeToDouble() elif self.OutputType == 'uchar': shiftScale.SetOutputScalarTypeToUnsignedChar() elif self.OutputType == 'char': shiftScale.SetOutputScalarTypeToChar() elif self.OutputType == 'ushort': shiftScale.SetOutputScalarTypeToUnsignedShort() elif self.OutputType == 'short': shiftScale.SetOutputScalarTypeToShort() elif self.OutputType == 'ulong': shiftScale.SetOutputScalarTypeToUnsignedLong() elif self.OutputType == 'long': shiftScale.SetOutputScalarTypeToLong() elif self.OutputType == 'uint': shiftScale.SetOutputScalarTypeToUnsignedInt() elif self.OutputType == 'int': shiftScale.SetOutputScalarTypeToInt() elif self.OutputType == 'float': shiftScale.SetOutputScalarTypeToFloat() if self.OutputType != 'unchanged': if self.ClampOverflowOn: shiftScale.ClampOverflowOn() shiftScale.ClampOverflowOff() shiftScale.Update() self.Image = shiftScale.GetOutput() if self.MapRanges and self.OutputRange[0] != 0.0: shiftScale2 = vtk.vtkImageShiftScale() shiftScale2.SetInput(self.Image) shiftScale2.SetShift(self.OutputRange[0]) shiftScale2.SetScale(1.0) shiftScale2.Update() self.Image = shiftScale2.GetOutput()
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()
def Get_filter(self): x1 = float(self.gui.m_textCtrlOldValue1.GetValue()) y1 = float(self.gui.m_textCtrlOldValue2.GetValue()) x2 = float(self.gui.m_textCtrlNewValue1.GetValue()) y2 = float(self.gui.m_textCtrlNewValue2.GetValue()) if x1 == x2 and y1 == y2: logging.info("Current values will have no effect.") return None if x1 == y1 or x2 == y2: logging.info("Cannot satisfy these shift/scale") return None shift = x2 - x1 scale = (y2 - x2) / (y1 - x1) _type = [ vtk.VTK_CHAR, vtk.VTK_UNSIGNED_CHAR, vtk.VTK_SHORT, vtk.VTK_UNSIGNED_SHORT, vtk.VTK_INT, vtk.VTK_FLOAT, vtk.VTK_DOUBLE ][self.gui.m_choiceScalarType.GetSelection()] _filter = vtk.vtkImageShiftScale() _filter.SetInput(component.getUtility(ICurrentImage).GetRealImage()) _filter.SetOutputScalarType(_type) _filter.SetScale(scale) _filter.SetShift(shift) _filter.SetClampOverflow( int(self.gui.m_checkBoxClampOverflow.GetValue())) return _filter
def DownsampleImage(self, image, nbits=8): """Downsamples an image""" image.SetReleaseDataFlag(1) # get the min and max values from the image (minval, maxval) = image.GetScalarRange() # create an 8-bit version of this image _filter = vtk.vtkImageShiftScale() _filter.SetInput(image.GetRealImage()) _filter.SetShift(-minval) try: if nbits == 8: _filter.SetScale(255.0 / (maxval - minval)) elif nbits == 16: _filter.SetScale(65535.0 / (maxval - minval)) except ZeroDivisionError: logging.exception("DownsampleImage") _filter.SetScale(1.0) if nbits == 8: _filter.SetOutputScalarTypeToUnsignedChar() elif nbits == 16: _filter.SetOutputScalarTypeToShort() elif nbits == 32: _filter.SetOutputScalarTypeToFloat() elif nbits == 64: _filter.SetOutputScalarTypeToDouble() _filter.AddObserver('ProgressEvent', self.HandleVTKProgressEvent) _filter.SetProgressText("Downsampling to %d-bit..." % nbits) logging.info("Image downsampled to {0}-bit".format(nbits)) _filter.Update() return MVImage.MVImage(_filter.GetOutputPort(), input=image)
def WritePNGImageFile(self): if self.OutputFileName == "": self.PrintError("Error: no OutputFileName.") self.PrintLog("Writing PNG image file.") outputImage = self.Image if self.Image.GetScalarTypeAsString() != "unsigned char": shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInput(self.Image) if self.WindowLevel[0] == 0.0: scalarRange = self.Image.GetScalarRange() shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(255.0 / (scalarRange[1] - scalarRange[0])) else: shiftScale.SetShift(-(self.WindowLevel[1] - self.WindowLevel[0] / 2.0)) shiftScale.SetScale(255.0 / self.WindowLevel[0]) shiftScale.SetOutputScalarTypeToUnsignedChar() shiftScale.ClampOverflowOn() shiftScale.Update() outputImage = shiftScale.GetOutput() writer = vtk.vtkPNGWriter() writer.SetInput(outputImage) if self.Image.GetDimensions()[2] == 1: writer.SetFileName(self.OutputFileName) else: writer.SetFilePrefix(self.OutputFileName) writer.SetFilePattern("%s%04d.png") writer.Write()
def ipl_maskaimpeel(image_in1, image_in2, peel_iter): ipl_maskaimpeel_settings(peel_iter) extent = image_in1.GetExtent() voi = vtk.vtkExtractVOI() voi.SetInput(image_in1) voi.SetVOI(extent[0], extent[1], extent[2], extent[3], extent[4], extent[5]) voi.Update() shift = vtk.vtkImageShiftScale() shift.SetInputConnection(voi.GetOutputPort()) shift.SetOutputScalarTypeToUnsignedChar() shift.Update() mask = vtk.vtkImageMask() mask.SetImageInput(image_in2) mask.SetMaskInput(shift.GetOutput()) mask.SetMaskedOutputValue(0) mask.Update() if peel_iter != 0: erode = vtk.vtkImageContinuousErode3D() erode.SetInputConnection(mask.GetOutputPort()) erode.SetKernelSize(peel_iter + 1, peel_iter + 1, peel_iter + 1) erode.Update() mask = erode image_out = mask.GetOutput() return image_out
def getIntensityScaledData(self, data): """ Return the data shifted and scaled to appropriate intensity range """ if not self.explicitScale: return data if self.intensityScale == -1: return data if not self.shift: self.shift = vtk.vtkImageShiftScale() self.shift.SetOutputScalarTypeToUnsignedChar() self.shift.SetClampOverflow(1) self.shift.SetInputConnection(data.GetProducerPort()) # Need to call this or it will remember the whole extent it got from resampling self.shift.UpdateWholeExtent() if self.intensityScale: self.shift.SetScale(self.intensityScale) currScale = self.intensityScale else: minval, maxval = self.originalScalarRange scale = 255.0 / maxval self.shift.SetScale(scale) currScale = scale self.shift.SetShift(self.intensityShift) Logging.info("Intensity shift = %d, scale = %f" % (self.intensityShift, currScale), kw="datasource") return self.shift.GetOutput()
def _handleFailedImage(idiff, pngr, img_fname): """Writes all the necessary images when an image comparison failed.""" f_base, f_ext = os.path.splitext(img_fname) # write the difference image gamma adjusted for the dashboard. gamma = vtk.vtkImageShiftScale() gamma.SetInputConnection(idiff.GetOutputPort()) gamma.SetShift(0) gamma.SetScale(10) pngw = vtk.vtkPNGWriter() pngw.SetFileName(_getTempImagePath(f_base + ".diff.png")) pngw.SetInputConnection(gamma.GetOutputPort()) pngw.Write() # Write out the image that was generated. Write it out as full so that # it may be used as a baseline image if the tester deems it valid. pngw.SetInputConnection(idiff.GetInputConnection(0,0)) pngw.SetFileName(_getTempImagePath(f_base + ".png")) pngw.Write() # write out the valid image that matched. pngw.SetInputConnection(idiff.GetInputConnection(1,0)) pngw.SetFileName(_getTempImagePath(f_base + ".valid.png")) pngw.Write()
def getMIP(imageData, color): """ A function that will take a volume and do a simple maximum intensity projection that will be converted to a wxBitmap """ maxval = imageData.GetScalarRange()[1] imageData.SetUpdateExtent(imageData.GetWholeExtent()) if maxval > 255: shiftscale = vtk.vtkImageShiftScale() shiftscale.SetInputConnection(imageData.GetProducerPort()) shiftscale.SetScale(255.0 / maxval) shiftscale.SetOutputScalarTypeToUnsignedChar() imageData = shiftscale.GetOutput() mip = vtkbxd.vtkImageSimpleMIP() mip.SetInputConnection(imageData.GetProducerPort()) if color == None: output = optimize.execute_limited(mip) return output if mip.GetOutput().GetNumberOfScalarComponents() == 1: ctf = getColorTransferFunction(color) maptocolor = vtk.vtkImageMapToColors() maptocolor.SetInputConnection(mip.GetOutputPort()) maptocolor.SetLookupTable(ctf) maptocolor.SetOutputFormatToRGB() imagedata = optimize.execute_limited(maptocolor) else: imagedata = output = optimize.execute_limited(mip) return imagedata
def convert_scene_to_numpy_array(self): """ Convert the current window view to a numpy array. :return output: Scene as numpy array """ vtk_win_to_img_filter = vtk.vtkWindowToImageFilter() vtk_win_to_img_filter.SetInput(self.GetRenderWindow()) if not self.zbuffer: vtk_win_to_img_filter.SetInputBufferTypeToRGB() vtk_win_to_img_filter.Update() self.vtk_image = vtk_win_to_img_filter.GetOutput() else: vtk_win_to_img_filter.SetInputBufferTypeToZBuffer() vtk_scale = vtk.vtkImageShiftScale() vtk_scale.SetInputConnection(vtk_win_to_img_filter.GetOutputPort()) vtk_scale.SetOutputScalarTypeToUnsignedChar() vtk_scale.SetShift(0) vtk_scale.SetScale(-255) vtk_scale.Update() self.vtk_image = vtk_scale.GetOutput() width, height, _ = self.vtk_image.GetDimensions() self.vtk_array = self.vtk_image.GetPointData().GetScalars() number_of_components = self.vtk_array.GetNumberOfComponents() np_array = vtk_to_numpy(self.vtk_array).reshape( height, width, number_of_components) self.output = cv2.flip(np_array, flipCode=0) return self.output
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.OutputType == 'uchar' and self.ShiftScale: shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputData(self.Image) if self.WindowLevel[0] == 0.0: scalarRange = self.Image.GetScalarRange() scale = 255.0 if (scalarRange[1]-scalarRange[0]) > 0.0: scale = 255.0/(scalarRange[1]-scalarRange[0]) shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(scale) else: shiftScale.SetShift(-(self.WindowLevel[1]-self.WindowLevel[0]/2.0)) shiftScale.SetScale(255.0/self.WindowLevel[0]) shiftScale.SetOutputScalarTypeToUnsignedChar() shiftScale.ClampOverflowOn() shiftScale.Update() self.Image = shiftScale.GetOutput() else: cast = vtk.vtkImageCast() cast.SetInputData(self.Image) if self.OutputType == 'float': cast.SetOutputScalarTypeToFloat() elif self.OutputType == 'double': cast.SetOutputScalarTypeToDouble() elif self.OutputType == 'uchar': cast.SetOutputScalarTypeToUnsignedChar() elif self.OutputType == 'short': cast.SetOutputScalarTypeToShort() cast.Update() self.Image = cast.GetOutput()
def WriteTIFFImageFile(self): if (self.OutputFileName == ''): self.PrintError('Error: no OutputFileName.') self.PrintLog('Writing TIFF image file.') outputImage = self.Image if self.Image.GetScalarTypeAsString() != 'unsigned char': shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputData(self.Image) if self.WindowLevel[0] == 0.0: scalarRange = self.Image.GetScalarRange() shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(255.0 / (scalarRange[1] - scalarRange[0])) else: shiftScale.SetShift(-(self.WindowLevel[1] - self.WindowLevel[0] / 2.0)) shiftScale.SetScale(255.0 / self.WindowLevel[0]) shiftScale.SetOutputScalarTypeToUnsignedChar() shiftScale.ClampOverflowOn() shiftScale.Update() outputImage = shiftScale.GetOutput() writer = vtk.vtkTIFFWriter() writer.SetInputData(outputImage) if self.Image.GetDimensions()[2] == 1: writer.SetFileName(self.OutputFileName) else: writer.SetFilePrefix(self.OutputFileName) writer.SetFilePattern("%s%04d.tif") writer.Write()
def getIntensityScaledData(self, data): """ Return the data shifted and scaled to appropriate intensity range """ if not self.explicitScale: return data if self.intensityScale == -1: return data if not self.shift: self.shift = vtk.vtkImageShiftScale() self.shift.SetOutputScalarTypeToUnsignedChar() self.shift.SetClampOverflow(1) self.shift.SetInputConnection(data.GetProducerPort()) # Need to call this or it will remember the whole extent it got from resampling self.shift.UpdateWholeExtent() if self.intensityScale: self.shift.SetScale(self.intensityScale) currScale = self.intensityScale else: minval, maxval = self.originalScalarRange scale = 255.0 / maxval self.shift.SetScale(scale) currScale = scale self.shift.SetShift(self.intensityShift) Logging.info("Intensity shift = %d, scale = %f"%(self.intensityShift, currScale), kw="datasource") return self.shift.GetOutput()
def convert(filepath): filepath = "./display/" reader = vtk.vtkDICOMImageReader() #we create a new vtkDICOMImageReader under the name of reader which we use to read the DICOM images. reader.SetDirectoryName(filepath) reader.Update() image = reader.GetOutput() shiftScaleFilter = vtkImageShiftScale() shiftScaleFilter.SetOutputScalarTypeToUnsignedChar() shiftScaleFilter.SetInputConnection(reader.GetOutputPort()) shiftScaleFilter.SetShift(-1.0*image.GetScalarRange()[0]) oldRange = image.GetScalarRange()[1] - image.GetScalarRange()[0] newRange = 255 shiftScaleFilter.SetScale(newRange/oldRange) shiftScaleFilter.Update() writer = vtkPNGWriter() writer.SetFileName('./display/output.png') # you give the path-filename where you want the output to be writer.SetInputConnection(shiftScaleFilter.GetOutputPort()) writer.Write() return 1
def avgProjectionsVtk(self, filenames , extent): '''Returns the average of the input images Input is passed as filenames pointing to 2D TIFF Output is a vtkImageData gives the same result as avgProjections within machine precision. ''' num = len(filenames) readers = [vtk.vtkTIFFReader() for i in range(num)] scalers = [vtk.vtkImageShiftScale() for i in range(num)] vois = [vtk.vtkExtractVOI() for i in range(num)] avger = vtk.vtkImageWeightedSum() counter = 0 for reader, voi, scaler, filename in zip(readers, vois , scalers ,filenames): reader.SetFileName(filename) reader.Update() print ("reading {0}".format(filename)) voi.SetInputData(reader.GetOutput()) voi.SetVOI(extent) voi.Update() print ("extracting VOI") scaler.SetInputData(voi.GetOutput()) scaler.SetOutputScalarTypeToDouble() scaler.SetScale(1) scaler.SetShift(0) scaler.Update() avger.AddInputData(scaler.GetOutput()) avger.SetWeight(counter , 1/float(num)) counter = counter + 1 print ("adding input connection {0}".format(counter)) avger.Update() return avger.GetOutput()
def execute(self, inputs, update = 0, last = 0): """ Execute the filter with given inputs and return the output """ if not lib.ProcessingFilter.ProcessingFilter.execute(self, inputs): return None image = self.getInput(1) self.vtkfilter.SetInput(image) self.vtkfilter.SetConsiderAnisotropy(self.parameters["ConsiderAnisotropy"]) self.vtkfilter.SetAlgorithm(self.parameters["Algorithm"]) data = self.vtkfilter.GetOutput() if self.parameters["CastToUnsignedChar"]: self.vtkfilter.Update() cast = vtk.vtkImageShiftScale() x0, x1 = data.GetScalarRange() print data print "Scalar range=",x0,x1 cast.SetInput(self.vtkfilter.GetOutput()) cast.SetOutputScalarTypeToUnsignedChar() #cast.SetClampOverflow(1) cast.SetScale(255.0/x1) print "Setting scale to ", 255.0/x1 data = cast.GetOutput() if update: self.vtkfilter.Update() return data
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageShiftScale(), 'Processing.', ('vtkImageData',), ('vtkImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def CreateVolumeSource(self): imageReader = vtk.vtkMetaImageReader() imageReader.SetFileName(self.ImageFileName) compSrc = vtk.vtkImageExtractComponents() compSrc.SetInputConnection(imageReader.GetOutputPort()) compSrc.SetComponents(self.ComponentIndex) compSrc.Update() valueMin, valueMax = compSrc.GetOutput().GetPointData().GetArray( 'MetaImage').GetValueRange() valueMin = 0.0 toUnsignedShort = vtk.vtkImageShiftScale() toUnsignedShort.ClampOverflowOn() toUnsignedShort.SetShift(-valueMin) if valueMax - valueMin != 0: toUnsignedShort.SetScale( 512.0 / (valueMax - valueMin)) #randomly cause error that "zerodivision" toUnsignedShort.SetInputConnection(compSrc.GetOutputPort()) toUnsignedShort.SetOutputScalarTypeToUnsignedShort() return toUnsignedShort
def setInputAsNumpy(self, numpyarray): if (len(numpy.shape(numpyarray)) == 3): doubleImg = vtk.vtkImageData() shape = numpy.shape(numpyarray) doubleImg.SetDimensions(shape[0], shape[1], shape[2]) doubleImg.SetOrigin(0, 0, 0) doubleImg.SetSpacing(1, 1, 1) doubleImg.SetExtent(0, shape[0] - 1, 0, shape[1] - 1, 0, shape[2] - 1) doubleImg.AllocateScalars(vtk.VTK_DOUBLE, 1) for i in range(shape[0]): for j in range(shape[1]): for k in range(shape[2]): doubleImg.SetScalarComponentFromDouble( i, j, k, 0, numpyarray[i][j][k]) # rescale to appropriate VTK_UNSIGNED_SHORT stats = vtk.vtkImageAccumulate() stats.SetInputData(doubleImg) stats.Update() iMin = stats.GetMin()[0] iMax = stats.GetMax()[0] scale = vtk.VTK_UNSIGNED_SHORT_MAX / (iMax - iMin) shiftScaler = vtk.vtkImageShiftScale() shiftScaler.SetInputData(doubleImg) shiftScaler.SetScale(scale) shiftScaler.SetShift(iMin) shiftScaler.SetOutputScalarType(vtk.VTK_UNSIGNED_SHORT) shiftScaler.Update() self.img3D = shiftScaler.GetOutput()
def shiftscale_uchar(image, ww=300.0, wc=40.0): """ Parameters ---------- image : vtk data ww : float window width wc : float window center Returns ------- shift_data : vkt uchar data """ shift_scale = vtk.vtkImageShiftScale() shift_scale.SetInputData(image.GetOutput()) shift_scale.SetShift(-(wc - 0.5 * ww)) shift_scale.SetScale(255.0 / ww) shift_scale.SetOutputScalarTypeToUnsignedChar() shift_scale.ClampOverflowOn() shift_scale.Update() return shift_scale
def WriteTIFFImageFile(self): if (self.OutputFileName == ''): self.PrintError('Error: no OutputFileName.') self.PrintLog('Writing TIFF image file.') outputImage = self.Image if self.Image.GetScalarTypeAsString() != 'unsigned char': shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputData(self.Image) if self.WindowLevel[0] == 0.0: scalarRange = self.Image.GetScalarRange() shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(255.0/(scalarRange[1]-scalarRange[0])) else: shiftScale.SetShift(-(self.WindowLevel[1]-self.WindowLevel[0]/2.0)) shiftScale.SetScale(255.0/self.WindowLevel[0]) shiftScale.SetOutputScalarTypeToUnsignedChar() shiftScale.ClampOverflowOn() shiftScale.Update() outputImage = shiftScale.GetOutput() writer = vtk.vtkTIFFWriter() writer.SetInputData(outputImage) if self.Image.GetDimensions()[2] == 1: writer.SetFileName(self.OutputFileName) else: writer.SetFilePrefix(self.OutputFileName) writer.SetFilePattern("%s%04d.tif") writer.Write()
def SetupTextureMapper(self): if not self.GetInput(): return mapper3D = vtk.vtkVolumeTextureMapper3D.SafeDownCast(self.__VolumeTextureMapper) if mapper3D and not self.GetRenderWindow().GetNeverRendered(): if not mapper3D.IsRenderSupported(self.__VolumeProperty): # try the ATI fragment program implementation mapper3D.SetPreferredMethodToFragmentProgram() if not mapper3D.IsRenderSupported(self.__VolumeProperty): print "Warning: 3D texture volume rendering is not supported by your hardware, switching to 2D texture rendering." newMapper = vtk.vtkVolumeTextureMapper2D() newMapper.CroppingOn() newMapper.SetCroppingRegionFlags (0x7ffdfff) range = self.GetInput().GetScalarRange() shift = 0 - range[0] scale = 65535.0 / (range[1]-range[0]) scaler = vtk.vtkImageShiftScale() scaler.SetInput(self.GetInput()) scaler.SetShift(shift) scaler.SetScale(scale) scaler.SetOutputScalarTypeToUnsignedShort() scaler.Update() newMapper.SetInput(scaler.GetOutput()) # del scaler self.__Callback.SetVolumeMapper(newMapper) self.__VolumeMapper = newMapper self.__VolumeMapper.SetMapper(newMapper)
def highlight_voxels_3D(self, coords): self.viewer.ren_iso.RemoveVolume(self.viewer.vol) newimage = vtk.vtkImageData() newimage.SetSpacing(self.viewer.volumedata.GetSpacing()) newimage.SetOrigin(self.viewer.volumedata.GetOrigin()) newimage.SetDimensions(self.viewer.volumedata.GetDimensions()) newimage.SetExtent(self.viewer.volumedata.GetExtent()) newimage.SetNumberOfScalarComponents(1) newimage.SetScalarTypeToDouble() newimage.AllocateScalars() for p in coords: newimage.SetScalarComponentFromDouble(p[0], p[1], p[2], 0, p[3]) shift_scale = vtk.vtkImageShiftScale() shift_scale.SetInput(newimage) shift_scale.SetOutputScalarTypeToUnsignedChar() shift_scale.Update() flipYFilter = vtk.vtkImageFlip() flipYFilter.SetFilteredAxis(1) flipYFilter.SetInput(shift_scale.GetOutput()) flipYFilter.Update() self.viewer.volMapper.SetInput(flipYFilter.GetOutput()) self.viewer.ren_iso.AddVolume(self.viewer.vol) self.viewer.refresh_3d()
def execute(self, inputs, update=0, last=0): """ Execute the filter with given inputs and return the output """ if not lib.ProcessingFilter.ProcessingFilter.execute(self, inputs): return None image = self.getInput(1) self.vtkfilter.SetInput(image) self.vtkfilter.SetConsiderAnisotropy( self.parameters["ConsiderAnisotropy"]) self.vtkfilter.SetAlgorithm(self.parameters["Algorithm"]) data = self.vtkfilter.GetOutput() if self.parameters["CastToUnsignedChar"]: self.vtkfilter.Update() cast = vtk.vtkImageShiftScale() x0, x1 = data.GetScalarRange() print data print "Scalar range=", x0, x1 cast.SetInput(self.vtkfilter.GetOutput()) cast.SetOutputScalarTypeToUnsignedChar() #cast.SetClampOverflow(1) cast.SetScale(255.0 / x1) print "Setting scale to ", 255.0 / x1 data = cast.GetOutput() if update: self.vtkfilter.Update() return data
def Execute(self): if self.Image == None: self.PrintError("Error: No input image.") if self.OutputType == "uchar" and self.ShiftScale: shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInput(self.Image) if self.WindowLevel[0] == 0.0: scalarRange = self.Image.GetScalarRange() shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(255.0 / (scalarRange[1] - scalarRange[0])) else: shiftScale.SetShift(-(self.WindowLevel[1] - self.WindowLevel[0] / 2.0)) shiftScale.SetScale(255.0 / self.WindowLevel[0]) shiftScale.SetOutputScalarTypeToUnsignedChar() shiftScale.ClampOverflowOn() shiftScale.Update() self.Image = shiftScale.GetOutput() else: cast = vtk.vtkImageCast() cast.SetInput(self.Image) if self.OutputType == "float": cast.SetOutputScalarTypeToFloat() elif self.OutputType == "double": cast.SetOutputScalarTypeToDouble() elif self.OutputType == "uchar": cast.SetOutputScalarTypeToUnsignedChar() elif self.OutputType == "short": cast.SetOutputScalarTypeToShort() cast.Update() self.Image = cast.GetOutput()
def createImageData(): sphere = vtk.vtkSphere() sphere.SetRadius(0.1) sphere.SetCenter(0.0, 0.0, 0.0) sampleFunction = vtk.vtkSampleFunction() sampleFunction.SetImplicitFunction(sphere) sampleFunction.SetOutputScalarTypeToDouble() sampleFunction.SetSampleDimensions(127, 127, 127) sampleFunction.SetModelBounds(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0) sampleFunction.SetCapping(False) sampleFunction.SetComputeNormals(False) sampleFunction.SetScalarArrayName("values") sampleFunction.Update() a = sampleFunction.GetOutput().GetPointData().GetScalars("values") range = a.GetRange() print range t = vtk.vtkImageShiftScale() t.SetInputConnection(sampleFunction.GetOutputPort()) t.SetShift(-range[0]) magnitude = range[1] - range[0] if magnitude == 0.0: magnitude = 1.0 t.SetScale(255.0 / magnitude) t.SetOutputScalarTypeToUnsignedChar() t.Update() return t.GetOutput()
def diff(im1, im2): #Takes the differences of two aim files and adds them together shift1 = vtk.vtkImageShiftScale() shift1.SetInputConnection(im1.GetOutputPort()) shift1.SetOutputScalarTypeToChar() shift2 = vtk.vtkImageShiftScale() shift2.SetInputConnection(im2.GetOutputPort()) shift2.SetOutputScalarTypeToChar() box1 = vtk.vtkImageReslice() box1.SetInput(shift1.GetOutput()) box1.SetResliceAxesOrigin(im2.GetOutput().GetOrigin()) box1.Update() sub1 = vtk.vtkImageMathematics() sub1.SetInput1(box1.GetOutput()) sub1.SetInput2(shift2.GetOutput()) sub1.SetOperationToSubtract() sub2 = vtk.vtkImageMathematics() sub2.SetInput1(shift2.GetOutput()) sub2.SetInput2(shift1.GetOutput()) sub2.SetOperationToSubtract() step1 = vtk.vtkImageMathematics() step1.SetInput1(sub1.GetOutput()) step1.SetConstantC(-127) step1.SetConstantK(0) step1.SetOperationToReplaceCByK() step2 = vtk.vtkImageMathematics() step2.SetInput1(sub2.GetOutput()) step2.SetConstantC(-127) step2.SetConstantK(0) step2.SetOperationToReplaceCByK() add = vtk.vtkImageMathematics() add.SetInput1(step2.GetOutput()) add.SetInput2(step1.GetOutput()) add.SetOperationToAdd() return add
def save_frame_depth(self, path): #setup camera camera = vtkCamera() camera.SetPosition(self.cx, self.cy, self.cz) camera.SetFocalPoint(self.fx, self.fy, self.fz) camera.SetViewUp(self.ux, self.uy, self.uz) camera.SetViewAngle(self.fovy) #setup renderer renderer = vtkRenderer() renderWindow = vtkRenderWindow() renderWindow.SetOffScreenRendering(1) renderWindow.AddRenderer(renderer) renderWindow.SetSize(self.w, self.h) for i in xrange(-1, self.expert.nr_obstacles_c()): vss, nss, iss = self.save_frame_mesh(i) #geometry pts = vtkPoints() for i in xrange(len(vss)): pts.InsertNextPoint(vss[i][0], vss[i][1], vss[i][2]) tris = vtkCellArray() for i in xrange(len(iss)): triangle = vtkTriangle() triangle.GetPointIds().SetId(0, iss[i][0]) triangle.GetPointIds().SetId(1, iss[i][1]) triangle.GetPointIds().SetId(2, iss[i][2]) tris.InsertNextCell(triangle) poly = vtkPolyData() poly.SetPoints(pts) poly.SetPolys(tris) #actor mapper = vtkPolyDataMapper() mapper.SetInput(poly) actor = vtkActor() actor.SetMapper(mapper) renderer.AddActor(actor) renderer.SetBackground(self.bk_r, self.bk_g, self.bk_b) renderer.SetActiveCamera(camera) renderWindow.Render() #output options windowToImageFilter = vtkWindowToImageFilter() windowToImageFilter.SetInput(renderWindow) windowToImageFilter.SetMagnification(1) windowToImageFilter.SetInputBufferTypeToZBuffer() #Extract z buffer value windowToImageFilter.Update() #scale and shift scale = vtkImageShiftScale() scale.SetOutputScalarTypeToUnsignedChar() scale.SetInputConnection(windowToImageFilter.GetOutputPort()) scale.SetShift(0) scale.SetScale(-255) #output writer = vtkBMPWriter() writer.SetFileName(path) writer.SetInputConnection(scale.GetOutputPort()) writer.Write()
def Rescale(combo, ZeroPoint): """Rescale to legal pixel values [-1, 1] --> [0, MaxScaledValue]""" scaled = vtk.vtkImageShiftScale() scaled.SetInputConnection(combo.GetOutputPort()) scaled.SetShift(1.) scaled.SetScale(ZeroPoint + 1) scaled.SetOutputScalarTypeToUnsignedShort() return scaled
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkImageShiftScale(), 'Processing.', ('vtkImageData', ), ('vtkImageData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def ipl_add_aims(image_in1, image_in2): ipl_add_aims_settings() extent1 = image_in1.GetExtent() voi1 = vtk.vtkExtractVOI() voi1.SetInput(image_in1) voi1.SetVOI(extent1[0], extent1[1], extent1[2], extent1[3], extent1[4], extent1[5]) extent2 = image_in2.GetExtent() voi2 = vtk.vtkExtractVOI() voi2.SetInput(image_in2) voi2.SetVOI(extent2[0], extent2[1], extent2[2], extent2[3], extent2[4], extent2[5]) shift1 = vtk.vtkImageShiftScale() shift1.SetInputConnection(voi1.GetOutputPort()) shift1.SetOutputScalarTypeToChar() shift1.Update() shift2 = vtk.vtkImageShiftScale() shift2.SetInputConnection(voi2.GetOutputPort()) shift2.SetOutputScalarTypeToChar() shift2.Update() add = vtk.vtkImageMathematics() add.SetInput1(shift1.GetOutput()) add.SetInput2(shift2.GetOutput()) add.SetOperationToAdd() add.Update() temp = vtk.vtkImageMathematics() temp.SetInput1(add.GetOutput()) temp.SetConstantC(-2) temp.SetConstantK(127) temp.SetOperationToReplaceCByK() temp.Update() image_out = temp.GetOutput() return image_out
def __init__(self): """ Initialization """ lib.ProcessingFilter.ProcessingFilter.__init__(self, (1, 1)) self.vtkfilter = vtk.vtkImageShiftScale() self.vtkfilter.AddObserver("ProgressEvent", lib.messenger.send) lib.messenger.connect(self.vtkfilter, 'ProgressEvent', self.updateProgress) self.eventDesc = "Applying a shift and scale to image intensity" self.descs = {"Shift": "Shift:", "Scale": "Scale:", "AutoScale": "Scale to max range of data type", "NoOverflow":"Prevent over/underflow", "Scale8bit": "Scale to 8-bit range (0-255)"} self.filterDesc = "Shifts pixel/voxel intensities and then scales them, corresponding roughly to the adjustment of brightness and contrast, respectively\nInput: Grayscale image\nOutput: Grayscale image"
def __cvt2ubyte(self, reader): reader.Update() self.sliceNum = reader.GetOutput().GetDimensions()[2] self.sliceIdx = self.sliceNum / 2 min, max = reader.GetOutput().GetScalarRange() data = vtk.vtkImageShiftScale() data.SetInputConnection(reader.GetOutputPort()) data.SetShift(-1.0 * min) data.SetScale(255.0 / (max - min)) data.SetOutputScalarTypeToUnsignedChar() return data
def __init__(self,renWin): self.renWin = renWin self.zBuffFilter = vtk.vtkWindowToImageFilter() self.zBuffFilter.SetInput(self.renWin) self.zBuffFilter.SetInputBufferTypeToZBuffer() self.scaledZBuff = vtk.vtkImageShiftScale() self.scaledZBuff.SetOutputScalarTypeToUnsignedChar() self.scaledZBuff.SetInputConnection(self.zBuffFilter.GetOutputPort()) self.scaledZBuff.SetShift(0) self.scaledZBuff.SetScale(255)
def __init__(self, renWin): self.renWin = renWin self.zBuffFilter = vtk.vtkWindowToImageFilter() self.zBuffFilter.SetInput(self.renWin) self.zBuffFilter.SetMagnification(1) self.zBuffFilter.SetInputBufferTypeToZBuffer() self.scaledZBuff = vtk.vtkImageShiftScale() self.scaledZBuff.SetOutputScalarTypeToUnsignedChar() self.scaledZBuff.SetInputConnection(self.zBuffFilter.GetOutputPort()) self.scaledZBuff.SetShift(0) self.scaledZBuff.SetScale(-255)
def __init__(self): """ Initialization """ lib.ProcessingFilter.ProcessingFilter.__init__(self, (1, 1)) self.vtkfilter = vtk.vtkImageShiftScale() self.vtkfilter.AddObserver("ProgressEvent", lib.messenger.send) lib.messenger.connect(self.vtkfilter, 'ProgressEvent', self.updateProgress) self.eventDesc = "Applying an Automatic background subtraction" self.descs = {"SmallestNonZeroValue":"Use smallest non-zero value as background", "FirstPeak":"First peak in histogram","MostCommon":"Most common value"} self.filterDesc = "Removes background by subtracting a certain value from the intensity of every pixel/voxel\nInput: Grayscale image\nOutput: Grayscale image"
def __cvt2ubyte(self, reader): reader.Update() x, y, z = reader.GetOutput().GetDimensions() self.orientation_dict = { #sliceNum, sliceIdx 0: [lambda viewer: viewer.SetSliceOrientationToXY, z, z / 2], 1: [lambda viewer: viewer.SetSliceOrientationToYZ, x, x / 2], 2: [lambda viewer: viewer.SetSliceOrientationToXZ, y, y / 2] } min, max = reader.GetOutput().GetScalarRange() data = vtk.vtkImageShiftScale() data.SetInputConnection(reader.GetOutputPort()) data.SetShift(-1.0 * min) data.SetScale(255.0 / (max - min + 0.00001)) data.SetOutputScalarTypeToUnsignedChar() return data
def CreateVolumeSource(self): imageReader = vtk.vtkMetaImageReader() imageReader.SetFileName(self.ImageFileName) imageReader.Update() valueMin, valueMax = imageReader.GetOutput().GetPointData( ).GetArray('MetaImage').GetValueRange() toUnsignedShort = vtk.vtkImageShiftScale() toUnsignedShort.ClampOverflowOn() toUnsignedShort.SetShift(-valueMin) toUnsignedShort.SetScale(512.0 / (valueMax - valueMin)) toUnsignedShort.SetInputConnection(imageReader.GetOutputPort()) toUnsignedShort.SetOutputScalarTypeToUnsignedShort() return toUnsignedShort
def _handleFailedImage(idiff, pngr, img_fname): """Writes all the necessary images when an image comparison failed.""" f_base, f_ext = os.path.splitext(img_fname) # write out the difference file in full. pngw = vtk.vtkPNGWriter() pngw.SetFileName(_getTempImagePath(f_base + ".diff.png")) pngw.SetInput(idiff.GetOutput()) pngw.Write() # write the difference image scaled and gamma adjusted for the # dashboard. sz = pngr.GetOutput().GetDimensions() if sz[1] <= 250.0: mag = 1.0 else: mag = 250.0 / sz[1] shrink = vtk.vtkImageResample() shrink.SetInput(idiff.GetOutput()) shrink.InterpolateOn() shrink.SetAxisMagnificationFactor(0, mag) shrink.SetAxisMagnificationFactor(1, mag) gamma = vtk.vtkImageShiftScale() gamma.SetInput(shrink.GetOutput()) gamma.SetShift(0) gamma.SetScale(10) jpegw = vtk.vtkJPEGWriter() jpegw.SetFileName(_getTempImagePath(f_base + ".diff.small.jpg")) jpegw.SetInput(gamma.GetOutput()) jpegw.SetQuality(85) jpegw.Write() # write out the image that was generated. shrink.SetInput(idiff.GetInput()) jpegw.SetInput(shrink.GetOutput()) jpegw.SetFileName(_getTempImagePath(f_base + ".test.small.jpg")) jpegw.Write() # write out the valid image that matched. shrink.SetInput(idiff.GetImage()) jpegw.SetInput(shrink.GetOutput()) jpegw.SetFileName(_getTempImagePath(f_base + ".small.jpg")) jpegw.Write()
def _handleFailedImage(idiff, pngr, img_fname): """Writes all the necessary images when an image comparison failed.""" f_base, f_ext = os.path.splitext(img_fname) # write out the difference file in full. pngw = vtk.vtkPNGWriter() pngw.SetFileName(_getTempImagePath(f_base + ".diff.png")) pngw.SetInput(idiff.GetOutput()) pngw.Write() # write the difference image scaled and gamma adjusted for the # dashboard. sz = pngr.GetOutput().GetDimensions() if sz[1] <= 250.0: mag = 1.0 else: mag = 250.0/sz[1] shrink = vtk.vtkImageResample() shrink.SetInput(idiff.GetOutput()) shrink.InterpolateOn() shrink.SetAxisMagnificationFactor(0, mag) shrink.SetAxisMagnificationFactor(1, mag) gamma = vtk.vtkImageShiftScale() gamma.SetInput(shrink.GetOutput()) gamma.SetShift(0) gamma.SetScale(10) jpegw = vtk.vtkJPEGWriter() jpegw.SetFileName(_getTempImagePath(f_base + ".diff.small.jpg")) jpegw.SetInput(gamma.GetOutput()) jpegw.SetQuality(85) jpegw.Write() # write out the image that was generated. shrink.SetInput(idiff.GetInput()) jpegw.SetInput(shrink.GetOutput()) jpegw.SetFileName(_getTempImagePath(f_base + ".test.small.jpg")) jpegw.Write() # write out the valid image that matched. shrink.SetInput(idiff.GetImage()) jpegw.SetInput(shrink.GetOutput()) jpegw.SetFileName(_getTempImagePath(f_base + ".small.jpg")) jpegw.Write()
def dicom_to_png(imagedata, dir): logging.debug("In data.dicom_to_png()") shiftScale = vtk.vtkImageShiftScale() shiftScale.SetOutputScalarTypeToUnsignedShort() shiftScale.SetInput(imagedata) inp = shiftScale.GetInput() minv, maxv = inp.GetScalarRange() shiftScale.SetShift(-minv) shiftScale.SetScale(65535 / (maxv - minv)) w = vtk.vtkPNGWriter() w.SetFileDimensionality(3) w.SetInput(shiftScale.GetOutput()) w.SetFilePattern("%s%d.png") if not os.path.exists(dir): os.mkdir(dir) w.SetFilePrefix(dir) w.Write()
def Display(self): wholeExtent = self.Image.GetWholeExtent() self.SliceVOI[0] = wholeExtent[0] self.SliceVOI[1] = wholeExtent[1] self.SliceVOI[2] = wholeExtent[2] self.SliceVOI[3] = wholeExtent[3] self.SliceVOI[4] = wholeExtent[4] self.SliceVOI[5] = wholeExtent[5] self.SliceVOI[self.Axis*2] = wholeExtent[self.Axis*2] self.SliceVOI[self.Axis*2+1] = wholeExtent[self.Axis*2] range = self.Image.GetScalarRange() imageShifter = vtk.vtkImageShiftScale() imageShifter.SetInput(self.Image) imageShifter.SetShift(-1.0*range[0]) imageShifter.SetScale(255.0/(range[1]-range[0])) imageShifter.SetOutputScalarTypeToUnsignedChar() widgetImage = imageShifter.GetOutput() self.ImageActor.SetInput(widgetImage) self.ImageActor.SetDisplayExtent(self.SliceVOI) self.vmtkRenderer.Renderer.AddActor(self.ImageActor) self.ImageTracerWidget.SetCaptureRadius(1.5) self.ImageTracerWidget.SetViewProp(self.ImageActor) self.ImageTracerWidget.SetInput(widgetImage) self.ImageTracerWidget.ProjectToPlaneOn() self.ImageTracerWidget.SetProjectionNormal(self.Axis) self.ImageTracerWidget.PlaceWidget() self.ImageTracerWidget.SetAutoClose(self.AutoClose) self.ImageTracerWidget.AddObserver("StartInteractionEvent",self.SetWidgetProjectionPosition) self.ImageTracerWidget.AddObserver("EndInteractionEvent",self.GetLineFromWidget) interactorStyle = vtk.vtkInteractorStyleImage() self.vmtkRenderer.RenderWindowInteractor.SetInteractorStyle(interactorStyle) self.vmtkRenderer.Render()
def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # ctor for this specific mixin # FilenameViewModuleMixin.__init__(self) self._shiftScale = vtk.vtkImageShiftScale() self._shiftScale.SetOutputScalarTypeToUnsignedShort() module_utils.setup_vtk_object_progress( self, self._shiftScale, 'Converting input to unsigned short.') self._writer = vtk.vtkPNGWriter() self._writer.SetFileDimensionality(3) self._writer.SetInput(self._shiftScale.GetOutput()) module_utils.setup_vtk_object_progress( self, self._writer, 'Writing PNG file(s)') self._config.filePattern = '%d.png' configList = [ ('File pattern:', 'filePattern', 'base:str', 'filebrowser', 'Filenames will be built with this. See module help.', {'fileMode' : wx.OPEN, 'fileMask' : 'PNG files (*.png)|*.png|All files (*.*)|*.*'})] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkPNGWriter' : self._writer}) self.sync_module_logic_with_config()
def execute(self, inputs, update = 0, last = 0): """ Execute the filter with given inputs and return the output """ if not lib.ProcessingFilter.ProcessingFilter.execute(self, inputs): return None roi = self.parameters["ROI"][1] scripting.wantWholeDataset = 1 imagedata = self.getInput(1) imagedata.SetUpdateExtent(imagedata.GetWholeExtent()) imagedata.Update() itkOrig = self.convertVTKtoITK(imagedata) itkOrig.DisconnectPipeline() mx, my, mz = self.dataUnit.getDimensions() n, maskImage = lib.ImageOperations.getMaskFromROIs([roi], mx, my, mz) itkLabel = self.convertVTKtoITK(maskImage) itkLabel = self.castITKImage(itkLabel, itkOrig) #vtkToItk2 = itk.VTKImageToImageFilter.IUC3.New() #vtkToItk2.SetInput(maskImage) #itkLabel = vtkToItk2.GetOutput() #itkLabel.Update() labelStats = itk.LabelStatisticsImageFilter[itkOrig, itkLabel].New() labelStats.SetInput(0, itkOrig) labelStats.SetInput(1, itkLabel) labelStats.Update() avgint = labelStats.GetMean(255) print "Subtract from image:",avgint shift = vtk.vtkImageShiftScale() shift.SetInput(imagedata) shift.SetClampOverflow(1) shift.SetScale(1) shift.SetShift(-avgint) return shift.GetOutput()
def getDataSet(self, i, raw = 0): """ Returns the DataSet at the specified index Parameters: i The index """ data = self.getTimepoint(i) data = self.getResampledData(data, i) if not self.shift: self.shift = vtk.vtkImageShiftScale() self.shift.SetOutputScalarTypeToUnsignedChar() self.shift.SetInput(data) x0, x1 = data.GetScalarRange() print "Scalar range=", x0, x1 if not x1: x1 = 1 scale = 255.0/x1 if scale: self.shift.SetScale(scale) self.shift.Update() data = self.shift.GetOutput() data.ReleaseDataFlagOff() return data
def Get_filter(self): x1 = float(self.gui.m_textCtrlOldValue1.GetValue()) y1 = float(self.gui.m_textCtrlOldValue2.GetValue()) x2 = float(self.gui.m_textCtrlNewValue1.GetValue()) y2 = float(self.gui.m_textCtrlNewValue2.GetValue()) if x1 == x2 and y1 == y2: logging.info( "Current values will have no effect.") return None if x1 == y1 or x2 == y2: logging.info("Cannot satisfy these shift/scale") return None shift = x2 - x1 scale = (y2 - x2) / (y1 - x1) _type = [vtk.VTK_CHAR, vtk.VTK_UNSIGNED_CHAR, vtk.VTK_SHORT, vtk.VTK_UNSIGNED_SHORT, vtk.VTK_INT, vtk.VTK_FLOAT, vtk.VTK_DOUBLE][self.gui.m_choiceScalarType.GetSelection()] _filter = vtk.vtkImageShiftScale() _filter.SetInput(component.getUtility(ICurrentImage).GetRealImage()) _filter.SetOutputScalarType(_type) _filter.SetScale(scale) _filter.SetShift(shift) _filter.SetClampOverflow(int( self.gui.m_checkBoxClampOverflow.GetValue())) return _filter
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()
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # A script to test the vtkLassoStencilSource reader = vtk.vtkPNGReader() reader.SetDataSpacing(0.8,0.8,1.5) reader.SetDataOrigin(0.0,0.0,0.0) reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/fullhead15.png") reader.Update() shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputConnection(reader.GetOutputPort()) shiftScale.SetScale(0.2) shiftScale.Update() points1 = vtk.vtkPoints() points1.InsertNextPoint(80,50,0) points1.InsertNextPoint(100,90,0) points1.InsertNextPoint(200,50,0) points1.InsertNextPoint(230,100,0) points1.InsertNextPoint(150,170,0) points1.InsertNextPoint(110,170,0) points1.InsertNextPoint(80,50,0) points2 = vtk.vtkPoints() points2.InsertNextPoint(80,50,0) points2.InsertNextPoint(100,90,0) points2.InsertNextPoint(200,50,0) points2.InsertNextPoint(230,100,0) points2.InsertNextPoint(150,170,0) points2.InsertNextPoint(110,170,0)
def buildPipeline(self): """ execute() -> None Dispatch the vtkRenderer to the actual rendering widget """ self.colorInputModule = self.wmod.forceGetInputFromPort( "colors", None ) if self.input() == None: print>>sys.stderr, "Must supply 'volume' port input to VectorCutPlane" return xMin, xMax, yMin, yMax, zMin, zMax = self.input().GetWholeExtent() spacing = self.input().GetSpacing() sx, sy, sz = spacing origin = self.input().GetOrigin() ox, oy, oz = origin cellData = self.input().GetCellData() pointData = self.input().GetPointData() vectorsArray = pointData.GetVectors() if vectorsArray == None: print>>sys.stderr, "Must supply point vector data for 'volume' port input to VectorVolume" return self.setRangeBounds( list( vectorsArray.GetRange(-1) ) ) self.nComponents = vectorsArray.GetNumberOfComponents() for iC in range(-1,3): print "Value Range %d: %s " % ( iC, str( vectorsArray.GetRange( iC ) ) ) for iV in range(10): print "Value[%d]: %s " % ( iV, str( vectorsArray.GetTuple3( iV ) ) ) self.initialOrigin = self.input().GetOrigin() self.initialExtent = self.input().GetExtent() self.initialSpacing = self.input().GetSpacing() self.dataBounds = self.getUnscaledWorldExtent( self.initialExtent, self.initialSpacing, self.initialOrigin ) dataExtents = ( (self.dataBounds[1]-self.dataBounds[0])/2.0, (self.dataBounds[3]-self.dataBounds[2])/2.0, (self.dataBounds[5]-self.dataBounds[4])/2.0 ) centroid = ( (self.dataBounds[0]+self.dataBounds[1])/2.0, (self.dataBounds[2]+self.dataBounds[3])/2.0, (self.dataBounds[4]+self.dataBounds[5])/2.0 ) self.pos = [ self.initialSpacing[i]*self.initialExtent[2*i] for i in range(3) ] if ( (self.initialOrigin[0] + self.pos[0]) < 0.0): self.pos[0] = self.pos[0] + 360.0 self.resample = vtk.vtkExtractVOI() self.resample.SetInput( self.input() ) self.resample.SetVOI( self.initialExtent ) self.ApplyGlyphDecimationFactor() lut = self.getLut() if self.colorInputModule <> None: colorInput = self.colorInputModule.getOutput() self.color_resample = vtk.vtkExtractVOI() self.color_resample.SetInput( colorInput ) self.color_resample.SetVOI( self.initialExtent ) self.color_resample.SetSampleRate( sampleRate, sampleRate, 1 ) # self.probeFilter = vtk.vtkProbeFilter() # self.probeFilter.SetSourceConnection( self.resample.GetOutputPort() ) # colorInput = self.colorInputModule.getOutput() # self.probeFilter.SetInput( colorInput ) resampledColorInput = self.color_resample.GetOutput() shiftScale = vtk.vtkImageShiftScale() shiftScale.SetOutputScalarTypeToFloat () shiftScale.SetInput( resampledColorInput ) valueRange = self.getScalarRange() shiftScale.SetShift( valueRange[0] ) shiftScale.SetScale ( (valueRange[1] - valueRange[0]) / 65535 ) colorFloatInput = shiftScale.GetOutput() colorFloatInput.Update() colorInput_pointData = colorFloatInput.GetPointData() self.colorScalars = colorInput_pointData.GetScalars() self.colorScalars.SetName('color') lut.SetTableRange( valueRange ) self.glyph = vtk.vtkGlyph3DMapper() # if self.colorInputModule <> None: self.glyph.SetColorModeToColorByScalar() # else: self.glyph.SetColorModeToColorByVector() scalarRange = self.getScalarRange() self.glyph.SetScaleModeToScaleByMagnitude() self.glyph.SetColorModeToMapScalars() self.glyph.SetUseLookupTableScalarRange(1) self.glyph.SetOrient( 1 ) # self.glyph.ClampingOn() self.glyph.SetRange( scalarRange[0:2] ) self.glyph.SetInputConnection( self.resample.GetOutputPort() ) self.arrow = vtk.vtkArrowSource() self.glyph.SetSourceConnection( self.arrow.GetOutputPort() ) self.glyph.SetLookupTable( lut ) self.glyphActor = vtk.vtkActor() self.glyphActor.SetMapper( self.glyph ) self.renderer.AddActor( self.glyphActor ) self.renderer.SetBackground( VTK_BACKGROUND_COLOR[0], VTK_BACKGROUND_COLOR[1], VTK_BACKGROUND_COLOR[2] ) self.set3DOutput(wmod=self.wmod)
def Execute(self): if self.Image == None: self.PrintError('Error: no Image.') cast = vtk.vtkImageCast() cast.SetInputData(self.Image) cast.SetOutputScalarTypeToFloat() cast.Update() self.Image = cast.GetOutput() if self.NegateImage: scalarRange = self.Image.GetScalarRange() negate = vtk.vtkImageMathematics() negate.SetInputData(self.Image) negate.SetOperationToMultiplyByK() negate.SetConstantK(-1.0) negate.Update() shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputConnection(negate.GetOutputPort()) shiftScale.SetShift(scalarRange[1]+scalarRange[0]) shiftScale.SetOutputScalarTypeToFloat() shiftScale.Update() self.Image = shiftScale.GetOutput() if self.Interactive: if not self.vmtkRenderer: self.vmtkRenderer = vmtkscripts.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) if not self.ImageSeeder: self.ImageSeeder = vmtkscripts.vmtkImageSeeder() self.ImageSeeder.vmtkRenderer = self.vmtkRenderer self.ImageSeeder.Image = self.Image self.ImageSeeder.Display = 0 self.ImageSeeder.Execute() ##self.ImageSeeder.Display = 1 self.ImageSeeder.BuildView() if not self.SurfaceViewer: self.SurfaceViewer = vmtkscripts.vmtkSurfaceViewer() self.SurfaceViewer.vmtkRenderer = self.vmtkRenderer initializationMethods = { '0': self.CollidingFrontsInitialize, '1': self.FastMarchingInitialize, '2': self.ThresholdInitialize, '3': self.IsosurfaceInitialize, '4': self.SeedInitialize } endInitialization = False while not endInitialization: queryString = 'Please choose initialization type: \n 0: colliding fronts;\n 1: fast marching;\n 2: threshold;\n 3: isosurface;\n 4: seed\n ' initializationType = self.InputText(queryString,self.InitializationTypeValidator) initializationMethods[initializationType]() self.DisplayLevelSetSurface(self.InitialLevelSets) queryString = 'Accept initialization? (y/n): ' inputString = self.InputText(queryString,self.YesNoValidator) if inputString == 'y': self.MergeLevelSets() self.DisplayLevelSetSurface(self.MergedInitialLevelSets) queryString = 'Initialize another branch? (y/n): ' inputString = self.InputText(queryString,self.YesNoValidator) if inputString == 'y': endInitialization = False elif inputString == 'n': endInitialization = True self.InitialLevelSets = self.MergedInitialLevelSets self.MergedInitialLevelSets = None else: if self.Method == "collidingfronts": self.CollidingFrontsInitialize() elif self.Method == "fastmarching": self.FastMarchingInitialize() elif self.Method == "threshold": self.ThresholdInitialize() elif self.Method == "isosurface": self.IsosurfaceInitialize() elif self.Method == "seeds": self.SeedInitialize() if self.OwnRenderer: self.vmtkRenderer.Deallocate()
def CollidingFrontsInitialize(self): self.PrintLog('Colliding fronts initialization.') seedIds1 = vtk.vtkIdList() seedIds2 = vtk.vtkIdList() if self.Interactive: queryString = "Please input lower threshold (\'n\' for none): " self.LowerThreshold = self.ThresholdInput(queryString) queryString = "Please input upper threshold (\'n\' for none): " self.UpperThreshold = self.ThresholdInput(queryString) queryString = 'Please place two seeds' seeds = self.SeedInput(queryString,2) seedIds1.InsertNextId(self.Image.FindPoint(seeds.GetPoint(0))) seedIds2.InsertNextId(self.Image.FindPoint(seeds.GetPoint(1))) else: seedIds1.InsertNextId(self.Image.ComputePointId([self.SourcePoints[0],self.SourcePoints[1],self.SourcePoints[2]])) seedIds2.InsertNextId(self.Image.ComputePointId([self.TargetPoints[0],self.TargetPoints[1],self.TargetPoints[2]])) scalarRange = self.Image.GetScalarRange() thresholdedImage = self.Image if (self.LowerThreshold is not None) | (self.UpperThreshold is not None): threshold = vtk.vtkImageThreshold() threshold.SetInputData(self.Image) if (self.LowerThreshold is not None) & (self.UpperThreshold is not None): threshold.ThresholdBetween(self.LowerThreshold,self.UpperThreshold) elif (self.LowerThreshold is not None): threshold.ThresholdByUpper(self.LowerThreshold) elif (self.UpperThreshold is not None): threshold.ThresholdByLower(self.UpperThreshold) threshold.ReplaceInOff() threshold.ReplaceOutOn() threshold.SetOutValue(scalarRange[0] - scalarRange[1]) threshold.Update() scalarRange = threshold.GetOutput().GetScalarRange() thresholdedImage = threshold.GetOutput() scale = 1.0 if scalarRange[1]-scalarRange[0] > 0.0: scale = 1.0 / (scalarRange[1]-scalarRange[0]) shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputData(thresholdedImage) shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(scale) shiftScale.SetOutputScalarTypeToFloat() shiftScale.Update() speedImage = shiftScale.GetOutput() collidingFronts = vtkvmtk.vtkvmtkCollidingFrontsImageFilter() collidingFronts.SetInputData(speedImage) collidingFronts.SetSeeds1(seedIds1) collidingFronts.SetSeeds2(seedIds2) collidingFronts.ApplyConnectivityOn() collidingFronts.StopOnTargetsOn() collidingFronts.Update() subtract = vtk.vtkImageMathematics() subtract.SetInputConnection(collidingFronts.GetOutputPort()) subtract.SetOperationToAddConstant() subtract.SetConstantC(-10.0 * collidingFronts.GetNegativeEpsilon()) subtract.Update() self.InitialLevelSets = vtk.vtkImageData() self.InitialLevelSets.DeepCopy(subtract.GetOutput()) self.IsoSurfaceValue = 0.0
def FastMarchingInitialize(self): self.PrintLog('Fast marching initialization.') sourceSeedIds = vtk.vtkIdList() targetSeedIds = vtk.vtkIdList() if self.Interactive: queryString = "Please input lower threshold (\'n\' for none): " self.LowerThreshold = self.ThresholdInput(queryString) queryString = "Please input upper threshold (\'n\' for none): " self.UpperThreshold = self.ThresholdInput(queryString) queryString = 'Please place source seeds' sourceSeeds = self.SeedInput(queryString,0) queryString = 'Please place target seeds' targetSeeds = self.SeedInput(queryString,0) for i in range(sourceSeeds.GetNumberOfPoints()): sourceSeedIds.InsertNextId(self.Image.FindPoint(sourceSeeds.GetPoint(i))) for i in range(targetSeeds.GetNumberOfPoints()): targetSeedIds.InsertNextId(self.Image.FindPoint(targetSeeds.GetPoint(i))) else: for i in range(len(self.SourcePoints)/3): sourceSeedIds.InsertNextId(self.Image.ComputePointId([self.SourcePoints[3*i+0],self.SourcePoints[3*i+1],self.SourcePoints[3*i+2]])) for i in range(len(self.TargetPoints)/3): targetSeedIds.InsertNextId(self.Image.ComputePointId([self.TargetPoints[3*i+0],self.TargetPoints[3*i+1],self.TargetPoints[3*i+2]])) scalarRange = self.Image.GetScalarRange() thresholdedImage = self.Image if (self.LowerThreshold is not None) | (self.UpperThreshold is not None): threshold = vtk.vtkImageThreshold() threshold.SetInputData(self.Image) if (self.LowerThreshold is not None) & (self.UpperThreshold is not None): threshold.ThresholdBetween(self.LowerThreshold,self.UpperThreshold) elif (self.LowerThreshold is not None): threshold.ThresholdByUpper(self.LowerThreshold) elif (self.UpperThreshold is not None): threshold.ThresholdByLower(self.UpperThreshold) threshold.ReplaceInOff() threshold.ReplaceOutOn() threshold.SetOutValue(scalarRange[0] - scalarRange[1]) threshold.Update() scalarRange = threshold.GetOutput().GetScalarRange() thresholdedImage = threshold.GetOutput() scale = 1.0 if scalarRange[1]-scalarRange[0] > 0.0: scale = 1.0 / (scalarRange[1]-scalarRange[0]) shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputData(thresholdedImage) shiftScale.SetShift(-scalarRange[0]) shiftScale.SetScale(scale) shiftScale.SetOutputScalarTypeToFloat() shiftScale.Update() speedImage = shiftScale.GetOutput() fastMarching = vtkvmtk.vtkvmtkFastMarchingUpwindGradientImageFilter() fastMarching.SetInputData(speedImage) fastMarching.SetSeeds(sourceSeedIds) fastMarching.GenerateGradientImageOff() fastMarching.SetTargetOffset(100.0) fastMarching.SetTargets(targetSeedIds) if targetSeedIds.GetNumberOfIds() > 0: fastMarching.SetTargetReachedModeToOneTarget() else: fastMarching.SetTargetReachedModeToNoTargets() fastMarching.Update() subtract = vtk.vtkImageMathematics() subtract.SetInputConnection(fastMarching.GetOutputPort()) subtract.SetOperationToAddConstant() subtract.SetConstantC(-fastMarching.GetTargetValue()) subtract.Update() self.InitialLevelSets = vtk.vtkImageData() self.InitialLevelSets.DeepCopy(subtract.GetOutput()) self.IsoSurfaceValue = 0.0