def resize(self, newsize): """Resize the image resolution by specifying the number of pixels in width and height. If left to zero, it will be automatically calculated to keep the original aspect ratio. :param list,float newsize: shape of picture as [npx, npy], or as a fraction. """ old_dims = np.array(self._data.GetDimensions()) if not utils.isSequence(newsize): newsize = (old_dims * newsize + 0.5).astype(int) if not newsize[1]: ar = old_dims[1]/old_dims[0] newsize = [newsize[0], int(newsize[0]*ar+0.5)] if not newsize[0]: ar = old_dims[0]/old_dims[1] newsize = [int(newsize[1]*ar+0.5), newsize[1]] newsize = [newsize[0], newsize[1], old_dims[2]] rsz = vtk.vtkImageResize() rsz.SetInputData(self._data) rsz.SetResizeMethodToOutputDimensions() rsz.SetOutputDimensions(newsize) rsz.Update() out = rsz.GetOutput() out.SetSpacing(1,1,1) return self._update(out)
def setupImageProcessingPipeline(self): # Gaussian Smooth the image first # http://www.vtk.org/doc/nightly/html/classvtkImageGaussianSmooth.html self.noiseFilter = vtk.vtkImageGaussianSmooth() self.noiseFilter.SetStandardDeviation(1, 1, 1) self.noiseFilter.SetRadiusFactors(10, 10, 10) # Image Resize for resampler # http://www.vtk.org/doc/nightly/html/classvtkImageResize.html self.resampler = vtk.vtkImageResize() self.resampler.SetResizeMethodToMagnificationFactors() self.resampler.SetMagnificationFactors(1, 1, 1) self.resampler.BorderOn() self.resampler.SetInputConnection(self.noiseFilter.GetOutputPort()) # Marching cubes for iso value # http://www.vtk.org/doc/nightly/html/classvtkImageMarchingCubes.html self.marchingCubes = vtk.vtkImageMarchingCubes() self.marchingCubes.SetInputConnection(self.resampler.GetOutputPort()) self.marchingCubes.ComputeGradientsOn() self.marchingCubes.ComputeNormalsOn() self.marchingCubes.ComputeScalarsOn() self.marchingCubes.SetNumberOfContours(1) self.marchingCubes.SetValue(0, 0) # Create mapper and actor for renderer self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputConnection(self.marchingCubes.GetOutputPort()) self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) self.actor.GetProperty().SetInterpolationToGouraud()
def createVTKDataFromHDF(directory_mdf, count, interpolation, vtk_image_data_dimensions): f = h5py.File(str(directory_mdf), 'r') dset_size = f['reconstruction/size'] dset_data = f['reconstruction/data'] dset_FOV = f['reconstruction/fieldOfView'] imageData = vtk.vtkImageData() imageData.SetDimensions(dset_size[0], dset_size[1], dset_size[2]) imageData.AllocateScalars(vtk.VTK_DOUBLE, 1) imageData.SetSpacing(dset_FOV[0] / dset_size[0] * 1000, \ dset_FOV[1] / dset_size[1] * 1000, dset_FOV[2] / dset_size[2] *1000) data_array = np.array(dset_data[count, :, 0]) counter = 0 for z in range(dset_size[2]): for y in range(dset_size[1]): for x in range(dset_size[0]): imageData.SetScalarComponentFromDouble(x, y, z, 0, data_array[counter]) counter = counter + 1 if interpolation == True: resize = vtk.vtkImageResize() resize.SetInputData(imageData) resize.SetOutputDimensions(vtk_image_data_dimensions) resize.Update() imageData = resize.GetOutput() return imageData
def adjustSizeRm(self, dims, checkbox_rm): resizerm = vtk.vtkImageResize() resizerm.SetInputData(self.image_data_rm) resizerm.SetOutputDimensions(dims[0],dims[1],dims[2]) resizerm.Update() self.image_data_rm = resizerm.GetOutput() if checkbox_rm == True: self.volumeMapperRm.SetInputData(self.image_data_rm)
def resize(self, *newdims): """Increase or reduce the number of voxels of a Volume with interpolation.""" old_dims = np.array(self.imagedata().GetDimensions()) old_spac = np.array(self.imagedata().GetSpacing()) rsz = vtk.vtkImageResize() rsz.SetResizeMethodToOutputDimensions() rsz.SetInputData(self.imagedata()) rsz.SetOutputDimensions(newdims) rsz.Update() self._data = rsz.GetOutput() new_spac = old_spac * old_dims / newdims # keep aspect ratio self._data.SetSpacing(new_spac) return self._update(self._data)
def __init__(self, parent=None): # Defaults self.filename = "" self.gaussStandardDeviation = 1.2 self.gaussRadius = 2 self.magnification = 1 self.isosurface = 1 self.actorColor = [1.000, 0.000, 0.000] self.actorOpacity = 1.0 self.actorVisibility = 1 self.actorPickable = 1 self.pipelineType = "MarchingCubes" # In the future we could define other types of pipelines self.pipelineDataType = None self.actorAdded = False self.processing_log = None self.image_info = None # Elements of the VTK pipeline self.reader = None self.gauss = vtk.vtkImageGaussianSmooth() self.pad = vtk.vtkImageConstantPad() self.resampler = vtk.vtkImageResize() self.marchingCubes = vtk.vtkImageMarchingCubes() self.mapper = vtk.vtkPolyDataMapper() self.mapperDS = vtk.vtkDataSetMapper() self.actor = vtk.vtkActor() self.transformPolyData = vtk.vtkTransformPolyDataFilter() # The vtkTransform is part of the pipeline. The matrix defines the vtkTransform, but we # store a copy in self.matrix for retrieval later. self.rigidBodyTransform = vtk.vtkTransform() self.rigidBodyTransform.Identity() self.rigidBodyTransform.PostMultiply() # Important so that transform concatenations is correct! self.matrix = vtk.vtkMatrix4x4() self.dim = [1,1,1] self.pos = [0,0,0] self.el_size_mm = [0.082,0.082,0.082] self.extent = [0,1,0,1,0,1] self.origin = [0,0,0] self.validForExtrusion = False
def createVTKDataFromMHAFile(directory, count, interpolation, vtk_image_data_dimensions): name = createMHAFileName(directory, count) if os.path.isfile(name): imageReader = vtk.vtkMetaImageReader() imageReader.SetFileName(name) imageReader.Update() if interpolation == True: resize = vtk.vtkImageResize() resize.SetInputData(imageReader.GetOutput()) resize.SetOutputDimensions(vtk_image_data_dimensions) resize.Update() imageData1 = resize.GetOutput() else: imageData1 = imageReader.GetOutput() return imageData1
def get_image_actor(image_array, clim=None, actortype='vtkImageActor'): image = image_array.copy() if clim is None: if image.min() != image.max(): clim = [image.min(), image.max()] else: clim = [0, 255] clim = np.array(clim) # If the array isn't already 8-bit int, make it 8-bit int... if image.dtype != np.uint8: # If we're given a higher bit-depth integer, it's easy to downcast it. if image.dtype == np.uint16 or image.dtype == np.int16: image = np.uint8(image / 2**8) clim = np.uint8(clim / 2**8) elif image.dtype == np.uint32 or image.dtype == np.int32: image = np.uint8(image / 2**24) clim = np.uint8(clim / 2**24) elif image.dtype == np.uint64 or image.dtype == np.int64: image = np.uint8(image / 2**56) clim = np.uint8(clim / 2**24) # Otherwise, scale it in a floating point way to its own max & min # and strip out any transparency info (since we can't be sure of the scale used for transparency) else: if image.min() < 0: image = image - image.min() clim = clim - image.min() if len(image.shape) == 3: if image.shape[2] == 4: image = image[:, :, :-1] image = np.uint8(255. * (image - image.min()) / (image.max() - image.min())) vtk_im_importer = vtk.vtkImageImport() # Create a temporary floating point copy of the data, for scaling. # Also flip the data (vtk addresses y from bottom right) and put in display coords. image = np.float32(np.flipud(image)) clim = np.float32(clim) # Scale to colour limits and convert to uint8 for displaying. image -= clim[0] image /= (clim[1] - clim[0]) image *= 255. image = np.uint8(image) im_data_string = image.tostring() vtk_im_importer.CopyImportVoidPointer(im_data_string, len(im_data_string)) vtk_im_importer.SetDataScalarTypeToUnsignedChar() if len(image.shape) == 2: vtk_im_importer.SetNumberOfScalarComponents(1) else: vtk_im_importer.SetNumberOfScalarComponents(image.shape[2]) vtk_im_importer.SetDataExtent(0, image.shape[1] - 1, 0, image.shape[0] - 1, 0, 0) vtk_im_importer.SetWholeExtent(0, image.shape[1] - 1, 0, image.shape[0] - 1, 0, 0) if actortype == 'vtkImageActor': actor = vtk.vtkImageActor() actor.InterpolateOff() mapper = actor.GetMapper() mapper.SetInputConnection(vtk_im_importer.GetOutputPort()) return actor elif actortype == 'vtkActor2D': resizer = vtk.vtkImageResize() resizer.SetInputConnection(vtk_im_importer.GetOutputPort()) resizer.SetResizeMethodToOutputDimensions() resizer.SetOutputDimensions( (image_array.shape[1], image_array.shape[0], 1)) resizer.InterpolateOff() mapper = vtk.vtkImageMapper() mapper.SetInputConnection(resizer.GetOutputPort()) mapper.SetColorWindow(255) mapper.SetColorLevel(127.5) actor = vtk.vtkActor2D() actor.SetMapper(mapper) actor.GetProperty().SetDisplayLocationToForeground() return actor, resizer
def generate(self, target_reduction = 0.9994, num_subdivisions = 3, resize_factors = None, clipping_factor = 0.0): # Convert to VTI myArguments = 'vmtkimagereader -ifile ' + self.input_path my_pype = pypes.PypeRun(myArguments) vtk_image = my_pype.GetScriptObject('vmtkimagereader','0').Image # Size the image if needed if resize_factors is not None: reduction_filter = vtk.vtkImageResize() reduction_filter.SetInput(vtk_image) reduction_filter.SetMagnificationFactors(resize_factors[0], resize_factors[1], resize_factors[2]) reduction_filter.SetResizeMethodToMagnificationFactors() reduction_filter.Update() # Threshold threshold = vtk.vtkThreshold() if resize_factors is not None: threshold.SetInputConnection(reduction_filter.GetOutputPort()) else: threshold.SetInput(vtk_image) threshold.ThresholdByUpper(1.0) threshold.Update() # Convert to polydata surface = vtk.vtkGeometryFilter() surface.SetInputConnection(threshold.GetOutputPort()) surface.Update() # Triangulate triangle = vtk.vtkTriangleFilter() triangle.SetInputConnection(surface.GetOutputPort()) triangle.Update() # Decimate decimate = vtk.vtkDecimatePro() decimate.SetInputConnection(triangle.GetOutputPort()) decimate.SetTargetReduction(target_reduction) decimate.SetFeatureAngle(15.0) decimate.Update() # Do loop subdivision su = vtk.vtkLinearSubdivisionFilter() su.SetInputConnection(decimate.GetOutputPort()) su.SetNumberOfSubdivisions(num_subdivisions) su.Update() # Clip the boundaries, recommended to ensure straight inlets and outlets if clipping_factor > 0.0: bounds = su.GetOutput().GetBounds() width = bounds[1] - bounds[0] height = bounds[3] - bounds[2] print bounds[2], bounds[3], height p1 = vtk.vtkPlane() p1.SetOrigin(bounds[0] + clipping_factor*width, 0.0, 0) p1.SetNormal(1, 0, 0) p2 = vtk.vtkPlane() p2.SetOrigin(0.0, bounds[2] + clipping_factor*height, 0) p2.SetNormal(0, 1, 0) p3 = vtk.vtkPlane() p3.SetOrigin(bounds[1] - clipping_factor*width, 0.0, 0) p3.SetNormal(-1, 0, 0) p4 = vtk.vtkPlane() p4.SetOrigin(0.0, bounds[3] - clipping_factor*height, 0) p4.SetNormal(0, -1, 0) c1 = vtk.vtkClipPolyData() c1.SetInputConnection(su.GetOutputPort()) c1.SetClipFunction(p1) c1.SetValue(0.0) c2 = vtk.vtkClipPolyData() c2.SetInputConnection(c1.GetOutputPort()) c2.SetClipFunction(p2) c2.SetValue(0.0) # c3 = vtk.vtkClipPolyData() c3.SetInputConnection(c2.GetOutputPort()) c3.SetClipFunction(p3) c3.SetValue(0.0) c4 = vtk.vtkClipPolyData() c4.SetInputConnection(c3.GetOutputPort()) c4.SetClipFunction(p4) c4.SetValue(0.0) su = vtk.vtkGeometryFilter() su.SetInputConnection(c4.GetOutputPort()) su.Update() feature_edges = vtk.vtkFeatureEdges() feature_edges.SetInputConnection(su.GetOutputPort()) feature_edges.Update() clean = vtk.vtkCleanPolyData() clean.SetInputConnection(feature_edges.GetOutputPort()) clean.Update() triangle2 = vtk.vtkTriangleFilter() triangle2.SetInputConnection(clean.GetOutputPort()) triangle2.Update() self.surface = su.GetOutput() self.boundaries = triangle2.GetOutput() return su.GetOutput(), triangle2.GetOutput()
def get_vtkobjects(self, opacity=None): if self.data is None: raise Exception('No image data loaded!') ImageImporter = vtk.vtkImageImport() # Create a temporary floating point copy of the data, for scaling. # Also flip the data (vtk addresses y from bottom right) and put in display coords. Data = np.float32( np.flipud(self.transform.original_to_display_image(self.data))) clim = np.float32(self.clim) # Scale to colour limits and convert to uint8 for displaying. Data -= clim[0] Data /= (clim[1] - clim[0]) Data *= 255. Data = np.uint8(Data) if self.postprocessor is not None: Data = self.postprocessor(Data) if opacity is not None: Alpha = np.uint8(np.ones(Data.shape[:2]) * opacity * 255) Data = np.dstack([Data, Alpha]) if self.alpha is not None: Alpha = np.flipud( self.transform.original_to_display_image(self.alpha)) Data = np.dstack([Data, Alpha]) DataString = Data.tostring() ImageImporter.CopyImportVoidPointer(DataString, len(DataString)) ImageImporter.SetDataScalarTypeToUnsignedChar() if len(self.data.shape) == 2: ImageImporter.SetNumberOfScalarComponents(1) else: ImageImporter.SetNumberOfScalarComponents(Data.shape[2]) ImageImporter.SetDataExtent(0, Data.shape[1] - 1, 0, Data.shape[0] - 1, 0, 0) ImageImporter.SetWholeExtent(0, Data.shape[1] - 1, 0, Data.shape[0] - 1, 0, 0) Resizer = vtk.vtkImageResize() Resizer.SetInputConnection(ImageImporter.GetOutputPort()) Resizer.SetResizeMethodToOutputDimensions() Resizer.SetOutputDimensions((Data.shape[1], Data.shape[0], 1)) # jrh mod begin Resizer.InterpolateOff() mapper = vtk.vtkImageMapper() mapper.SetInputConnection(Resizer.GetOutputPort()) mapper.SetColorWindow(255) mapper.SetColorLevel(127.5) Actor = vtk.vtkActor2D() Actor.SetMapper(mapper) Actor.GetProperty().SetDisplayLocationToBackground() return Actor, Resizer
def __init__(self, input_file, gaussian, radius, thresh, zoom, zSlice, brightness, window_size, *args, **kwargs): """MainWindow constructor""" super().__init__(*args, **kwargs) # Window setup self.resize(window_size[0],window_size[1]) self.title = "Qt Viewer for Lesion Augmentation" self.statusBar().showMessage("Welcome.",8000) # Capture defaults self.gaussian = gaussian self.radius = radius self.thresh = thresh self.zoom = zoom self.brightness = brightness self.shape_dic = None self.lesion_dic = {} self.thresholdArray = None self.imageArray = None self.zSlice = 100 self.shape = None self.crop = None self.colorWindow = 1000 self.colorLevel = 500 # Initialize the window self.initUI() # Set up some VTK pipeline classes self.reader = None self.gauss = vtk.vtkImageGaussianSmooth() self.lesion = vtk.vtkImageData() self.threshold = vtk.vtkImageThreshold() self.mapToColors = vtk.vtkImageMapToColors() self.imageViewer = vtk.vtkImageViewer2() self.resizeImage = vtk.vtkImageResize() self.resizeSeg = vtk.vtkImageResize() self.contourRep = vtk.vtkOrientedGlyphContourRepresentation() self.contourWidget = vtk.vtkContourWidget() self.placer = vtk.vtkImageActorPointPlacer() self.polyData = None self.origmapper = vtk.vtkImageMapper()#vtkImageSliceMapper()# self.mapper = vtk.vtkImageMapper() self.stencilmapper = vtk.vtkPolyDataMapper() self.origactor = vtk.vtkActor2D() #vtkImageActor() self.actor = vtk.vtkActor2D() self.stencilactor = vtk.vtkActor() # Take inputs from command line. Only use these if there is an input file specified if (input_file != None): if (not os.path.exists(input_file)): qtw.QMessageBox.warning(self, "Error", "Invalid input file.") return self.createPipeline(input_file) self.statusBar().showMessage("Loading file " + input_file,4000) self.changeSigma(gaussian) self.changeRadius(radius) self.changeThreshold(thresh) self.changeBrightness(brightness) self.changeSlice(zSlice)
reader2.SetFileName(input2) reader2.GlobalWarningDisplayOff() #reader2.DataOnCellsOn() reader2.Update() shift = vtk.vtkImageShiftScale() shift.SetInputConnection(reader1.GetOutputPort()) shift.SetOutputScalarTypeToUnsignedChar() mask = vtk.vtkImageMask() mask.SetImageInput(reader2.GetOutput()) mask.SetMaskInput(shift.GetOutput()) mask.SetMaskedOutputValue(0) if peel_iter != 0: erode = vtk.vtkImageResize() erode.SetKernelSize(2 * peel_iter, 2 * peel_iter, 2 * peel_iter) erode.SetInputConnection(mask.GetOutputPort()) erode.Update() writer = vtkn88.vtkn88AIMWriter() writer.SetInputConnection(erode.GetOutputPort()) writer.SetFileName(output) #writer.SetAimOffset( offset[0], offset[1], offset[2] ) writer.Update() print "Writing: ", output else: writer = vtkn88.vtkn88AIMWriter() writer.SetInputConnection(mask.GetOutputPort())