def Execute(self): if (self.Mesh == None): self.PrintError('Error: no Mesh.') if not self.Matrix4x4: self.Matrix4x4 = vtk.vtkMatrix4x4() if self.MatrixCoefficients != []: self.PrintLog('Setting up transform matrix using specified coefficients') self.Matrix4x4.DeepCopy(self.MatrixCoefficients) elif self.Translation != [0.0,0.0,0.0] or self.Rotation != [0.0,0.0,0.0] or self.Scaling != [1.0,1.0,1.0]: self.PrintLog('Setting up transform matrix using specified translation, rotation and/or scaling') transform = vtk.vtkTransform() transform.RotateX(self.Rotation[0]) transform.RotateY(self.Rotation[1]) transform.RotateZ(self.Rotation[2]) transform.Translate(self.Translation[0], self.Translation[1], self.Translation[2]) transform.Scale(self.Scaling[0], self.Scaling[1], self.Scaling[2]) self.Matrix4x4.DeepCopy(transform.GetMatrix()) if self.InvertMatrix: self.Matrix4x4.Invert() transform = vtk.vtkMatrixToLinearTransform() transform.SetInput(self.Matrix4x4) transformFilter = vtk.vtkTransformFilter() transformFilter.SetInputData(self.Mesh) transformFilter.SetTransform(transform) transformFilter.Update() self.Mesh = transformFilter.GetOutput()
def set_matrix(self, registration_mat): print "VTKSurface.set_matrix(", registration_mat, ")!!" def vtkmatrix4x4_to_array(vtkmat): scipy_array = zeros((4,4), 'd') for i in range(0,4): for j in range(0,4): scipy_array[i][j] = mat.GetElement(i,j) return scipy_array def array_to_vtkmatrix4x4(scipy_array): mat = vtk.vtkMatrix4x4() for i in range(0,4): for j in range(0,4): mat.SetElement(i,j, scipy_array[i][j]) return mat #print "calling SetUserMatrix(", array_to_vtkmatrix4x4(registration_mat) , ")" mat = array_to_vtkmatrix4x4(registration_mat) mat.Modified() mat2xform = vtk.vtkMatrixToLinearTransform() mat2xform.SetInput(mat) print "calling SetUserTransform(", mat2xform, ")" self.SetUserTransform(mat2xform) # see vtk Prop3d docs self.Modified() # how do we like update the render tree or somethin.. self.renderer.Render()
def convert_to_vtk_transform(transform): """ Converts a Raysect AffineMatrix3D to an equivalent VTK vtkMatrixToLinearTransform. :param AffineMatrix3D transform: The Raysect transform matrix to be converted to VTK format. :rtype: vtk.vtkMatrixToLinearTransform """ # linear transform matrix t1 = vtk.vtkMatrixToLinearTransform() m1 = vtk.vtkMatrix4x4() t1.SetInput(m1) m1.SetElement(0, 0, transform[0, 0]) m1.SetElement(0, 1, transform[0, 1]) m1.SetElement(0, 2, transform[0, 2]) m1.SetElement(0, 3, transform[0, 3]) m1.SetElement(1, 0, transform[1, 0]) m1.SetElement(1, 1, transform[1, 1]) m1.SetElement(1, 2, transform[1, 2]) m1.SetElement(1, 3, transform[1, 3]) m1.SetElement(2, 0, transform[2, 0]) m1.SetElement(2, 1, transform[2, 1]) m1.SetElement(2, 2, transform[2, 2]) m1.SetElement(2, 3, transform[2, 3]) m1.SetElement(3, 0, transform[3, 0]) m1.SetElement(3, 1, transform[3, 1]) m1.SetElement(3, 2, transform[3, 2]) m1.SetElement(3, 3, transform[3, 3]) return t1
def set_matrix(self, registration_mat): if debug: print "VTKSurface.set_matrix(", registration_mat, ")!!" def vtkmatrix4x4_to_array(vtkmat): scipy_array = zeros((4, 4), 'd') for i in range(0, 4): for j in range(0, 4): scipy_array[i][j] = mat.GetElement(i, j) return scipy_array def array_to_vtkmatrix4x4(scipy_array): mat = vtk.vtkMatrix4x4() for i in range(0, 4): for j in range(0, 4): mat.SetElement(i, j, scipy_array[i][j]) return mat #print "calling SetUserMatrix(", array_to_vtkmatrix4x4(registration_mat) , ")" mat = array_to_vtkmatrix4x4(registration_mat) mat.Modified() mat2xform = vtk.vtkMatrixToLinearTransform() mat2xform.SetInput(mat) if debug: print "calling SetUserTransform(", mat2xform, ")" self.SetUserTransform(mat2xform) # see vtk Prop3d docs self.Modified() # how do we like update the render tree or somethin.. self.renderer.Render()
def __init__(self): ''' Constructor ''' self.__OrientationMatrix = vtk.vtkMatrix4x4() self.__CornerAnnotation = vtk.vtkCornerAnnotation() self.__TextProperty = vtk.vtkTextProperty() self.__LookupTable = vtk.vtkLookupTable() self.__ScalarBarActor = vtk.vtkScalarBarActor() self.__Prop3DCollection = vtk.vtkProp3DCollection() self.__DataSetCollection = vtk.vtkDataSetCollection() self.__OrientationTransform = vtk.vtkMatrixToLinearTransform() self.__OrientationMatrix.Identity() self.__CornerAnnotation.SetNonlinearFontScaleFactor(0.30) self.__CornerAnnotation.SetText(0, "Jolly - (c) summit 2009 ref vtkINRIA3D") self.__CornerAnnotation.SetMaximumFontSize(46) self.__ScalarBarActor.SetLabelTextProperty(self.__TextProperty) self.__ScalarBarActor.GetLabelTextProperty().BoldOff() self.__ScalarBarActor.GetLabelTextProperty().ItalicOff() self.__ScalarBarActor.SetNumberOfLabels(3) self.__ScalarBarActor.SetWidth(0.1) self.__ScalarBarActor.SetHeight(0.5) self.__ScalarBarActor.SetPosition(0.9, 0.3) self.__LookupTable.SetTableRange(0, 1) self.__LookupTable.SetSaturationRange(0, 0) self.__LookupTable.SetHueRange(0, 0) self.__LookupTable.SetValueRange(0, 1) self.__LookupTable.Build() self.__ShowAnnotations = True self.__ShowScalarBar = True self.__OrientationTransform.SetInput(self.__OrientationMatrix) self.__WindowLevel = self.GetWindowLevel() self.__WindowLevel.SetLookupTable( self.__LookupTable ) self.__ScalarBarActor.SetLookupTable(self.__LookupTable) self.__Renderer = self.GetRenderer() self.__Renderer.AddViewProp(self.__CornerAnnotation) self.__Renderer.AddViewProp(self.__ScalarBarActor) self.__ImageActor = self.GetImageActor() self.__RenderWindow = self.GetRenderWindow () self.__InteractorStyle = self.GetInteractorStyle() self.__Interactor = None self.__CornerAnnotation.SetWindowLevel(self.__WindowLevel) self.__CornerAnnotation.SetImageActor(self.__ImageActor) self.__CornerAnnotation.ShowSliceAndImageOn() # Sometime we would want to set the default window/level value instead # of the ImageData's ScalarRange self.__RefWindow = None self.__RefLevel = None
def Update(self): if shared.debug: print "Loading ", self.__filename self.__nim=load(self.__filename) if shared.debug: print self.__nim self.__data=self.__nim.get_data().astype("f").swapaxes(0,2) #self.__vtkimport.SetDataExtent(0,self.__data.shape[2]-1,0,self.__data.shape[1]-1,0,self.__data.shape[0]-1) self.__vtkimport.SetWholeExtent(0,self.__data.shape[2]-1,0,self.__data.shape[1]-1,0,self.__data.shape[0]-1) self.__vtkimport.SetDataExtentToWholeExtent() voxdim = self.__nim.get_header()['pixdim'][:3].copy() #Export data as string self.__data_string = self.__data.tostring() if shared.debug: print voxdim self.__vtkimport.SetDataSpacing((1.,1.,1.))#to reverse: [::-1] self.__vtkimport.CopyImportVoidPointer(self.__data_string,len(self.__data_string)) self.__vtkimport.UpdateWholeExtent() imgData1 = self.__vtkimport.GetOutput() imgData1.SetExtent(self.__vtkimport.GetDataExtent()) imgData1.SetOrigin((0,0,0)) imgData1.SetSpacing(1.,1.,1.) #print imgData1 #print self._irs #self._irs.SetInputConnection(self.__vtkimport.GetOutputPort()) self._irs.SetInput(imgData1) #print self._irs self._irs.SetInterpolationModeToCubic() #self._irs.AutoCropOutputOn() affine = array_to_vtkmatrix4x4(self.__nim.get_affine()) if shared.debug: print self._irs.GetResliceAxesOrigin() self._irs.SetResliceAxes(affine) if shared.debug: print self._irs.GetResliceAxesOrigin() m2t = vtk.vtkMatrixToLinearTransform() m2t.SetInput(affine.Invert()) self._irs.TransformInputSamplingOff() self._irs.SetResliceTransform(m2t.MakeTransform()) #self._irs.SetResliceAxesOrigin((0.,0.,0.)) #self.__vtkimport.GetOutput().GetOrigin()) #print self.__vtkimport.GetOutput().GetBounds() #print self._irs.GetOutput().GetBounds() if shared.debug: print voxdim, self._irs.GetOutputSpacing() self._irs.SetOutputSpacing(abs(voxdim)) if shared.debug: print self._irs.GetOutputSpacing() #print self._irs.GetOutputOrigin() #self._irs.SetOutputOrigin((0,0,0)) # print self._irs.GetOutputOrigin() #m2t_i.DeepCopy(m2t); #m2t_i = affine_i.Invert(); #m2t_i.MultiplyPoint(); #self._irs.SetOutputOrigin(self.__nim.get_affine()[:3,-1]) #self._irs.SetOutputExtent(self.__vtkimport.GetDataExtent()) self._irs.AutoCropOutputOn() self._irs.Update()
def set_matrix(self, registration_mat): print "VTKSurface.set_matrix(", registration_mat, ")!!" #print "calling SetUserMatrix(", array_to_vtkmatrix4x4(registration_mat) , ")" mat = array_to_vtkmatrix4x4(registration_mat) mat.Modified() mat2xform = vtk.vtkMatrixToLinearTransform() mat2xform.SetInput(mat) print "calling SetUserTransform(", mat2xform, ")" self.SetUserTransform(mat2xform) # see vtk Prop3d docs self.Modified() # how do we like update the render tree or somethin.. self.renderer.Render()
def Execute(self): if len(self.Points) % 3 != 0: self.PrintError('Error: Points not made up of triplets.') return matrix = vtk.vtkMatrix4x4() matrix.DeepCopy(self.MatrixCoefficients) if self.InvertMatrix: matrix.Invert() transform = vtk.vtkMatrixToLinearTransform() transform.SetInput(matrix) outputPoints = [] for i in range(len(self.Points)/3): point = [self.Points[3*i+0],self.Points[3*i+1],self.Points[3*i+2]] outputPoint = transform.TransformPoint(point) outputPoints.append(outputPoint) self.Points = outputPoints
# https://www.slicer.org/wiki/Documentation/Nightly/Modules/Transforms vtk.vtkMatrix4x4.Multiply4x4(lps2ras, trans_m, vtkmat) vtk.vtkMatrix4x4.Multiply4x4(vtkmat, ras2lps, vtkmat) # Convert from LPS (ITK) to RAS (Slicer) #vtk.vtkMatrix4x4.Multiply4x4(ras2lps, trans_m, vtkmat) #tk.vtkMatrix4x4.Multiply4x4(vtkmat, lps2ras, vtkmat) # Convert the sense of the transform (from ITK resampling to Slicer modeling transform) invert = vtk.vtkMatrix4x4() vtk.vtkMatrix4x4.Invert(vtkmat, invert) #print(invert) # linear transform matrix invert_lt = vtk.vtkMatrixToLinearTransform() invert_lt.SetInput(invert) pre = vtk.vtkTransform() pre.RotateZ(180) trans_1 = vtk.vtkTransform() trans_1.SetInput(invert_lt) trans_1.Concatenate(pre) trans_1.PreMultiply() # Does it do the matrix order = resize * trans_1 * pre trans_1.Update() print(trans_1.GetMatrix()) poly_filt = vtk.vtkTransformPolyDataFilter()
p6.SetOrigin(0.5, 0.5, 0.508) p6.SetPoint1(-0.5, 0.5, 0.508) p6.SetPoint2(0.5, -0.5, 0.508) p6.SetXResolution(5) p6.SetYResolution(5) # append together ap = vtk.vtkAppendPolyData() ap.AddInputConnection(p1.GetOutputPort()) ap.AddInputConnection(p2.GetOutputPort()) ap.AddInputConnection(p3.GetOutputPort()) ap.AddInputConnection(p4.GetOutputPort()) ap.AddInputConnection(p5.GetOutputPort()) ap.AddInputConnection(p6.GetOutputPort()) #-------------------------- # linear transform matrix t1 = vtk.vtkMatrixToLinearTransform() m1 = vtk.vtkMatrix4x4() t1.SetInput(m1) m1.SetElement(0, 0, 1.127631) m1.SetElement(0, 1, 0.205212) m1.SetElement(0, 2, -0.355438) m1.SetElement(1, 0, 0.000000) m1.SetElement(1, 1, 0.692820) m1.SetElement(1, 2, 0.400000) m1.SetElement(2, 0, 0.200000) m1.SetElement(2, 1, -0.469846) m1.SetElement(2, 2, 0.813798) f11 = vtk.vtkTransformPolyDataFilter() f11.SetInputConnection(ap.GetOutputPort()) f11.SetTransform(t1) m11 = vtk.vtkDataSetMapper()
p6.SetOrigin(0.5,0.5,0.508) p6.SetPoint1(-0.5,0.5,0.508) p6.SetPoint2(0.5,-0.5,0.508) p6.SetXResolution(5) p6.SetYResolution(5) # append together ap = vtk.vtkAppendPolyData() ap.AddInputConnection(p1.GetOutputPort()) ap.AddInputConnection(p2.GetOutputPort()) ap.AddInputConnection(p3.GetOutputPort()) ap.AddInputConnection(p4.GetOutputPort()) ap.AddInputConnection(p5.GetOutputPort()) ap.AddInputConnection(p6.GetOutputPort()) #-------------------------- # linear transform matrix t1 = vtk.vtkMatrixToLinearTransform() m1 = vtk.vtkMatrix4x4() t1.SetInput(m1) m1.SetElement(0,0,1.127631) m1.SetElement(0,1,0.205212) m1.SetElement(0,2,-0.355438) m1.SetElement(1,0,0.000000) m1.SetElement(1,1,0.692820) m1.SetElement(1,2,0.400000) m1.SetElement(2,0,0.200000) m1.SetElement(2,1,-0.469846) m1.SetElement(2,2,0.813798) f11 = vtk.vtkTransformPolyDataFilter() f11.SetInputConnection(ap.GetOutputPort()) f11.SetTransform(t1) m11 = vtk.vtkDataSetMapper()
def take_orthogonal_screenshots(image, center=None, length=0, offsets=None, size=(512, 512), prefix='screenshot_{n}', suffix=('axial', 'coronal', 'sagittal'), path_format='{prefix}_{suffix}', level_window=None, qform=None, polydata=[], colors=[], line_width=3, trim=False, overwrite=True): """Take three orthogonal screenshots of the given image patch. Arguments --------- image : vtkImageData Volume data. center : (float, float, float) or (int, int, int) vtkImageData coordinates or voxel indices (3-tuple of ints) of patch center point. Be sure to pass tuple with correct type. When not specified, the image center point is used. length : float or int Side length of patch either in mm (float) or number of voxels (int). offsets : list of float or int, optional One or more offsets in either mm (float) or number of voxels (int) from the center point along the orthogonal viewing direction. A screenshot of the volume of interest is taken for each combination of offset and orthgonal viewing direction, i.e., the number of screenshots is `3 * len(offset)`. For example, when the volume of interest is the entire image, i.e., `center=None` and `length=0`, this can be used to render multiple slices with one call of this function. size : (int, int) Either int or 2-tuple/-list of int values specifying the width and height of the screenshot. prefix : str Common output path prefix of screenshot files. suffix : (str, str, str) List or tuple of three strings used as suffix of the screenshot take from the respective orthogonal view. The order is: axial, coronal, sagittal. path_format: str A format string used to construct the file name of each individual screenshot. Make sure to use a suitable format string such that every screenshot has a unique file name. The allowed placeholders are: - `{prefix}`: Substituted by the `prefix` argument. - `{suffix}`: Substituted by the `suffix` argument corresponding to the orthogonal view. - `{n}`: The 1-based index of the screenshot. - `{i}`: The i (int) volume index of the screenshot center point before trimming. - `{j}`: The j (int) volume index of the screenshot center point before trimming. - `{k}`: The k (int) volume index of the screenshot center point before trimming. - `{x}`: The x (float) vtkImageData coordinates of the center point before trimming. - `{y}`: The y (float) vtkImageData coordinates of the center point before trimming. - `{z}`: The z (float) vtkImageData coordinates of the center point before trimming. - `{vi}`: The i (int) volume index of the viewport center point after trimming. - `{vj}`: The j (int) volume index of the viewport center point after trimming. - `{vk}`: The k (int) volume index of the viewport center point after trimming. - `{vx}`: The x (float) vtkImageData coordinates of the viewport center point after trimming. - `{vy}`: The y (float) vtkImageData coordinates of the viewport center point after trimming. - `{vz}`: The z (float) vtkImageData coordinates of the viewport center point after trimming. qform : vtkMatrix4x4, optional Homogeneous vtkImageData coordinates to world transformation matrix. For example, pass the vtkNIFTIImageReader.GetQFormMatrix(). level_window : (float, float), optional 2-tuple/-list of level and window color transfer function parameters. When not specified, the auto_level_window function with default percentiles is used to compute an intensity range that is robust to outliers. polydata : vtkPolyData, list, optional List of vtkPolyData objects to be cut by each orthogonal image slice plane and the contours rendered over the image. When a `qform` matrix is given, the points are transformed to image coordinates using the inverse of the `qform` matrix. colors : list, optional List of colors (3-tuples of float RGB values in [0, 1]) to use for each `polydata` contour. trim : bool, optional Whether to trim cropping region such that screenshot is contained within image bounds. overwrite : bool, optional Whether to overwrite existing output files. When this option is False, a screenshot is only taken when the output file does not exist. Returns ------- paths: list List of 6-tuples with parameters used to render each screenshot and the absolute file path of the written PNG image files. The number of screenshots is divisable by three, where the first `len(paths)/3` screenshots are taken from axial image slices, the next `len(paths)/3` screenshots are taken from coronal slices, and the last `len(paths)/3` screenshots are taken from sagittal slices. For each screenshot, the returned 6-tuple contains the following values: - path: Absolute path of PNG file. - zdir: Volume dimension corresponding to viewing direction. - center: 3-tuple of screenshot center voxel indices before trimming. - origin: 3-tuple of viewport center voxel indices after trimming. - size: 2-tuple of extracted slice width and height. - isnew: Whether image file was newly written or existed already. This value is always True when `overwrite=True`. """ if isinstance(size, int): size = (size, size) if not level_window: level_window = auto_level_window(image) if not suffix or len(suffix) != 3: raise Exception("suffix must be a tuple/list of three elements") suffix = list(suffix) suffix.reverse() origin = image.GetOrigin() spacing = image.GetSpacing() dims = image.GetDimensions() if os.path.splitext(path_format)[1] != '.png': path_format += '.png' if center and (isinstance(center[0], int) and isinstance(center[1], int) and isinstance(center[2], int)): index = center else: if not center: center = image.GetCenter() index = nearest_voxel(point_to_index(center, origin, spacing)) if not offsets: offsets = [0] elif isinstance(offsets, (int, float)): offsets = [offsets] if qform: linear_transform = vtk.vtkMatrixToLinearTransform() linear_transform.SetInput(invert_matrix(qform)) linear_transform.Update() else: linear_transform = None args = dict(polydata=polydata, transform=linear_transform, level_window=level_window, colors=colors, line_width=line_width) n = 0 screenshots = [] for zdir in (2, 1, 0): xdir, ydir = slice_axes(zdir) if isinstance(length, int): width = length height = length else: width = iround(length / spacing[xdir]) height = iround(length / spacing[ydir]) for offset in offsets: ijk = list(index) if isinstance(offset, int): ijk[zdir] += offset else: ijk[zdir] += iround(offset / spacing[zdir]) if ijk[zdir] < 0 or ijk[zdir] >= dims[zdir]: continue vox = list(ijk) if trim: bounds = cropping_region(vox, (xdir, ydir, zdir), width, height) if bounds[0] < 0: bounds[0] = 0 if bounds[1] >= dims[0]: bounds[1] = dims[0] - 1 if bounds[2] < 0: bounds[2] = 0 if bounds[3] >= dims[1]: bounds[3] = dims[1] - 1 if bounds[4] < 0: bounds[4] = 0 if bounds[5] >= dims[2]: bounds[5] = dims[2] - 1 dim = 2 * xdir width = (bounds[dim + 1] - bounds[dim]) vox[xdir] = bounds[dim] + width / 2 dim = 2 * ydir height = (bounds[dim + 1] - bounds[dim]) vox[ydir] = bounds[dim] + height / 2 renderer = slice_view(image, zdir=zdir, index=vox, width=width, height=height, **args) window = vtk.vtkRenderWindow() window.SetSize(size) window.AddRenderer(renderer) n += 1 xyz = index_to_point(ijk, origin, spacing) pos = index_to_point(vox, origin, spacing) path = os.path.abspath( path_format.format( n=n, prefix=prefix, suffix=suffix[zdir], vi=vox[0], vj=vox[1], vk=vox[2], vx=pos[0], vy=pos[1], vz=pos[2], i=ijk[0], j=ijk[1], k=ijk[2], x=xyz[0], y=xyz[1], z=xyz[2], )) if overwrite or not os.path.isfile(path): directory = os.path.dirname(path) if not os.path.isdir(directory): os.makedirs(directory) take_screenshot(window, path=path) isnew = True else: isnew = False screenshots.append((path, zdir, ijk, vox, (width, height), isnew)) renderer = None window = None return screenshots
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.Cast: cast = vtk.vtkImageCast() cast.SetInputData(self.Image) cast.SetOutputScalarTypeToFloat() cast.Update() self.Image = cast.GetOutput() resliceFilter = vtk.vtkImageReslice() resliceFilter.SetInputData(self.Image) if self.ReferenceImage: resliceFilter.SetInformationInput(self.ReferenceImage) else: if self.OutputSpacing: resliceFilter.SetOutputSpacing(self.OutputSpacing) if self.OutputOrigin: resliceFilter.SetOutputOrigin(self.OutputOrigin) if self.OutputExtent: resliceFilter.SetOutputExtent(self.OutputExtent) if self.Interpolation == 'nearestneighbor': resliceFilter.SetInterpolationModeToNearestNeighbor() elif self.Interpolation == 'linear': resliceFilter.SetInterpolationModeToLinear() elif self.Interpolation == 'cubic': resliceFilter.SetInterpolationModeToCubic() else: self.PrintError('Error: unsupported interpolation mode') resliceFilter.SetBackgroundLevel(self.BackgroundLevel) if self.TransformInputSampling: resliceFilter.TransformInputSamplingOn() else: resliceFilter.TransformInputSamplingOff() if not self.Matrix4x4: if self.MatrixCoefficients != []: self.PrintLog( 'Setting up transform matrix using specified coefficients') self.Matrix4x4 = vtk.vtkMatrix4x4() self.Matrix4x4.DeepCopy(self.MatrixCoefficients) elif self.Translation != [0.0, 0.0, 0.0] or self.Rotation != [ 0.0, 0.0, 0.0 ] or self.Scaling != [1.0, 1.0, 1.0]: self.PrintLog( 'Setting up transform matrix using specified translation, rotation and/or scaling' ) transform = vtk.vtkTransform() transform.RotateX(self.Rotation[0]) transform.RotateY(self.Rotation[1]) transform.RotateZ(self.Rotation[2]) transform.Translate(self.Translation[0], self.Translation[1], self.Translation[2]) transform.Scale(self.Scaling[0], self.Scaling[1], self.Scaling[2]) self.Matrix4x4 = vtk.vtkMatrix4x4() self.Matrix4x4.DeepCopy(transform.GetMatrix()) if self.InvertMatrix and self.Matrix4x4: self.Matrix4x4.Invert() if self.Matrix4x4: transform = vtk.vtkMatrixToLinearTransform() transform.SetInput(self.Matrix4x4) resliceFilter.SetResliceTransform(transform) resliceFilter.Update() self.Image = resliceFilter.GetOutput()
def take_screenshots_of_single_roi(args): # arguments args.database = os.path.abspath(args.database) base_dir = os.path.dirname(args.database) level_window = None # i.e., default if args.range: level_window = range_to_level_window(*args.range) # read intensity image image, qform = read_image(os.path.abspath(args.image)) image2world = vtkMatrixToLinearTransform() image2world.SetInput(qform) image2world.Update() world2image = image2world.GetLinearInverse() # with database connection open... db = sqlite3.connect(args.database) try: # pre-configure output path if args.scan > 0: scan_id = args.scan else: scan_id = get_scan_id(db, args.subject, args.session) if args.prefix: prefix = os.path.abspath(args.prefix) prefix = partial_format(prefix, subject=args.subject, session=args.session, scan=scan_id, roi=args.roi) else: prefix = os.path.join(base_dir, '-'.join([args.subject, args.session]), 'screenshots', 'roi-slices') path_format = args.path_format if not path_format: path_format = os.path.join( '{prefix}', 'roi-{roi:06d}-{n:02d}_idx-{i:03d}-{j:03d}-{k:03d}_{suffix}') path_format = partial_format(path_format, subject=args.subject, session=args.session, scan=scan_id, roi=args.roi) # get ROI parameters row = db.execute( "SELECT CenterX, CenterY, CenterZ, Span FROM ROIs WHERE ROI_Id = {}" .format(args.roi)).fetchone() center = [0, 0, 0] span = args.zoom * row[3] world2image.TransformPoint((row[0], row[1], row[2]), center) if len(args.offsets) > 0: offsets = args.offsets else: offsets = compute_offsets(span, args.subdiv) # collect information about overlays and read input files overlays = [] cur = db.cursor() try: for overlay in args.overlays: try: overlay_id = int(overlay[0]) overlay_name = get_overlay_name(cur, overlay_id) except ValueError: overlay_name = overlay[0] overlay_id = get_overlay_id(cur, overlay_name) overlays.append((overlay_id, overlay_name, read_surface(os.path.abspath(overlay[1])))) finally: cur.close() # choose colors if args.colors: colors = args.colors elif len(overlays) == 1: colors = [single_overlay_color] else: if args.use_all_colors: colors = list(multi_overlay_colors) else: colors = multi_overlay_colors[0:len(overlays)] if (len(overlays) > len(colors)): raise Exception( "Not enough different colors defined to render {} overlays" .format(len(overlays))) if args.shuffle_colors and len(colors) > 1: random.shuffle(colors) # take screenshots of orthogonal slices of ROI volume if args.all_overlays: if args.verbose > 0: print( "Take screenshots of orthogonal slices of ROI volume {} with all overlays" .format(args.roi)) screenshots = [] all_path_format = partial_format(path_format, o=0) try: screenshots = take_orthogonal_screenshots( image, level_window=level_window, qform=qform, prefix=prefix, suffix=args.suffix, path_format=all_path_format, center=center, length=span, offsets=offsets, polydata=[x[2] for x in overlays], colors=colors, line_width=args.line_width, size=args.size, overwrite=False) insert_screenshots(db, roi_id=args.roi, base=base_dir, screenshots=screenshots, overlays=[x[0] for x in overlays], colors=colors, verbose=(args.verbose - 1)) except BaseException as e: for screenshot in screenshots: path = screenshot[0] if os.path.isfile(path): os.remove(path) exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) raise (e) if args.verbose > 0: print( "Saved screenshots of orthogonal slices of ROI volume {} with all overlays" .format(args.roi)) # take screenshots of orthogonal slices of ROI volume with each colored contour alone # (this helps to identify whether two contours are simply identical or one has extra lines) if len(overlays) > 1 and args.individual_overlays: if args.verbose > 0: print( "Take screenshots of orthogonal slices of ROI volume {} with all overlays" .format(args.roi)) try: screenshots = [] for i in xrange(len(overlays)): suffix = [ '_'.join([str(overlays[i][0]), s]) for s in args.suffix ] if isinstance(args.line_width, int): line_width = args.line_width elif i < len(args.line_width): line_width = args.line_width[i] else: line_width = args.line_width[-1] screenshots = take_orthogonal_screenshots( image, level_window=level_window, qform=qform, prefix=prefix, suffix=suffix, path_format=path_format, center=center, length=span, offsets=offsets, polydata=[overlays[i][2]], colors=[colors[i]], line_width=line_width, size=args.size, overwrite=False) insert_screenshots(db, roi_id=args.roi, base=base_dir, screenshots=screenshots, overlays=[overlays[i][0]], colors=[colors[i]], verbose=(args.verbose - 1)) except BaseException as e: for screenshot in screenshots: path = screenshot[0] if os.path.isfile(path): os.remove(path) exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) raise (e) if args.verbose > 0: print( "Saved screenshots of orthogonal slices of ROI volume {} with all overlays" .format(args.roi)) finally: db.close()
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') if self.Cast: cast = vtk.vtkImageCast() cast.SetInputData(self.Image) cast.SetOutputScalarTypeToFloat() cast.Update() self.Image = cast.GetOutput() resliceFilter = vtk.vtkImageReslice() resliceFilter.SetInputData(self.Image) if self.ReferenceImage: resliceFilter.SetInformationInput(self.ReferenceImage) else: if self.OutputSpacing: resliceFilter.SetOutputSpacing(self.OutputSpacing) if self.OutputOrigin: resliceFilter.SetOutputOrigin(self.OutputOrigin) if self.OutputExtent: resliceFilter.SetOutputExtent(self.OutputExtent) if self.Interpolation == 'nearestneighbor': resliceFilter.SetInterpolationModeToNearestNeighbor() elif self.Interpolation == 'linear': resliceFilter.SetInterpolationModeToLinear() elif self.Interpolation == 'cubic': resliceFilter.SetInterpolationModeToCubic() else: self.PrintError('Error: unsupported interpolation mode') resliceFilter.SetBackgroundLevel(self.BackgroundLevel) if self.TransformInputSampling: resliceFilter.TransformInputSamplingOn() else: resliceFilter.TransformInputSamplingOff() if not self.Matrix4x4: if self.MatrixCoefficients != []: self.PrintLog('Setting up transform matrix using specified coefficients') self.Matrix4x4 = vtk.vtkMatrix4x4() self.Matrix4x4.DeepCopy(self.MatrixCoefficients) elif self.Translation != [0.0,0.0,0.0] or self.Rotation != [0.0,0.0,0.0] or self.Scaling != [1.0,1.0,1.0]: self.PrintLog('Setting up transform matrix using specified translation, rotation and/or scaling') transform = vtk.vtkTransform() transform.RotateX(self.Rotation[0]) transform.RotateY(self.Rotation[1]) transform.RotateZ(self.Rotation[2]) transform.Translate(self.Translation[0], self.Translation[1], self.Translation[2]) transform.Scale(self.Scaling[0], self.Scaling[1], self.Scaling[2]) self.Matrix4x4 = vtk.vtkMatrix4x4() self.Matrix4x4.DeepCopy(transform.GetMatrix()) if self.InvertMatrix and self.Matrix4x4: self.Matrix4x4.Invert() if self.Matrix4x4: transform = vtk.vtkMatrixToLinearTransform() transform.SetInput(self.Matrix4x4) resliceFilter.SetResliceTransform(transform) resliceFilter.Update() self.Image = resliceFilter.GetOutput()
def take_screenshots_of_single_roi(args): color = rgb(*args.color) args.database = os.path.abspath(args.database) base_dir = os.path.dirname(args.database) image, qform = read_image(os.path.abspath(args.image)) image2world = vtkMatrixToLinearTransform() image2world.SetInput(qform) image2world.Update() world2image = image2world.GetLinearInverse() db = sqlite3.connect(args.database) if args.scan > 0: scan_id = args.scan else: scan_id = get_scan_id(db, args.subject, args.session) if args.prefix: prefix = os.path.abspath(args.prefix) prefix = partial_format(prefix, subject=args.subject, session=args.session, scan=scan_id, roi=args.roi) else: prefix = os.path.join(os.path.dirname(args.database), '-'.join([args.subject, args.session]), 'screenshots', 'roi-bounds') if not args.path_format: args.path_format = os.path.join('{prefix}', 'roi-{roi:06d}-{n:02d}_{suffix}.png') if args.range: level_window = range_to_level_window(*args.range) else: level_window = None try: if args.verbose > 0: print("Take screenshots of bounding boxes of ROI {roi}".format( roi=args.roi)) cur = db.cursor() try: overlay_id = get_overlay_id(cur, 'ROI Bounds') finally: cur.close() row = db.execute( "SELECT CenterX, CenterY, CenterZ, Span FROM ROIs WHERE ROI_Id = " + str(args.roi)).fetchone() span = row[3] center = [0, 0, 0] world2image.TransformPoint((row[0], row[1], row[2]), center) if len(args.offsets) > 0: offsets = args.offsets else: offsets = compute_offsets(span, args.subdiv) screenshots = [] path_format = partial_format(args.path_format, subject=args.subject, session=args.session, roi=args.roi) try: screenshots = take_screenshots_of_roi_bounds( image, transform=image2world, level_window=level_window, center=center, length=span, offsets=offsets, zoom_out_factor=args.zoom_out_factor, size=args.size, line_width=args.line_width, color=color, prefix=prefix, suffix=args.suffix, path_format=path_format, overwrite=False) insert_screenshots(db, roi_id=args.roi, base=base_dir, screenshots=screenshots, overlays=[overlay_id], colors=[color], verbose=(args.verbose - 1)) except BaseException as e: for screenshot in screenshots: path = screenshot[0] if os.path.isfile(path): os.remove(path) raise (e) if args.verbose > 0: print("Saved screenshots of bounding boxes of ROI {roi}".format( roi=args.roi)) finally: db.close()