def generate_tube_colormap(group): colormap = {} children = group.GetChildren(1) # recursive for idx in range(len(children)): child = itk.down_cast(children[idx]) colormap[child.GetId()] = [ c * 255 for c in child.GetProperty().GetColor() ] return colormap
def tubetree(self, roots): tubeGroup = self.segmenter.GetTubeGroup() conv = itk.ConvertTubesToTubeTree[3].New() conv.SetInput(tubeGroup) # TODO add roots, if len(roots) > 0 conv.SetMaxTubeDistanceToRadiusRatio(2) conv.SetMaxContinuityAngleError(180) conv.Update() children = conv.GetOutput().GetChildren(1) # recursive new_parent_ids = [] for idx in range(len(children)): child = itk.down_cast(children[idx]) new_parent_ids.append((child.GetId(), child.GetParentId())) return new_parent_ids
def load_data(self, index=0): ReaderClass, image_io = self._find_loader() reader = ReaderClass.New() # Re-using the same ImageIO causes a memory leak ! image_io_clone = itk.down_cast(image_io.CreateAnother()) reader.SetImageIO(image_io_clone) reader.SetFileName(self._filename) reader.Update() if reader.GetNameOfClass() == "ImageFileReader": array = itk_image_to_array(reader.GetOutput(), True) else: array = reader.GetArray() if image_io.GetNameOfClass() == "NiftiImageIO": data_type = image_io.GetPixelTypeAsString(image_io.GetPixelType()) if array.ndim == 4 and data_type == "scalar": # Make sure to /NOT/ use a view, which uses too much memory array = array[index].copy() return array
def __init__(self, imageOrFilter, Label=False, Title=None): import tempfile import itk import os import platform # get some data from the environment command = os.environ.get("WRAPITK_SHOW2D_COMMAND") if command is None: if platform.system() == "Darwin": command = ( "open -a ImageJ -n --args -eval 'open(\"%(image)s\"); " "run (\"View 100%%\"); rename(\"%(title)s\");'") else: command = ( "imagej %(image)s -run 'View 100%%' -eval " "'rename(\"%(title)s\")' &") label_command = os.environ.get("WRAPITK_SHOW2D_LABEL_COMMAND") if label_command is None: if platform.system() == "Darwin": label_command = ( "open -a ImageJ -n --args -eval 'open(\"%(image)s\"); " "run (\"View 100%%\"); rename(\"%(title)s\"); " "run(\"3-3-2 RGB\");'") else: label_command = ( "imagej %(image)s -run 'View 100%%' -eval " "'rename(\"%(title)s\")' -run '3-3-2 RGB' &") compress = os.environ.get( "WRAPITK_SHOW2D_COMPRESS", "true").lower() in ["on", "true", "yes", "1"] extension = os.environ.get("WRAPITK_SHOW2D_EXTENSION", ".tif") # use the tempfile module to get a non used file name and to put # the file at the rignt place self.__tmpFile__ = tempfile.NamedTemporaryFile(suffix=extension) # get an updated image img = output(imageOrFilter) img.UpdateOutputInformation() img.Update() if Title is None: # try to generate a title s = img.GetSource() if s: s = itk.down_cast(s) if hasattr(img, "GetSourceOutputIndex"): o = '[%s]' % img.GetSourceOutputIndex() elif hasattr(img, "GetSourceOutputName"): o = '[%s]' % img.GetSourceOutputName() else: o = "" Title = "%s%s" % (s.__class__.__name__, o) else: Title = img.__class__.__name__ try: import IPython ip = IPython.get_ipython() if ip is not None: names = [] ref = imageOrFilter if s: ref = s for n, v in ip.user_ns.iteritems(): if isinstance(v, itk.LightObject) and v == ref: names.append(n) if names != []: Title = ", ".join(names) + " - " + Title except ImportError: # just do nothing pass # change the LabelMaps to an Image, so we can look at them easily if 'LabelMap' in dir(itk) and img.GetNameOfClass() == 'LabelMap': # retreive the biggest label in the label map maxLabel = img.GetNthLabelObject( img.GetNumberOfLabelObjects() - 1).GetLabel() # search for a filter to convert the label map lab = itk.LabelMapToLabelImageFilter.keys() maxVal = itk.NumericTraits[itk.template(params[1])[1][0]].max() cond = params[0] == class_(img) and maxVal >= maxLabel label_image_type = sorted([params[1] for params in lab if cond])[0] convert = itk.LabelMapToLabelImageFilter[ img, label_image_type].New(img) convert.Update() img = convert.GetOutput() # this is a label image - force the parameter Label = True write(img, self.__tmpFile__.name, compress) # now run imview import os if Label: os.system( label_command % {"image": self.__tmpFile__.name, "title": Title}) else: os.system( command % {"image": self.__tmpFile__.name, "title": Title})
itk.meshwrite(mesh, sys.argv[4], compression=True) # test search res = itk.search("Index") assert res[0] == "Index" assert res[1] == "index" assert "ContinuousIndex" in res res = itk.search("index", True) assert "Index" not in res # test down_cast obj = itk.Object.cast(reader) # be sure that the reader is casted to itk::Object assert obj.__class__ == itk.Object down_casted = itk.down_cast(obj) assert down_casted == reader assert down_casted.__class__ == ReaderType # test setting the IO manually png_io = itk.PNGImageIO.New() assert png_io.GetFileName() == "" reader = itk.ImageFileReader.New(FileName=filename, ImageIO=png_io) reader.Update() assert png_io.GetFileName() == filename # test reading image series series_reader = itk.ImageSeriesReader.New(FileNames=[filename, filename]) series_reader.Update() assert series_reader.GetOutput().GetImageDimension() == 3 assert series_reader.GetOutput().GetLargestPossibleRegion().GetSize()[2] == 2
# test search res = itk.search("Index") assert res[0] == "Index" assert res[1] == "index" assert "ContinuousIndex" in res res = itk.search("index", True) assert "Index" not in res # test down_cast obj = itk.Object.cast(reader) # be sure that the reader is casted to itk::Object assert obj.__class__ == itk.Object down_casted = itk.down_cast(obj) assert down_casted == reader assert down_casted.__class__ == ReaderType # test setting the IO manually png_io = itk.PNGImageIO.New() assert png_io.GetFileName() == '' reader=itk.ImageFileReader.New(FileName=fileName, ImageIO=png_io) reader.Update() assert png_io.GetFileName() == fileName # test reading image series series_reader = itk.ImageSeriesReader.New(FileNames=[fileName,fileName]) series_reader.Update() assert series_reader.GetOutput().GetImageDimension() == 3 assert series_reader.GetOutput().GetLargestPossibleRegion().GetSize()[2] == 2
parameter_map = parameters.GetDefaultParameterMap('translation', 2) parameters.WriteParameterFile(parameter_map, prefix + "translation.default.txt") parameters.AddParameterMap(parameter_map) parameters.SetParameter("ResultImageFormat", "mha") parameter_map = parameters.GetDefaultParameterMap('affine', 1) parameters.WriteParameterFile(parameter_map, prefix + "affine.default.txt") parameters.AddParameterMap(parameter_map) parameters.RemoveParameter("WriteResultImage") assert (parameters.GetNumberOfParameterMaps() is 2) parameter_map = parameters.GetParameterMap(0) parameters.WriteParameterFile(parameter_map, prefix + "translation.set.txt") parameter_map = parameters.GetParameterMap(1) parameters.WriteParameterFile(parameter_map, prefix + "affine.set.txt") fixed = itk.imread(fixed_filename, itk.F) moving = itk.imread(moving_filename, itk.F) if output_parameter_files: registered, transform = itk.elastix_registration_method( fixed, moving, parameter_object=parameters) else: registered, transform = itk.elastix_registration_method(fixed, moving) itk.imwrite(itk.down_cast(registered), result_filename) print(transform)
def to_point_set(point_set_like): # noqa: C901 if isinstance(point_set_like, itk.PointSet): if not hasattr(itk, 'PyVectorContainer'): raise ImportError( 'itk.MeshToPolyDataFilter is not available -- install the itk-meshtopolydata package' ) itk_polydata = itk.mesh_to_poly_data_filter(point_set_like) point_set = {'vtkClass': 'vtkPolyData'} points = itk_polydata.GetPoints() point_template = itk.template(points) element_type = point_template[1][1] # todo: test array_view here and below point_values = itk.PyVectorContainer[ element_type].array_from_vector_container(points) if len(point_values.shape) > 1 and point_values.shape[ 1] == 2 or point_values.shape[1] == 3: if point_values.shape[1] == 2: point_values = np.hstack((point_values, -5.0e-6 * np.ones( (point_values.shape[0], 1)))).astype(np.float32) points = { 'vtkClass': 'vtkPoints', 'numberOfComponents': 3, 'dataType': 'Float32Array', 'size': point_values.size, 'values': point_values } point_set['points'] = points else: return None itk_point_data = itk_polydata.GetPointData() if itk_point_data and itk_point_data.Size(): pixel_type = itk.template(itk_polydata)[1][0] data_type, number_of_components = _itk_pixel_to_vtkjs_type_components[ pixel_type] data = itk.PyVectorContainer[ pixel_type].array_from_vector_container(itk_point_data) point_data = { "vtkClass": "vtkDataSetAttributes", "activeScalars": 0, "arrays": [{ "data": { 'vtkClass': 'vtkDataArray', 'name': 'Point Data', 'numberOfComponents': number_of_components, 'size': data.size, 'dataType': data_type, 'values': data } }], } point_set['pointData'] = point_data return point_set elif isinstance(point_set_like, itk.GroupSpatialObject): children = point_set_like.GetChildren() point_set = {'vtkClass': 'vtkPolyData'} points_list = [] for ii in range(len(children)): child = children[ii] down_casted = itk.down_cast(child) if isinstance(down_casted, itk.PointBasedSpatialObject): n_points = down_casted.GetNumberOfPoints() for ii in range(n_points): point = down_casted.GetPoint(ii) point.SetSpatialObject(down_casted) position = point.GetPositionInWorldSpace() points_list.append(list(position)) return _numpy_array_to_point_set(points_list) elif is_arraylike(point_set_like): return _numpy_array_to_point_set(point_set_like) elif have_vtk and isinstance(point_set_like, vtk.vtkPolyData): from vtk.util.numpy_support import vtk_to_numpy point_set = {'vtkClass': 'vtkPolyData'} points_data = vtk_to_numpy(point_set_like.GetPoints().GetData()) points_data = points_data.astype(np.float32).ravel() points = { 'vtkClass': 'vtkPoints', 'name': '_points', 'numberOfComponents': 3, 'dataType': 'Float32Array', 'size': points_data.size, 'values': points_data } point_set['points'] = points vtk_verts = point_set_like.GetVerts() if vtk_verts.GetNumberOfCells(): data = vtk_to_numpy(vtk_verts.GetData()) data = data.astype(np.uint32).ravel() cells = { 'vtkClass': 'vtkCellArray', 'name': '_' + 'verts', 'numberOfComponents': 1, 'size': data.size, 'dataType': 'Uint32Array', 'values': data } point_set['verts'] = cells vtk_point_data = point_set_like.GetPointData() if vtk_point_data and vtk_point_data.GetNumberOfArrays(): vtkjs_point_data = _vtk_data_attributes_to_vtkjs(vtk_point_data) point_set['pointData'] = vtkjs_point_data vtk_cell_data = point_set_like.GetCellData() if vtk_cell_data and vtk_cell_data.GetNumberOfArrays(): vtkjs_cell_data = _vtk_data_attributes_to_vtkjs(vtk_cell_data) point_set['cellData'] = vtkjs_cell_data return point_set elif isinstance(point_set_like, zarr.Group): return zarr_to_vtkjs(point_set_like) return None