def onJumpToPoint(self, caller, event): fiducialNode = caller.GetMarkupsNode() controlPointIndex = caller.GetActiveControlPoint() # Use the UI input slice node. mrmlSliceNode = self.ui.inputSliceNodeSelector.currentNode() if not mrmlSliceNode: message = ("Slice node not set", ) self.showStatusMessage(message, True) return # Get control point orientation matrix. self.currentControlPointID = fiducialNode.GetNthControlPointID( controlPointIndex) controlPointOrientationMatrix = vtk.vtkMatrix3x3() fiducialNode.GetNthControlPointOrientationMatrixWorld( controlPointIndex, controlPointOrientationMatrix) sliceToRAS = mrmlSliceNode.GetSliceToRAS() # Control point orientation has not been set, or has been reset. if controlPointOrientationMatrix.IsIdentity(): # Store the orientation part of a sliceToRAS matrix. sliceToRASOrientationMatrix = vtk.vtkMatrix3x3() for col in range(3): for row in range(3): value = sliceToRAS.GetElement(row, col) sliceToRASOrientationMatrix.SetElement(row, col, value) fiducialNode.SetNthControlPointOrientationMatrixWorld( controlPointIndex, sliceToRASOrientationMatrix) message = ("Slice orientation recorded", ) self.showStatusMessage(message) else: # Restore the orientation part of a sliceToRAS matrix. for col in range(3): for row in range(3): value = controlPointOrientationMatrix.GetElement(row, col) sliceToRAS.SetElement(row, col, value) # Update slice orientation in UI. mrmlSliceNode.UpdateMatrices() message = ("Slice orientation restored", ) self.showStatusMessage(message) # Execute a request to reset a control point orientation matrix. if self.ui.resetOrientationCheckBox.checked: identityMatrix = vtk.vtkMatrix3x3() fiducialNode.SetNthControlPointOrientationMatrixWorld( controlPointIndex, identityMatrix) message = ("Reset orientation at point", fiducialNode.GetNthControlPointLabel(controlPointIndex)) self.showStatusMessage(message) # Always set the checkbox to false. self.ui.resetOrientationCheckBox.checked = False
def create_structure(self): import vtk # REQUIRES VTK < 9.0!!! # molecule mol = vtk.vtkMolecule() # hardcoded structure CO2 a1 = mol.AppendAtom(6, 0.0, 0.0, 0.0) a2 = mol.AppendAtom(8, 0.0, 0.0, -1.0) a3 = mol.AppendAtom(8, 0.0, 0.0, 1.0) mol.AppendBond(a2, a1, 1) mol.AppendBond(a3, a1, 1) # hardcoded cell, cubic 10x10x10 vector = vtk.vtkMatrix3x3() vector.DeepCopy([10, 0, 0, 0, 10, 0, 0, 0, 10]) mol.SetLattice(vector) # Change lattice origin so molecule is in the centre mol.SetLatticeOrigin(vtk.vtkVector3d(-5.0, -5.0, -5.0)) # Create a mapper and actor mapper = vtk.vtkMoleculeMapper() mapper.SetInputData(mol) actor = vtk.vtkActor() actor.SetMapper(mapper) self.fbo.addActors([actor]) self.fbo.update()
def __init__(self, parent): ScriptedLoadableModuleWidget.__init__(self, parent) global OPENCV2_AVAILABLE try: global cv2 import cv2 OPENCV2_AVAILABLE = True except ImportError: OPENCV2_AVAILABLE = False if not OPENCV2_AVAILABLE: logging.error("OpenCV2 python interface not available.") return self.logic = PinholeCameraRayIntersectionLogic() self.markupsLogic = slicer.modules.markups.logic() self.canSelectFiducials = False self.isManualCapturing = False self.validPinholeCamera = False self.centerFiducialSelectionNode = None self.copyNode = None self.widget = None self.videoCameraIntrinWidget = None self.videoCameraSelector = None self.videoCameraNode = None self.markupsNode = None # Observer tags self.videoCameraObserverTag = None self.videoCameraTransformObserverTag = None self.pointModifiedObserverTag = None self.videoCameraTransformNode = None self.videoCameraTransformStatusLabel = None self.okPixmap = PinholeCameraRayIntersectionWidget.loadPixmap( 'icon_Ok', 20, 20) self.notOkPixmap = PinholeCameraRayIntersectionWidget.loadPixmap( 'icon_NotOk', 20, 20) # Inputs/Outputs self.imageSelector = None self.videoCameraTransformSelector = None # Actions self.captureButton = None self.resetButton = None self.actionContainer = None # Results self.resultsLabel = None self.videoCameraToReference = None self.identity3x3 = vtk.vtkMatrix3x3() self.identity4x4 = vtk.vtkMatrix4x4()
def testMatirx(): m3 = vtk.vtkMatrix3x3() print(type(m3)) m31 = vtk.vtkMatrix3x3() v3 = [1, 0, 0, 0, 2, 0, 0, 0, 3] v31 = [2, 2, 2] v32 = [2, 2, 2] m3.DeepCopy(v3) m3.MultiplyPoint(v31, v32) vtk.vtkMatrix3x3.Invert(m3, m31) m3.Transpose() m3.Adjoint(m3, m31) print(m3.Determinant()) print(m3.IsA('vtkMatrix3x3'), type(m3)) res = m31.GetData() print('m31', res, type(res)) ls = [] for i in range(3): for j in range(3): ls.append(m3.GetElement(i, j)) print(ls)
def getVTKMatrixFromNumpyMatrix(self, numpyMatrix): dimensions = len(numpyMatrix) - 1 if dimensions == 2: vtkMatrix = vtk.vtkMatrix3x3() elif dimensions == 3: vtkMatrix = vtk.vtkMatrix4x4() else: raise ValueError('Unknown matrix dimensions.') for row in range(dimensions + 1): for col in range(dimensions + 1): vtkMatrix.SetElement(row, col, numpyMatrix[row, col]) return vtkMatrix
def numpy_to_vtk_matrix(array): """Convert a numpy array to a VTK matrix.""" if array is None: return None if array.shape == (4, 4): matrix = vtk.vtkMatrix4x4() elif array.shape == (3, 3): matrix = vtk.vtkMatrix3x3() else: raise ValueError("Invalid matrix shape: {0}".format(array.shape)) for i in range(array.shape[0]): for j in range(array.shape[1]): matrix.SetElement(i, j, array[i, j]) return matrix
def test_arrayFromVTKMatrix(self): # Test arrayFromVTKMatrix, vtkMatrixFromArray, and updateVTKMatrixFromArray import numpy as np self.delayDisplay( 'Test arrayFromVTKMatrix, vtkMatrixFromArray, and updateVTKMatrixFromArray' ) # Test 4x4 matrix a = np.array([[1.5, 0.5, 0, 4], [0, 2.0, 0, 11], [0, 0, 2.5, 6], [0, 0, 0, 1]]) vmatrix = slicer.util.vtkMatrixFromArray(a) self.assertTrue(isinstance(vmatrix, vtk.vtkMatrix4x4)) self.assertEqual(vmatrix.GetElement(0, 1), 0.5) self.assertEqual(vmatrix.GetElement(1, 3), 11) narray = slicer.util.arrayFromVTKMatrix(vmatrix) np.testing.assert_array_equal(a, narray) vmatrixExisting = vtk.vtkMatrix4x4() slicer.util.updateVTKMatrixFromArray(vmatrixExisting, a) narray = slicer.util.arrayFromVTKMatrix(vmatrixExisting) np.testing.assert_array_equal(a, narray) # Test 3x3 matrix a = np.array([[1.5, 0, 0], [0, 2.0, 0], [0, 1.2, 2.5]]) vmatrix = slicer.util.vtkMatrixFromArray(a) self.assertTrue(isinstance(vmatrix, vtk.vtkMatrix3x3)) self.assertEqual(vmatrix.GetElement(0, 0), 1.5) self.assertEqual(vmatrix.GetElement(2, 1), 1.2) narray = slicer.util.arrayFromVTKMatrix(vmatrix) np.testing.assert_array_equal(a, narray) vmatrixExisting = vtk.vtkMatrix3x3() slicer.util.updateVTKMatrixFromArray(vmatrixExisting, a) narray = slicer.util.arrayFromVTKMatrix(vmatrixExisting) np.testing.assert_array_equal(a, narray) # Test invalid matrix size caughtException = False try: vmatrix = slicer.util.vtkMatrixFromArray(np.zeros([3, 4])) except RuntimeError: caughtException = True self.assertTrue(caughtException)
def vtkMatrixFromArray(self, narray): """Create VTK matrix from a 3x3 or 4x4 numpy array. :param narray: input numpy array The returned matrix is just a copy and so any modification in the array will not affect the output matrix. To set numpy array from VTK matrix, use :py:meth:`arrayFromVTKMatrix`. """ from vtk import vtkMatrix4x4 from vtk import vtkMatrix3x3 narrayshape = narray.shape if narrayshape == (4, 4): vmatrix = vtkMatrix4x4() self.updateVTKMatrixFromArray(vmatrix, narray) return vmatrix elif narrayshape == (3, 3): vmatrix = vtkMatrix3x3() self.updateVTKMatrixFromArray(vmatrix, narray) return vmatrix else: raise RuntimeError("Unsupported numpy array shape: " + str(narrayshape) + " expected (4,4)")
def convert_vtk_matrix_to_list(matrix): """ Convert a vtk matrix object into a list :param matrix: vtkMatrix4x4 or vtkMatrix3x3 :return: list of elements with the same dimensions """ if isinstance(matrix, type(vtk.vtkMatrix4x4())): dim = 4 elif isinstance(matrix, type(vtk.vtkMatrix3x3())): dim = 3 else: raise Exception("Type not allowed") threshold = 0.00000000000001 # Threshold for rounding result = [] for i in range(dim): row = [] for j in range(dim): n = matrix.GetElement(i, j) if abs(n) < threshold: n = 0 row.append(n) result.append(row) return result
def vtkmatrix_from_array(array): """Convert a ``numpy.ndarray`` or array-like to a vtk matrix. Parameters ---------- array : numpy.ndarray or array-like The array or array-like to be converted to a vtk matrix. Shape (3, 3) gets converted to a ``vtk.vtkMatrix3x3``, shape (4, 4) gets converted to a ``vtk.vtkMatrix4x4``. No other shapes are valid. """ array = np.asarray(array) if array.shape == (3, 3): matrix = vtk.vtkMatrix3x3() elif array.shape == (4, 4): matrix = vtk.vtkMatrix4x4() else: raise ValueError(f'Invalid shape {array.shape}, must be (3, 3) or (4, 4).') m, n = array.shape for i in range(m): for j in range(n): matrix.SetElement(i, j, array[i, j]) return matrix
# Determine bone geometry Log("Determining bone geometry.") moi = vtkski.vtkskiTensorOfInertia() moi.SetInput(image) #moi.SetSpecificValue (-1)# later change to not include 127 moi.SetLowerThreshold(1) moi.SetUpperThreshold(127) moi.UseThresholdsOn() Log("Number of cells belonging to bone: %d" % moi.GetCount()) Log("Volume of bone: %.2f" % moi.GetVolume()) boneCenterOfMass = (moi.GetCenterOfMassX(), moi.GetCenterOfMassY(), moi.GetCenterOfMassZ()) Log("Center of mass of bone: %.5f, %.5f, %.5f" % boneCenterOfMass) bonePrincipleAxes = vtk.vtkMatrix3x3() moi.GetPrincipleAxes(bonePrincipleAxes) # Take 3rd row - that is the 3rd principle axis, which is always the # principle axis lying closest to the z axis. boneAxisX = (bonePrincipleAxes.GetElement(0, 0), bonePrincipleAxes.GetElement(0, 1), bonePrincipleAxes.GetElement(0, 2)) Log("AxisX of bone: %.5f, %.5f, %.5f" % boneAxisX) boneAxisY = (bonePrincipleAxes.GetElement(1, 0), bonePrincipleAxes.GetElement(1, 1), bonePrincipleAxes.GetElement(1, 2)) Log("AxisY of bone: %.5f, %.5f, %.5f" % boneAxisY)
def definePlaneAxis(self, oPoint, zV): xP = [0.0, 0.0, 0.0, 0.0] self.xAxisFiducial.GetNthFiducialWorldCoordinates(0, xP) # a = Plane(Point3D(1,4,6), normal_vector=(2,4,6)) xAxisPoint = [xP[i] for i in (0,1,2)] self.zVector = zV self.xVector = np.subtract(xAxisPoint,oPoint) self.yVector = np.cross(self.zVector, self.xVector) #Para hallar la matriz de transformacion es necesario tener vectores unitarios! xUnitario = self.xVector/numpy.linalg.norm(self.xVector) yUnitario = self.yVector/numpy.linalg.norm(self.yVector) zUnitario = self.zVector/numpy.linalg.norm(self.zVector) print type(self.xVector) print ('Vector x:') print (self.xVector) print (self.xVector[0]) print ('Vector y:') print (self.yVector) print ('Vector z:') print (self.zVector) print oPoint #We create the transformation matrix so that change the coordinates system: R = vtk.vtkMatrix3x3() R.SetElement( 0, 0, xUnitario[0] ) # Row 1 R.SetElement( 0, 1, xUnitario[1] ) R.SetElement( 0, 2, xUnitario[2] ) R.SetElement( 1, 0, yUnitario[0] ) # Row 2 R.SetElement( 1, 1, yUnitario[1] ) R.SetElement( 1, 2, yUnitario[2] ) R.SetElement( 2, 0, zUnitario[0] ) # Row 3 R.SetElement( 2, 1, zUnitario[1] ) R.SetElement( 2, 2, zUnitario[2] ) resultPoint = [0.0, 0.0, 0.0] R.MultiplyPoint(oPoint, resultPoint) matrixTransfBOX = vtk.vtkMatrix4x4() matrixTransfBOX.SetElement( 0, 0, xUnitario[0] ) # Row 1 matrixTransfBOX.SetElement( 0, 1, xUnitario[1] ) matrixTransfBOX.SetElement( 0, 2, xUnitario[2] ) matrixTransfBOX.SetElement( 0, 3, -resultPoint[0] ) matrixTransfBOX.SetElement( 1, 0, yUnitario[0] ) # Row 2 matrixTransfBOX.SetElement( 1, 1, yUnitario[1] ) matrixTransfBOX.SetElement( 1, 2, yUnitario[2] ) matrixTransfBOX.SetElement( 1, 3, -resultPoint[1] ) matrixTransfBOX.SetElement( 2, 0, zUnitario[0] ) # Row 3 matrixTransfBOX.SetElement( 2, 1, zUnitario[1] ) matrixTransfBOX.SetElement( 2, 2, zUnitario[2] ) matrixTransfBOX.SetElement( 2, 3, -resultPoint[2] ) matrixTransfBOX.SetElement( 3, 0, 0 ) # Row 4 matrixTransfBOX.SetElement( 3, 1, 0) matrixTransfBOX.SetElement( 3, 2, 0 ) matrixTransfBOX.SetElement( 3, 3, 1 ) print (matrixTransfBOX) #self.planeA.SetAndObserveTransformNodeID(self.boxToReference.GetID()) oPoint = oPoint + [1.0] nuevoOrigen = [0.0, 0.0, 0.0 , 0.0] matrixTransfBOX.MultiplyPoint(oPoint, nuevoOrigen) print nuevoOrigen
def GetNthControlPointOrientationMatrixWorldByID(id): controlPointIndex = self.fiducialNode.GetNthControlPointIndexByID(id) controlPointOrientationMatrix = vtk.vtkMatrix3x3() self.fiducialNode.GetNthControlPointOrientationMatrixWorld( controlPointIndex, controlPointOrientationMatrix) return controlPointOrientationMatrix
def rotationFromHomogeneous(mat4): mat3 = vtk.vtkMatrix3x3() for i in range(3): for j in range(3): mat3.SetElement(i, j, mat4.GetElement(i, j)) return mat3