def test_inf_notrain(self): self.gp.clear() (fm, fv) = self.gp.inf(self.z) fmtrue = np.mat([1, 1]).T fvtrue = np.mat([7.389056, 7.389056]).T self.assertTrue(almostEqual(fmtrue, fm, 0.00001)) self.assertTrue(almostEqual(fvtrue, fv, 0.00001))
def setUp(self): hyp = {'mean': 1, 'cov': [-1.5, -1.3, 1], 'lik': -1} k = plan.gp.kernels.SE(hyp) self.gp = plan.gp.gp.GP(k) x = np.mat([[0, 0], [0, 0.5], [1, 0]]) y = np.mat([2, 1, 3]).T self.gp.add(x, y) self.z = np.mat([[0.5, 0.5], [0.25, 0.5]])
def test_symmetric(self): v = Symmetric(vertical=True).mat h = Symmetric(horizontal=True).mat f = Symmetric(fortyfive=True).mat ev = mt.mat('1 0 0; 0 -1 0; 0 0 1') eh = mt.mat('-1 0 0; 0 1 0; 0 0 1') ef = mt.mat('0 1 0; 1 0 0; 0 0 1') self.assertTrue((v == ev).all(), str(v)) self.assertTrue((h == eh).all(), str(h)) self.assertTrue((f == ef).all(), str(f))
def GetCovm2D(axis1_len, axis2_len, axis1_angle, nsigma=3): 'axis1_angle measured in degrees' assert axis1_len>0 and axis2_len>0 w=np.array([axis1_len, axis2_len], dtype=np.float32) w=(w/nsigma)**2 v=matlib.zeros((2, 2), dtype=np.float32) axis1_rad=math.radians(axis1_angle) axis2_rad=math.radians(axis1_angle+90) v[:, 0]=matlib.mat((math.cos(axis1_rad), math.sin(axis1_rad))).T v[:, 1]=matlib.mat((math.cos(axis2_rad), math.sin(axis2_rad))).T #print 'v get2D', v return v*matlib.diag(w)*v.T
def ComputeTPSKernel(model, ctrl_pts): m = model.shape[0] n = ctrl_pts.shape[0] M = ml.mat(model) C = ml.mat(ctrl_pts) result = ml.zeros([m, n], dtype = npy.float32) for i in range(m): for j in range(n): v = M[i, :] - C[j, :] r = npy.linalg.norm(v) result[i, j] = -r return result
def calc_rot_matrix(posor): """Calculate the rotation matrix that takes a column vector from the camera coordinates associated with posor to absolute coordinates""" th = posor.theta theta = np.mat([[np.cos(th), -np.sin(th), 0], [np.sin(th), np.cos(th), 0], [0, 0, 1]], dtype=npfloat) ph = posor.phi phi = np.mat([[np.cos(ph), 0, -np.sin(ph)], [0, 1, 0], [np.sin(ph), 0, np.cos(ph)]], dtype=npfloat) ps = posor.psi psi = np.mat([[1, 0, 0], [0, np.cos(ps), -np.sin(ps)], [0, np.sin(ps), np.cos(ps)]], dtype=npfloat) return theta * phi * psi
def angle2rotation(theta): # ZXY xx, yy, zz = theta cx = npy.cos(xx) sx = npy.sin(xx) cy = npy.cos(yy) sy = npy.sin(yy) cz = npy.cos(zz) sz = npy.sin(zz) Rx = ml.mat([[1, 0, 0], [0, cx, sx], [0, -sx, cx]]) Ry = ml.mat([[cy, 0, -sy], [0, 1, 0], [sy, 0, cy]]) Rz = ml.mat([[cz, sz, 0], [-sz, cz, 0], [0, 0, 1]]) R = Ry * Rx * Rz return R
def calc_rays(xys, view): """Return a matrix of column vectors of the rays corresponding to the pixels xys, given as a list of pairs. view defines the camera. The results are in camera coordinates.""" something = view_number(view) cxys = xys - np.array([view.centerx, view.centery]) return np.mat([np.full(len(xys), something), cxys[:, 0], -cxys[:, 1]], dtype=npfloat)
def getMatrixFromGmmPara(para): R = ml.mat(para[:9]).reshape(3, 3) T0 = ml.mat(para[9:12]).T if len(para) > 12: C = ml.mat(para[12:]) else: C = ml.zeros([1, 3], dtype = npy.float32) T0 = R.I * T0 T0 = -T0.T T = ml.zeros([4, 4], dtype = npy.float32) T[-1, -1] = 1 T[:3, :3] = R T[-1, :3] = T0 + C - C * R return T
def register(self, fixedData, movingData, discard = False): fixed_points = fixedData.getPointSet('Contour') moving_points = movingData.getPointSet('Contour') fixed_res = fixedData.getResolution().tolist() moving_res = movingData.getResolution().tolist() fixed_points = fixed_points.copy()[npy.where(fixed_points[:, 0] >= 0)] moving_points = moving_points.copy()[npy.where(moving_points[:, 0] >= 0)] # Use the bifurcation as the initial position fixed_bif = db.getBifurcation(fixed_points) moving_bif = db.getBifurcation(moving_points) if (fixed_bif < 0) or (moving_bif < 0): fixed_min = 0 else: temp = moving_points[:, 2:] moving_delta = moving_bif - npy.min(temp[npy.where(npy.round(temp[:, 1]) == 0), 0]) fixed_min = fixed_bif - moving_delta * moving_res[-1] / fixed_res[-1] # Get the result transformation parameters0 T = ml.mat([0, 0, 0]).T; R = ml.mat([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).I; if (fixed_bif >= 0) and (moving_bif >= 0): T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) moving_points = movingData.getPointSet('Contour').copy() moving_center = movingData.getPointSet('Centerline').copy() new_trans_points, result_center_points = util.resliceTheResultPoints(moving_points, moving_center, 20, moving_res, fixed_res, discard, R, T) T = -T T = R * T transform = sitk.Transform(3, sitk.sitkAffine) para = R.reshape(1, -1).tolist()[0] + T.T.tolist()[0] transform.SetParameters(para) movingImage = movingData.getSimpleITKImage() fixedImage = fixedData.getSimpleITKImage() resultImage = sitk.Resample(movingImage, fixedImage, transform, sitk.sitkLinear, 0, sitk.sitkFloat32) return sitk.GetArrayFromImage(resultImage), {'Contour': trans_points, 'Centerline': result_center_points}, para + [0, 0, 0]
def applyTransformForPoints(points, moving_res, fixed_res, R, T, C = npy.asmatrix([0, 0, 0]).T): points[:, :3] *= moving_res[:3] points[:, :3] -= C.T if T.shape[1] == 1: TT = ml.ones((points.shape[0], 1)) * T.T else: TT = T temp = ml.mat(points[:, :3]) * R + TT + ml.ones((points.shape[0], 1)) * C.T points[:, :3] = temp points[:, :3] /= fixed_res[:3] return points
def test_offsets(self): # test rotation p = np.matrix('1;0;0') T = Transform(p=p) assert_allclose(T.rotate_x(pi / 2).rotate_z(pi / 2).rotate_y( pi / 2).rotate_z(-pi / 2), T, atol=1e-7) # test translation T = Transform() assert_allclose( T.translate_x(5).translate_y(-2).translate_z(3).p, np.mat('5;-2;3')) # test mDH T = Transform().mDH(pi, 1, pi / 4, 2).mDH(0, 1, 0, 0) N = np.eye(4) N[:3, :3] = Rroll(pi) * Ryaw(pi / 4) N[:3, 3] = np.mat('1.7071;-.7071;-2') assert_allclose(T, N, atol=1e-4) # test inverse assert_allclose(T * T.I, Transform(), atol=1e-7)
def calc_phi(xys, ref_half_plane, view, cameraposor, laserpos, lasertheta): """Given an array of pixel pairs xys from a camera with view and cameraposor and laser with laserpos and lasertheta, calculate the laser inclination based on a known half-plane ref_half_plane. Throws a NoReferenceException if no pixels are in the reference half-plane.""" cref_pos = ddd.unrotate(ref_half_plane.pos - cameraposor.pos, cameraposor) cref_side = ddd.unrotate(ref_half_plane.side, cameraposor) cref_line = np.cross(cref_side, ddd.unrotate(ref_half_plane.normal, cameraposor), axis = 0) # TODO less copy-pasta cpos = np.array([cref_pos[1, 0], -cref_pos[2, 0]]) / cref_pos[0, 0] * ddd.view_number(view) \ + np.array([view.centerx, view.centery]) cline_ = cref_pos / cref_pos[0, 0] - cref_line / cref_line[0, 0] cside_ = np.array([cref_side[1, 0], -cref_side[2, 0]]) cside = np.array([cline_[2, 0], cline_[1, 0]]) if np.dot(cside, cside_) < 0: cside = - cside dxys = xys - cpos dot_products = np.array(np.mat([cside]) * np.mat(dxys).T)[0] good_xys = xys[dot_products >= 0] print("say "+str(np.average(good_xys[:,1]))) if len(good_xys) == 0: raise NoReferenceException() threepoints = ddd.threedize_plane(good_xys, view, cameraposor, ref_half_plane) return calc_phi_points(threepoints, laserpos, lasertheta)
def classify_click(self): if not self.taught: if self.teaching: self.error_dialog( 'Please wait until teaching process finishes') else: self.error_dialog( 'Please teach neural network before starting classification' ) return result = self.neuralNetwork.classify_input(m.mat(self.selectedFields)) if result == -1: self.modelResult.setText("?") else: self.modelResult.setText(str(result))
def applyTransformForPoints(points, moving_res, fixed_res, R, T, C=npy.asmatrix([0, 0, 0]).T): points[:, :3] *= moving_res[:3] points[:, :3] -= C.T if T.shape[1] == 1: TT = ml.ones((points.shape[0], 1)) * T.T else: TT = T temp = ml.mat(points[:, :3]) * R + TT + ml.ones((points.shape[0], 1)) * C.T points[:, :3] = temp points[:, :3] /= fixed_res[:3] return points
def calc_fx(svm_obj, x): """ Calculate fx value according to input x. :param svm_obj: shared svm object :param x: input data vector :return: fx value """ test_data = matlib.mat(x) if svm_obj.kernel_type[0] == 'lin': svm_obj.w = calc_w(svm_obj) return svm_obj.w * test_data.T + svm_obj.b else: fx = 0 for i in range(svm_obj.data_size): fx += svm_obj.alphas[i] * svm_obj.label_set[i] * kernel( svm_obj, test_data, svm_obj.X[i, :]) fx += svm_obj.b return fx
def register(self, fixedData, movingData, index = -1, discard = False, delta = 0, fov = 9999999.0, down_fix = 1, down_mov = 1, occ = 9999999.0, op = False, useMask = False, isTime = False, MaxRate = 0.2, aug = False, distance_fix = 0.3, distance_mov = 0.1, w_wrong = 1.5, truth_mov = None): time1 = time.time() if index == -1: index = self.gui.getDataIndex({'Contour': 0, 'Centerline': 1}, 'Select the object') if index is None: return None, None, None if index == 0: fixed_points = fixedData.getPointSet('Contour').copy() moving_points = movingData.getPointSet('Contour').copy() else: fixed_points = fixedData.getPointSet('Centerline').copy() moving_points = movingData.getPointSet('Centerline').copy() if truth_mov is None: truth_mov = moving_points.copy() fixed_bif = db.getBifurcation(fixed_points) moving_bif = db.getBifurcation(moving_points) if useMask: mask_points = movingData.getPointSet('Mask') for point in mask_points: moving_points = npy.delete(moving_points, npy.where((npy.abs(moving_points[:, 2] - point[2]) < 0.0001) & (npy.round(moving_points[:, -1]) == point[3])), axis = 0) fixed_res = fixedData.getResolution().tolist() moving_res = movingData.getResolution().tolist() fixed_points = fixed_points[npy.where(fixed_points[:, 0] >= 0)] moving_points = moving_points[npy.where(moving_points[:, 0] >= 0)] # Use the bifurcation as the initial position if (fixed_bif < 0) or (moving_bif < 0): fixed_min = 0 # Augmentation of pointset fixed = fixed_points.copy() moving = moving_points.copy() if index == 1 and aug: fixed = util.augmentCenterline(fixed, 1, 10) moving = util.augmentCenterline(moving, 1, 10) fix_dis = util.getAxisSin(fixed, 3 / fixed_res[2]) * distance_fix mov_dis = util.getAxisSin(moving, 3 / moving_res[2]) * distance_mov fixed = util.resampleCenterline(fixed, fix_dis / fixed_res[2]) moving = util.resampleCenterline(moving, mov_dis / moving_res[2]) fixed = fixed[npy.cast[npy.int32](npy.abs(fixed[:, 2] - fixed_bif)) % down_fix == 0] moving = moving[npy.cast[npy.int32](npy.abs(moving[:, 2] - moving_bif)) % down_mov == 0] fixed[:, :3] *= fixed_res[:3] moving[:, :3] *= moving_res[:3] new_trans_points = truth_mov result_center_points = movingData.getPointSet('Centerline').copy() new_trans_points = new_trans_points[new_trans_points[:, 3] >= 0] result_center_points = result_center_points[result_center_points[:, 3] >= 0] new_trans_points[:, :3] *= moving_res[:3] result_center_points[:, :3] *= moving_res[:3] if (fixed_bif >= 0) and (moving_bif >= 0): fixed[:, 2] -= (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta) # Prepare for ICP MaxIterNum = 50 #MaxNum = 600 MaxNum = int(MaxRate * moving.shape[0] + 0.5) targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()] targetVertices = [vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray()] target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()] Locator = [vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator()] for i in range(3): for x in fixed[npy.round(fixed[:, 3]) == i]: id = targetPoints[i].InsertNextPoint(x[0], x[1], x[2]) targetVertices[i].InsertNextCell(1) targetVertices[i].InsertCellPoint(id) target[i].SetPoints(targetPoints[i]) target[i].SetVerts(targetVertices[i]) Locator[i].SetDataSet(target[i]) Locator[i].SetNumberOfCellsPerBucket(1) Locator[i].BuildLocator() step = 1 if moving.shape[0] > MaxNum: ind = moving[:, 2].argsort() moving = moving[ind, :] step = moving.shape[0] / MaxNum nb_points = moving.shape[0] / step points1 = vtk.vtkPoints() points1.SetNumberOfPoints(nb_points) label = npy.zeros([MaxNum * 2], dtype = npy.int8) j = 0 for i in range(nb_points): points1.SetPoint(i, moving[j][0], moving[j][1], moving[j][2]) label[i] = moving[j][3] j += step closestp = vtk.vtkPoints() closestp.SetNumberOfPoints(nb_points) points2 = vtk.vtkPoints() points2.SetNumberOfPoints(nb_points) id1 = id2 = vtk.mutable(0) dist = vtk.mutable(0.0) outPoint = [0.0, 0.0, 0.0] p1 = [0.0, 0.0, 0.0] p2 = [0.0, 0.0, 0.0] iternum = 0 a = points1 b = points2 if (op and index == 0) or (not op and index == 1): w_mat = [[1, w_wrong, w_wrong], [w_wrong, 1, 99999999], [w_wrong, 99999999, 1]] else: w_mat = [[1, 1, 1], [1, 1, 1], [1, 1, 1]] accumulate = vtk.vtkTransform() accumulate.PostMultiply() LandmarkTransform = vtk.vtkLandmarkTransform() LandmarkTransform.SetModeToRigidBody() while True: for i in range(nb_points): min_dist = 99999999 min_outPoint = [0.0, 0.0, 0.0] for j in range(3): Locator[j].FindClosestPoint(a.GetPoint(i), outPoint, id1, id2, dist) dis = npy.sqrt(npy.sum((npy.array(outPoint) - a.GetPoint(i)) ** 2)) if dis * w_mat[label[i]][j] < min_dist: min_dist = dis * w_mat[label[i]][j] min_outPoint = copy.deepcopy(outPoint) closestp.SetPoint(i, min_outPoint) LandmarkTransform.SetSourceLandmarks(a) LandmarkTransform.SetTargetLandmarks(closestp) LandmarkTransform.Update() accumulate.Concatenate(LandmarkTransform.GetMatrix()) iternum += 1 for i in range(nb_points): a.GetPoint(i, p1) LandmarkTransform.InternalTransformPoint(p1, p2) b.SetPoint(i, p2) b, a = a, b if iternum >= MaxIterNum: break matrix = accumulate.GetMatrix() T = ml.mat([matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3)]).T R = ml.mat([[matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2)], [matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2)], [matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2)]]).I result_center_points[:, :3] = util.applyTransformForPoints(result_center_points[:, :3], npy.array([1.0, 1, 1]), npy.array([1.0, 1, 1]), R, T, ml.zeros([3, 1], dtype = npy.float32)) new_trans_points[:, :3] = util.applyTransformForPoints(new_trans_points[:, :3], npy.array([1.0, 1, 1]), npy.array([1.0, 1, 1]), R, T, ml.zeros([3, 1], dtype = npy.float32)) LandmarkTransform = vtk.vtkThinPlateSplineTransform() LandmarkTransform.SetBasisToR() iternum = 0 # Non-rigid while True: for i in range(nb_points): min_dist = 99999999 min_outPoint = [0.0, 0.0, 0.0] for j in range(3): Locator[j].FindClosestPoint(a.GetPoint(i), outPoint, id1, id2, dist) dis = npy.sqrt(npy.sum((npy.array(outPoint) - a.GetPoint(i)) ** 2)) if dis * w_mat[label[i]][j] < min_dist: min_dist = dis * w_mat[label[i]][j] min_outPoint = copy.deepcopy(outPoint) closestp.SetPoint(i, min_outPoint) LandmarkTransform.SetSourceLandmarks(a) LandmarkTransform.SetTargetLandmarks(closestp) LandmarkTransform.Update() ''' for i in range(result_center_points.shape[0]): LandmarkTransform.InternalTransformPoint([result_center_points[i, 0], result_center_points[i, 1], result_center_points[i, 2]], p2) result_center_points[i, :3] = p2 ''' for i in range(new_trans_points.shape[0]): LandmarkTransform.InternalTransformPoint([new_trans_points[i, 0], new_trans_points[i, 1], new_trans_points[i, 2]], p2) new_trans_points[i, :3] = p2 iternum += 1 if iternum >= 1: break for i in range(nb_points): a.GetPoint(i, p1) LandmarkTransform.InternalTransformPoint(p1, p2) b.SetPoint(i, p2) b, a = a, b time2 = time.time() if (fixed_bif >= 0) and (moving_bif >= 0): new_trans_points[:, 2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta) result_center_points[:, 2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta) new_trans_points[:, :3] /= fixed_res[:3] result_center_points[:, :3] /= fixed_res[:3] resultImage = movingData.getData().copy() sa = SurfaceErrorAnalysis(None) dataset = db.BasicData(npy.array([[[0]]]), fixedData.getInfo(), {'Contour': new_trans_points, 'Centerline': result_center_points}) mean_dis, mean_whole, max_dis, max_whole = sa.analysis(dataset, point_data_fix = fixedData.getPointSet('Contour').copy(), useResult = True) del dataset print mean_dis print mean_whole if isTime: return resultImage, {'Contour': new_trans_points, 'Centerline': result_center_points}, [mean_dis, mean_whole], time2 - time1 return resultImage, {'Contour': new_trans_points, 'Centerline': result_center_points}, [mean_dis, mean_whole]
def setUp(self): self.hyp = {'mean': 0, 'cov': [-1.5, -1.3, 5], 'lik': -1} self.k = plan.gp.kernels.SE(self.hyp) self.x = np.mat([[0, 0], [0, 0.5], [1, 0]]) self.z = np.mat([[0.5, 0.5], [0.25, 0.5]])
def setWidgetView(self, widget, color=[[1, 0, 0], [0, 1, 0], [0, 0, 1]]): super(SurfaceView, self).setWidgetView(widget) if type(self.parent) is MdiChildRegistration: point_array_move = self.parent.getData('move').pointSet point_data_move = npy.array(point_array_move.getData('Contour')) point_data_result = npy.array(point_data_move) if point_data_result is None or not point_data_result.shape[0]: return self.spacing_mov = self.parent.getData( 'move').getResolution().tolist() self.spacing = self.parent.getData().getResolution().tolist() para = npy.array( self.parent.getData().getInfo().getData('transform')) R = ml.mat(para[:9].reshape(3, 3)) T = ml.mat(para[9:12].reshape(3, 1)) T = R.I * T T = -T point_data_result[:, :3] *= self.spacing_mov[:3] point_data_result[:, :3] = ml.mat( point_data_result[:, :3]) * R + ml.ones( (point_data_result.shape[0], 1)) * T.T point_data_result[:, :3] /= self.spacing[:3] else: point_array_result = self.parent.getData().pointSet point_data_result = npy.array( point_array_result.getData('Contour')) point_array_move = point_array_result point_data_move = npy.array(point_array_move.getData('Contour')) zmin = int(npy.min(point_data_move[:, 2]) + 0.5) zmax = int(npy.max(point_data_move[:, 2]) + 0.5) self.spacing = self.parent.getData().getResolution().tolist() self.spacing = [float(x) / self.spacing[-1] for x in self.spacing] point_data_result[:, :2] *= self.spacing[:2] self.renderer = vtk.vtkRenderer() self.render_window = widget.GetRenderWindow() self.render_window.AddRenderer(self.renderer) self.window_interactor = vtk.vtkRenderWindowInteractor() self.render_window.SetInteractor(self.window_interactor) self.contours = [] self.delaunay3D = [] self.delaunayMapper = [] self.surface_actor = [] for cnt in range(3): self.contours.append(vtk.vtkPolyData()) self.delaunay3D.append(vtk.vtkDelaunay3D()) self.delaunayMapper.append(vtk.vtkDataSetMapper()) self.surface_actor.append(vtk.vtkActor()) point_result = point_data_result[npy.where( npy.round(point_data_result[:, -1]) == cnt)] point_move = point_data_move[npy.where( npy.round(point_data_move[:, -1]) == cnt)] if not point_result.shape[0]: continue self.cells = vtk.vtkCellArray() self.points = vtk.vtkPoints() l = 0 for i in range(zmin, zmax + 1): data = point_result[npy.where( npy.round(point_move[:, 2]) == i)] if data is not None: if data.shape[0] == 0: continue count = data.shape[0] points = vtk.vtkPoints() for j in range(count): points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2]) para_spline = vtk.vtkParametricSpline() para_spline.SetPoints(points) para_spline.ClosedOn() # The number of output points set to 10 times of input points numberOfOutputPoints = count * 10 self.cells.InsertNextCell(numberOfOutputPoints) for k in range(0, numberOfOutputPoints): t = k * 1.0 / numberOfOutputPoints pt = [0.0, 0.0, 0.0] para_spline.Evaluate([t, t, t], pt, [0] * 9) if pt[0] != pt[0]: print pt continue self.points.InsertPoint(l, pt[0], pt[1], pt[2]) self.cells.InsertCellPoint(l) l += 1 self.contours[cnt].SetPoints(self.points) self.contours[cnt].SetPolys(self.cells) self.delaunay3D[cnt].SetInput(self.contours[cnt]) self.delaunay3D[cnt].SetAlpha(2) self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput()) self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt]) self.surface_actor[cnt].GetProperty().SetDiffuseColor( color[cnt][0], color[cnt][1], color[cnt][2]) self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1) self.surface_actor[cnt].GetProperty().SetSpecular(0.4) self.surface_actor[cnt].GetProperty().SetSpecularPower(50) self.renderer.AddViewProp(self.surface_actor[cnt]) self.renderer.ResetCamera() point = self.renderer.GetActiveCamera().GetFocalPoint() dis = self.renderer.GetActiveCamera().GetDistance() self.renderer.GetActiveCamera().SetViewUp(0, 0, 1) self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis, point[2]) self.renderer.ResetCameraClippingRange() self.render_window.Render() # Manually set to trackball style self.window_interactor.SetKeyCode('t') self.window_interactor.CharEvent() self.window_interactor.GetInteractorStyle().AddObserver( "KeyPressEvent", self.KeyPressCallback) self.window_interactor.GetInteractorStyle().AddObserver( "CharEvent", self.KeyPressCallback)
def analysis(self, data, point_data_fix = None, point_data_mov = None, point_data_mask = None, spacing_mov = None, useResult = False): if point_data_fix is None: point_data_fix = self.gui.dataModel[data.getFixedIndex()].getPointSet('Contour').copy() point_data_mov = self.gui.dataModel[data.getMovingIndex()].getPointSet('Contour').copy() point_data_mask = self.gui.dataModel[data.getMovingIndex()].getPointSet('Mask').copy() spacing_mov = self.gui.dataModel[data.getMovingIndex()].getResolution().tolist() self.spacing = data.getResolution().tolist() point_data_fix = point_data_fix[point_data_fix[:, 0] >= 0] bif = db.getBifurcation(point_data_fix) point_data_fix = util.augmentPointset(point_data_fix, 3, -1, bif, nn = 20) point_data_fix[:, :3] *= self.spacing[:3] if point_data_mov is not None: point_data_mov = point_data_mov[point_data_mov[:, 0] >= 0] if not useResult: para = npy.array(data.info.getData('transform')).flatten() point_data_result = point_data_mov.copy() for point in point_data_mask: point_data_result = npy.delete(point_data_result, npy.where((npy.abs(point_data_result[:, 2] - point[2]) < 0.0001) & (npy.round(point_data_result[:, -1]) == point[3])), axis = 0) point_data_result[:, :3] *= spacing_mov[:3] R = ml.mat(para[:9]).reshape(3, 3) T = ml.mat(para[9:12]).T if para.shape[0] > 12: C = ml.mat(para[12:]).T else: C = ml.zeros([3, 1], dtype = npy.float32) T = R.I * T T = -T point_data_result[:, :3] = util.applyTransformForPoints(point_data_result[:, :3], npy.array([1.0, 1, 1]), npy.array([1.0, 1, 1]), R, T, C) else: point_data_result = data.getPointSet('Contour').copy() point_data_result = point_data_result[point_data_result[:, -1] >= 0] point_data_result[:, :3] *= self.spacing[:3] targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()] targetVertices = [vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray()] target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()] Locator = [vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator()] label_dis = [3, 2, 1] for i in range(3): for x in point_data_fix[npy.round(point_data_fix[:, 3]) != label_dis[i]]: id = targetPoints[i].InsertNextPoint(x[0], x[1], x[2]) targetVertices[i].InsertNextCell(1) targetVertices[i].InsertCellPoint(id) target[i].SetPoints(targetPoints[i]) target[i].SetVerts(targetVertices[i]) Locator[i].SetDataSet(target[i]) Locator[i].SetNumberOfCellsPerBucket(1) Locator[i].BuildLocator() ''' Locator = vtk.vtkCellLocator() targetPoints = vtk.vtkPoints() targetVertices = vtk.vtkCellArray() target = vtk.vtkPolyData() for x in point_data_fix: id = targetPoints.InsertNextPoint(x[0], x[1], x[2]) targetVertices.InsertNextCell(1) targetVertices.InsertCellPoint(id) target.SetPoints(targetPoints) target.SetVerts(targetVertices) Locator.SetDataSet(target) Locator.SetNumberOfCellsPerBucket(1) Locator.BuildLocator() ''' id1 = id2 = vtk.mutable(0) dist = vtk.mutable(0.0) outPoint = [0.0, 0.0, 0.0] cnt_num = npy.array([0, 0, 0]) mean_dis = npy.array([0.0, 0.0, 0.0]) max_dis = npy.array([0.0, 0.0, 0.0]) for pt in point_data_result: cnt = int(pt[-1] + 0.5) Locator[cnt].FindClosestPoint(pt[:3].tolist(), outPoint, id1, id2, dist) dis = npy.sqrt(npy.sum((npy.array(outPoint) - pt[:3]) ** 2)) mean_dis[cnt] += dis max_dis[cnt] = npy.max([max_dis[cnt], dis]) cnt_num[cnt] += 1 cnt_total = npy.sum(cnt_num) mean_whole = npy.sum(mean_dis) / cnt_total mean_dis /= cnt_num mean_dis[mean_dis != mean_dis] = 0 # Replace the NAN in the mean distance max_whole = npy.max(max_dis) if self.gui is not None: message = "Error on Vessel 0: %0.2fmm (Total %d slices)\nError on Vessel 1: %0.2fmm (Total %d slices)\nError on Vessel 2: %0.2fmm (Total %d slices)\nWhole Error: %0.2fmm (Total %d slices)\n" \ % (mean_dis[0], cnt_num[0], mean_dis[1], cnt_num[1], mean_dis[2], cnt_num[2], mean_whole, cnt_total) + \ "-----------------------------------------------------------------------------\n" + \ "Max Error on Vessel 0: %0.2fmm\nMax Error on Vessel 1: %0.2fmm\nMax Error on Vessel 2: %0.2fmm\nTotal Max Error: %0.2fmm" \ % (max_dis[0], max_dis[1], max_dis[2], npy.max(max_dis)); self.gui.showErrorMessage("Centerline Registration Error", message) return mean_dis, mean_whole, max_dis, max_whole
def subselect(Q, s): return math.sqrt(Q.shape[1] / s) * mat.mat(random.permutation(Q))[0:s]
def register(self, fixedData, movingData): def iterationUpdate(): currentParameter = transform.GetParameters() print "M: %f P: %f %f %f %f %f %f" % (optimizer.GetValue(), currentParameter.GetElement(0), currentParameter.GetElement(1), currentParameter.GetElement(2), currentParameter.GetElement(3), currentParameter.GetElement(4), currentParameter.GetElement(5)) image_type = fixedData.getITKImageType() fixedImage = fixedData.getITKImage() movingImage = movingData.getITKImage() mov_size = movingImage.GetLargestPossibleRegion().GetSize() rescale_filter_fixed = itk.RescaleIntensityImageFilter[image_type, image_type].New() rescale_filter_fixed.SetInput(fixedImage) rescale_filter_fixed.SetOutputMinimum(0) rescale_filter_fixed.SetOutputMaximum(255) rescale_filter_moving = itk.RescaleIntensityImageFilter[image_type, image_type].New() rescale_filter_moving.SetInput(movingImage) rescale_filter_moving.SetOutputMinimum(0) rescale_filter_moving.SetOutputMaximum(255) registration = itk.ImageRegistrationMethod[image_type, image_type].New() imageMetric = itk.MattesMutualInformationImageToImageMetric[image_type, image_type].New() transform = itk.Euler3DTransform.New() optimizer = itk.RegularStepGradientDescentOptimizer.New() interpolator = itk.LinearInterpolateImageFunction[image_type, itk.D].New() registration.SetOptimizer(optimizer) registration.SetTransform(transform) registration.SetInterpolator(interpolator) registration.SetMetric(imageMetric) registration.SetFixedImage(rescale_filter_fixed.GetOutput()) registration.SetMovingImage(rescale_filter_moving.GetOutput()) registration.SetFixedImageRegion(fixedImage.GetBufferedRegion()) fixed_res = fixedData.getResolution().tolist() moving_res = movingData.getResolution().tolist() transform.SetParameters([0.0, 0.0, 0.0, 0.0, 0.0, -329 * fixed_res[-1] + 95 * moving_res[-1]]) transform.SetCenter([mov_size[0] * moving_res[0] / 2, mov_size[1] * moving_res[1] / 2, 95 * moving_res[-1]]) initialParameters = transform.GetParameters() print "Initial Registration Parameters " print initialParameters.GetElement(0) print initialParameters.GetElement(1) print initialParameters.GetElement(2) print initialParameters.GetElement(3) print initialParameters.GetElement(4) print initialParameters.GetElement(5) registration.SetInitialTransformParameters(initialParameters) # optimizer scale translationScale = 2.0 optimizerScales = itk.Array[itk.D](transform.GetNumberOfParameters()) optimizerScales.SetElement(0, 0.01) optimizerScales.SetElement(1, 0.01) optimizerScales.SetElement(2, 0.01) optimizerScales.SetElement(3, translationScale) optimizerScales.SetElement(4, translationScale) optimizerScales.SetElement(5, translationScale) optimizer.SetScales(optimizerScales) #imageMetric.UseAllPixelsOn() imageMetric.SetNumberOfHistogramBins(64) imageMetric.SetNumberOfSpatialSamples(80000) optimizer.MinimizeOn() optimizer.SetMaximumStepLength(2.00) optimizer.SetMinimumStepLength(0.001) optimizer.SetRelaxationFactor(0.8) optimizer.SetNumberOfIterations(200) iterationCommand = itk.PyCommand.New() iterationCommand.SetCommandCallable(iterationUpdate) optimizer.AddObserver(itk.IterationEvent(), iterationCommand) # Start the registration process try: registration.Update() except Exception: print "error" transform.SetParameters([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) # Get the final parameters of the transformation finalParameters = registration.GetLastTransformParameters() print "Final Registration Parameters " print finalParameters.GetElement(0) print finalParameters.GetElement(1) print finalParameters.GetElement(2) print finalParameters.GetElement(3) print finalParameters.GetElement(4) print finalParameters.GetElement(5) # Use the final transform for resampling the moving image. parameters = transform.GetParameters() # Fail to use ResampleImageFilter x = parameters.GetElement(0) y = parameters.GetElement(1) z = parameters.GetElement(2) Xr = ml.mat([[1, 0, 0], [0, npy.cos(x), npy.sin(x)], [0, -npy.sin(x), npy.cos(x)]]) Yr = ml.mat([[npy.cos(y), 0, -npy.sin(y)], [0, 1, 0], [npy.sin(y), 0, npy.cos(y)]]) Zr = ml.mat([[npy.cos(z), npy.sin(z), 0], [-npy.sin(z), npy.cos(z), 0], [0, 0, 1]]) R = Xr * Yr * Zr T = ml.mat([parameters.GetElement(3), parameters.GetElement(4), parameters.GetElement(5)]).T transform = sitk.Transform(3, sitk.sitkAffine) para = R.reshape(1, -1).tolist()[0] + T.T.tolist()[0] transform.SetParameters(para) transform.SetFixedParameters([mov_size[0] * moving_res[0] / 2, mov_size[1] * moving_res[1] / 2, 95 * moving_res[-1]]) movingImage = movingData.getSimpleITKImage() fixedImage = fixedData.getSimpleITKImage() resultImage = sitk.Resample(movingImage, fixedImage, transform, sitk.sitkLinear, 0, sitk.sitkFloat32) array = sitk.GetArrayFromImage(resultImage) #print npy.sum(array) return array, {}, para
def register(self, fixedData, movingData, discard = False): index = self.gui.getDataIndex({'Contour': 0, 'Centerline': 1}, 'Select the object') if index is None: return None, None, None if index == 0: fixed_points = fixedData.getPointSet('Contour') moving_points = movingData.getPointSet('Contour') else: fixed_points = fixedData.getPointSet('Centerline') moving_points = movingData.getPointSet('Centerline') fixed_res = fixedData.getResolution().tolist() moving_res = movingData.getResolution().tolist() fixed_points = fixed_points.copy()[npy.where(fixed_points[:, 0] >= 0)] moving_points = moving_points.copy()[npy.where(moving_points[:, 0] >= 0)] # Use the bifurcation as the initial position fixed_bif = db.getBifurcation(fixed_points) moving_bif = db.getBifurcation(moving_points) if (fixed_bif < 0) or (moving_bif < 0): fixed_min = 0 else: temp = moving_points[:, 2:] moving_delta = moving_bif - npy.min(temp[npy.where(npy.round(temp[:, 1]) == 0), 0]) fixed_min = fixed_bif - moving_delta * moving_res[-1] / fixed_res[-1] #print moving_res #print fixed_res # Augmentation of pointset fixed = fixed_points[npy.where(fixed_points[:, 2] >= fixed_min)] moving = moving_points.copy() fixed = util.augmentPointset(fixed, int(fixed_res[-1] / moving_res[-1] + 0.5), moving.shape[0], fixed_bif) moving = util.augmentPointset(moving, int(moving_res[-1] / fixed_res[-1] + 0.5), fixed.shape[0], moving_bif) fixed = fixed[:, :3] moving = moving[:, :3] fixed[:, :3] *= fixed_res[:3] moving[:, :3] *= moving_res[:3] if (fixed_bif >= 0) and (moving_bif >= 0): fixed[:, 2] -= (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) print fixed.shape[0], moving.shape[0] #return None, None, None sourcePoints = vtk.vtkPoints() sourceVertices = vtk.vtkCellArray() for x in moving: id = sourcePoints.InsertNextPoint(x[0], x[1], x[2]) sourceVertices.InsertNextCell(1) sourceVertices.InsertCellPoint(id) source = vtk.vtkPolyData() source.SetPoints(sourcePoints) source.SetVerts(sourceVertices) targetPoints = vtk.vtkPoints() targetVertices = vtk.vtkCellArray() for x in fixed: id = targetPoints.InsertNextPoint(x[0], x[1], x[2]) targetVertices.InsertNextCell(1) targetVertices.InsertCellPoint(id) target = vtk.vtkPolyData() target.SetPoints(targetPoints) target.SetVerts(targetVertices) icp = vtk.vtkIterativeClosestPointTransform() icp.SetSource(source) icp.SetTarget(target) icp.GetLandmarkTransform().SetModeToRigidBody() icp.Modified() icp.Update() icp_filter = vtk.vtkTransformPolyDataFilter() icp_filter.SetInput(source) icp_filter.SetTransform(icp) icp_filter.Update() # Get the result transformation parameters matrix = icp.GetMatrix() T = ml.mat([matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3)]).T; R = ml.mat([[matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2)], [matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2)], [matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2)]]).I; if (fixed_bif >= 0) and (moving_bif >= 0): T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) moving_points = movingData.getPointSet('Contour').copy() moving_center = movingData.getPointSet('Centerline').copy() new_trans_points, result_center_points = util.resliceTheResultPoints(moving_points, moving_center, 20, moving_res, fixed_res, discard, R, T) T = -T T = R * T transform = sitk.Transform(3, sitk.sitkAffine) para = R.reshape(1, -1).tolist()[0] + T.T.tolist()[0] transform.SetParameters(para) movingImage = movingData.getSimpleITKImage() fixedImage = fixedData.getSimpleITKImage() resultImage = sitk.Resample(movingImage, fixedImage, transform, sitk.sitkLinear, 0, sitk.sitkFloat32) return sitk.GetArrayFromImage(resultImage), {'Contour': trans_points, 'Centerline': result_center_points}, para + [0, 0, 0]
trainingSet = m.mat([ [1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1], [0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0], [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], [1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1], [1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], [0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], [1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], [1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1] ], dtype=float)
def process(self, dataset, i): def autoDetectContour(point, cnt, start, end, delta, res, type): self.new_points = npy.append(self.new_points, point, 0) points = point[:, :-2] d = 20 count = 0 for i in range(start + delta, end + delta, delta): center = calCentroidFromContour(points).reshape(2) image = dataset[type].getData()[i, :, :].transpose().copy() image = (image - npy.min(image)) / (npy.max(image) - npy.min(image)) * 255 down = npy.max([npy.ceil(center[0] - d / res[0]), 0]) up = npy.min([npy.floor(center[0] + d / res[0]), image.shape[0]]) left = npy.max([npy.ceil(center[1] - d / res[1]), 0]) right = npy.min([npy.floor(center[1] + d / res[1]), image.shape[1]]) crop_image = image[down : up, left : right] center -= [down, left] result = ac_segmentation(center, crop_image) a1 = ac_area(points.transpose(), image.shape) a2 = ac_area(result, crop_image.shape) rate = a2 * 1.0 / a1 if rate >= min(1.5 + count * 0.2, 2.1) or rate <= 0.7: temp_array = points.copy() if cnt != 1 and rate > 0.7: count += 1 else: temp_array = result.transpose().copy() temp_array[:, :2] += [down, left] count = 0 points = temp_array.copy() temp_array = npy.insert(temp_array, 2, [[i], [cnt]], 1) self.new_points = npy.append(self.new_points, temp_array, 0) sys.stdout.write(str(i) + ',') sys.stdout.flush() print ' ' # Segmentation of data print 'Segment Data %s...' % self.ini.file.name_result[i] tmp = dataset['fix'].pointSet.data['Contour'] tmp = tmp[tmp[:, 0] >= 0] self.new_points = npy.array([[-1, -1, -1, -1]], dtype = npy.float32) bottom = int(npy.round(npy.min(tmp[:, 2]))) bif = int(db.getBifurcation(tmp) + 0.5) up = int(npy.round(npy.max(tmp[:, 2]))) bottom += (bif - bottom) / 2 up -= (up - bif) / 2 point_vital = [0] * 3 point_vital[0] = tmp[(npy.round(tmp[:, -1]) == 0) & (npy.round(tmp[:, 2]) == bottom)].copy() point_vital[1] = tmp[(npy.round(tmp[:, -1]) == 1) & (npy.round(tmp[:, 2]) == up)].copy() point_vital[2] = tmp[(npy.round(tmp[:, -1]) == 2) & (npy.round(tmp[:, 2]) == up)].copy() autoDetectContour(point_vital[0], 0, bottom, bif, 1, dataset['fix'].getResolution().tolist(), 'fix') autoDetectContour(point_vital[1], 1, up, bif, -1, dataset['fix'].getResolution().tolist(), 'fix') autoDetectContour(point_vital[2], 2, up, bif, -1, dataset['fix'].getResolution().tolist(), 'fix') print ' ' print 'Finish segmentation for fix data. ' pointset = {'Contour': self.new_points} dataset['fix'].pointSet.data['Centerline'] = calCenterlineFromContour(pointset) self.new_points_fix = self.new_points.copy() # For mov data tmp = dataset['mov'].pointSet.data['Contour'] tmp = tmp[tmp[:, 0] >= 0] self.new_points = npy.array([[-1, -1, -1, -1]], dtype = npy.float32) bottom = int(npy.round(npy.min(tmp[:, 2]))) bif = int(db.getBifurcation(tmp) + 0.5) up = int(npy.round(npy.max(tmp[:, 2]))) bottom += (bif - bottom) / 2 up -= (up - bif) / 2 point_vital = [0] * 3 point_vital[0] = tmp[(npy.round(tmp[:, -1]) == 0) & (npy.round(tmp[:, 2]) == bottom)].copy() point_vital[1] = tmp[(npy.round(tmp[:, -1]) == 1) & (npy.round(tmp[:, 2]) == up)].copy() point_vital[2] = tmp[(npy.round(tmp[:, -1]) == 2) & (npy.round(tmp[:, 2]) == up)].copy() autoDetectContour(point_vital[0], 0, bottom, bif, 1, dataset['mov'].getResolution().tolist(), 'mov') autoDetectContour(point_vital[1], 1, up, bif, -1, dataset['mov'].getResolution().tolist(), 'mov') autoDetectContour(point_vital[2], 2, up, bif, -1, dataset['mov'].getResolution().tolist(), 'mov') print ' ' print 'Finish segmentation for mov data. ' pointset = {'Contour': self.new_points} dataset['mov'].pointSet.data['Centerline'] = calCenterlineFromContour(pointset) self.new_points_mov = self.new_points.copy() # ICP with centerline without label print 'Register Data %s with ICP(centerline) without label...' % self.ini.file.name_result[i] data, point, para = self.icp.register(dataset['fix'], dataset['mov'], 1, op = True) resultData = db.ResultData(data, db.ImageInfo(dataset['fix'].info.data), point) resultData.info.addData('fix', 1) resultData.info.addData('move', 2) resultData.info.addData('transform', para) print 'Done!' mean_dis, mean_whole, max_dis, max_whole = self.surfaceerror.analysis(resultData, dataset['fix'].getPointSet('Contour').copy(), dataset['mov'].getPointSet('Contour').copy(), dataset['mov'].getPointSet('Mask').copy(), dataset['mov'].getResolution().tolist()) print 'Contour Error Done! Whole mean is %0.2fmm.' % mean_whole dice_index, dice_index_all = self.areaerror.analysis(resultData, dataset['fix'].getPointSet('Contour').copy()) print 'Area Error Done! Whole Dice index is %0.3f.' % dice_index_all self.sheet2.write(0, i + 2, self.ini.file.name_result[i]) for j in range(3): self.sheet2.write(j + 1, i + 2, mean_dis[j]) self.sheet2.write(j + 5, i + 2, max_dis[j]) self.sheet2.write(j + 9, i + 2, dice_index[j]) self.sheet2.write(4, i + 2, mean_whole) self.sheet2.write(8, i + 2, max_whole) self.sheet2.write(12, i + 2, dice_index_all) self.book.save(self.path + self.ini.file.savedir + 'multicontrast_seg_feature.xls') del data, point, resultData # ICP with centerline with label print 'Register Data %s with ICP(centerline) with label...' % self.ini.file.name_result[i] data, point, para = self.icp.register(dataset['fix'], dataset['mov'], 1, op = False) resultData = db.ResultData(data, db.ImageInfo(dataset['fix'].info.data), point) resultData.info.addData('fix', 1) resultData.info.addData('move', 2) resultData.info.addData('transform', para) print 'Done!' mean_dis, mean_whole, max_dis, max_whole = self.surfaceerror.analysis(resultData, dataset['fix'].getPointSet('Contour').copy(), dataset['mov'].getPointSet('Contour').copy(), dataset['mov'].getPointSet('Mask').copy(), dataset['mov'].getResolution().tolist()) print 'Contour Error Done! Whole mean is %0.2fmm.' % mean_whole dice_index, dice_index_all = self.areaerror.analysis(resultData, dataset['fix'].getPointSet('Contour').copy()) print 'Area Error Done! Whole Dice index is %0.3f.' % dice_index_all self.sheet4.write(0, i + 2, self.ini.file.name_result[i]) for j in range(3): self.sheet4.write(j + 1, i + 2, mean_dis[j]) self.sheet4.write(j + 5, i + 2, max_dis[j]) self.sheet4.write(j + 9, i + 2, dice_index[j]) self.sheet4.write(4, i + 2, mean_whole) self.sheet4.write(8, i + 2, max_whole) self.sheet4.write(12, i + 2, dice_index_all) self.book.save(self.path + self.ini.file.savedir + 'multicontrast_seg_feature.xls') del data, point, resultData fix_points = dataset['fix'].getPointSet('Contour').copy() dataset['fix'].pointSet.data['Contour'] = self.new_points_fix mov_points = dataset['mov'].getPointSet('Contour').copy() dataset['mov'].pointSet.data['Contour'] = self.new_points_mov print 'Saving Data %s...' % self.ini.file.name_result[i] db.saveMatData(self.path + self.ini.file.savedir + self.ini.file.name_result[i] + '_snap.mat', [dataset['fix']], 0) db.saveMatData(self.path + self.ini.file.savedir + self.ini.file.name_result[i] + '_merge.mat', [dataset['mov']], 0) print 'Done!' # ICP with contour without label print 'Register Data %s with ICP(contour) without label...' % self.ini.file.name_result[i] data, point, para = self.icp.register(dataset['fix'], dataset['mov'], 0, op = False) resultData = db.ResultData(data, db.ImageInfo(dataset['fix'].info.data), point) resultData.info.addData('fix', 1) resultData.info.addData('move', 2) resultData.info.addData('transform', para) print 'Done!' mean_dis, mean_whole, max_dis, max_whole = self.surfaceerror.analysis(resultData, fix_points.copy(), mov_points.copy(), dataset['mov'].getPointSet('Mask').copy(), dataset['mov'].getResolution().tolist()) print 'Contour Error Done! Whole mean is %0.2fmm.' % mean_whole para = resultData.info.getData('transform') R = ml.mat(para[:9]).reshape(3, 3) T = ml.mat(para[9:12]).T T = R.I * T T = -T tmp_con, result_center_points = util.resliceTheResultPoints(mov_points, None, 20, dataset['mov'].getResolution().tolist(), dataset['fix'].getResolution().tolist(), False, R, T) resultData.pointSet.data['Contour'] = tmp_con dice_index, dice_index_all = self.areaerror.analysis(resultData, fix_points.copy()) print 'Area Error Done! Whole Dice index is %0.3f.' % dice_index_all self.sheet1.write(0, i + 2, self.ini.file.name_result[i]) for j in range(3): self.sheet1.write(j + 1, i + 2, mean_dis[j]) self.sheet1.write(j + 5, i + 2, max_dis[j]) self.sheet1.write(j + 9, i + 2, dice_index[j]) self.sheet1.write(4, i + 2, mean_whole) self.sheet1.write(8, i + 2, max_whole) self.sheet1.write(12, i + 2, dice_index_all) self.book.save(self.path + self.ini.file.savedir + 'multicontrast_seg_feature.xls') del data, point, resultData # ICP with contour with label print 'Register Data %s with ICP(contour) with label...' % self.ini.file.name_result[i] data, point, para = self.icp.register(dataset['fix'], dataset['mov'], 0, op = True) resultData = db.ResultData(data, db.ImageInfo(dataset['fix'].info.data), point) resultData.info.addData('fix', 1) resultData.info.addData('move', 2) resultData.info.addData('transform', para) print 'Done!' mean_dis, mean_whole, max_dis, max_whole = self.surfaceerror.analysis(resultData, fix_points.copy(), mov_points.copy(), dataset['mov'].getPointSet('Mask').copy(), dataset['mov'].getResolution().tolist()) print 'Contour Error Done! Whole mean is %0.2fmm.' % mean_whole para = resultData.info.getData('transform') R = ml.mat(para[:9]).reshape(3, 3) T = ml.mat(para[9:12]).T T = R.I * T T = -T tmp_con, result_center_points = util.resliceTheResultPoints(mov_points, None, 20, dataset['mov'].getResolution().tolist(), dataset['fix'].getResolution().tolist(), False, R, T) resultData.pointSet.data['Contour'] = tmp_con dice_index, dice_index_all = self.areaerror.analysis(resultData, fix_points.copy()) print 'Area Error Done! Whole Dice index is %0.3f.' % dice_index_all self.sheet3.write(0, i + 2, self.ini.file.name_result[i]) for j in range(3): self.sheet3.write(j + 1, i + 2, mean_dis[j]) self.sheet3.write(j + 5, i + 2, max_dis[j]) self.sheet3.write(j + 9, i + 2, dice_index[j]) self.sheet3.write(4, i + 2, mean_whole) self.sheet3.write(8, i + 2, max_whole) self.sheet3.write(12, i + 2, dice_index_all) self.book.save(self.path + self.ini.file.savedir + 'multicontrast_seg_feature.xls') del data, point, resultData del self.new_points, fix_points, self.new_points_fix, self.new_points_mov, mov_points, tmp_con, result_center_points
def applyTransform(points, para): T = ml.mat(para[:3]).T; R = ml.mat(para[3:].reshape(3, 3)).T.I; result = npy.array(points) result[:, :3] = ml.mat(points[:, :3]) * R + ml.ones((points.shape[0], 1)) * T.T return result
def register(self, fixedData, movingData, index=-1, discard=False, method="EM_TPS", execute=True, isTime=False): if index == -1: index = self.gui.getDataIndex({ 'Contour': 0, 'Centerline': 1 }, 'Select the object') if index is None: return None, None, None if index == 0: fixed_points = fixedData.getPointSet('Contour') moving_points = movingData.getPointSet('Contour') else: fixed_points = fixedData.getPointSet('Centerline') moving_points = movingData.getPointSet('Centerline') time1 = time.time() fixed_res = fixedData.getResolution().tolist() moving_res = movingData.getResolution().tolist() fixed_points = fixed_points.copy()[npy.where(fixed_points[:, -1] >= 0)] moving_points = moving_points.copy()[npy.where( moving_points[:, -1] >= 0)] # Use the bifurcation as the initial position fixed_bif = db.getBifurcation(fixed_points) moving_bif = db.getBifurcation(moving_points) if (fixed_bif < 0) or (moving_bif < 0): fixed_min = 0 else: temp = moving_points[:, 2:] moving_delta = moving_bif - npy.min( temp[npy.where(npy.round(temp[:, 1]) == 0), 0]) #fixed_min = 0 # Augmentation of pointset fixed = fixed_points.copy() tmp_fix = fixedData.getPointSet('Centerline') tmp_fix = tmp_fix[tmp_fix[:, -1] >= 0].copy() ctrl_pts = gutil.getControlPoints(tmp_fix, 1.0 / fixed_res[2]) moving = moving_points.copy() fixed = fixed[:, :3] moving = moving[:, :3] fixed[:, :3] *= fixed_res[:3] ctrl_pts *= fixed_res[:3] ctrl_pts_backup = ctrl_pts.copy() moving[:, :3] *= moving_res[:3] if (fixed_bif >= 0) and (moving_bif >= 0): fixed[:, 2] -= (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) ctrl_pts[:, 2] -= (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) #print fixed.shape[0], moving.shape[0] eg.initial_data(fixed, moving, ctrl_pts) if execute: code = eg.run_executable(method=method) #print code if code != 0: print "GMM Fail!" return None, None, None trans, para, para2 = eg.get_final_result(methodname=method) time2 = time.time() # Clear the temp files #eg.clear_temp_file() # Get the result transformation parameters if method == 'rigid': S1 = ml.eye(3, dtype=npy.float32) * para2[3] C = npy.asmatrix(para2[:3]).T C2 = npy.asmatrix(para2[4:7]).T T0 = npy.asmatrix(para[4:]).T R = util.quaternion2rotation(para[:4]) T = S1 * T0 + C2 - C if (fixed_bif >= 0) and (moving_bif >= 0): T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) moving_points = movingData.getPointSet('Contour').copy() moving_center = movingData.getPointSet('Centerline').copy() #new_trans_points, result_center_points = util.resliceTheResultPoints(moving_points, moving_center, 20, moving_res, fixed_res, discard, R, T, C) new_trans_points = util.applyTransformForPoints( moving_points, moving_res, fixed_res, R, T, C) result_center_points = util.applyTransformForPoints( moving_center, moving_res, fixed_res, R, T, C) T = -T T = R * T """ # Copy the output points of GMMREG for test new_trans_points = trans if (fixed_bif >= 0) and (moving_bif >= 0): new_trans_points[:, 2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) new_trans_points[:, :3] /= fixed_res[:3] new_trans_points = npy.insert(new_trans_points, [new_trans_points.shape[1]], moving_points[:, -1].reshape(-1, 1), axis = 1) new_trans_points = npy.append(new_trans_points, npy.array([[-1, -1, -1, -1]]), axis = 0) #result_center_points = movingData.getPointSet('Centerline').copy() result_center_points = movingData.getPointSet('Contour').copy() """ transform = sitk.Transform(3, sitk.sitkAffine) para = R.reshape(1, -1).tolist()[0] + T.T.tolist()[0] transform.SetParameters(para) transform.SetFixedParameters(C.T.tolist()[0]) #movingImage = movingData.getSimpleITKImage() #fixedImage = fixedData.getSimpleITKImage() #resultImage = sitk.Resample(movingImage, fixedImage, transform, sitk.sitkLinear, 0, sitk.sitkFloat32) if isTime: #return sitk.GetArrayFromImage(resultImage), {'Contour': new_trans_points, 'Centerline': result_center_points}, para + C.T.tolist()[0], time2 - time1 return movingData.getData().copy(), { 'Contour': new_trans_points, 'Centerline': result_center_points }, para + C.T.tolist()[0], time2 - time1 #return sitk.GetArrayFromImage(resultImage), {'Contour': new_trans_points, 'Centerline': result_center_points}, para + C.T.tolist()[0] return movingData.getData().copy(), { 'Contour': new_trans_points, 'Centerline': result_center_points }, para + C.T.tolist()[0] else: # EM_TPS moving_points = movingData.getPointSet('Contour').copy() moving_points = moving_points[npy.where(moving_points[:, 0] >= 0)] moving = moving_points[:, :3].copy() moving *= moving_res[:3] m = moving.shape[0] n = ctrl_pts.shape[0] M = ml.mat(moving.copy()) C2 = npy.asmatrix(para2[4:7]) C2 = ml.repmat(C2, m, 1) C3 = npy.asmatrix(para2[7:]) C3 = ml.repmat(C3, n, 1) ctrl_pts -= C3 ctrl_pts /= para2[3] C = npy.asmatrix(para2[:3]) C = ml.repmat(C, m, 1) moving -= C moving /= para2[3] basis = ml.zeros([m, n], dtype=npy.float32) basis[:, 0] = 1 basis[:, 1:4] = moving U = gutil.ComputeTPSKernel(moving, ctrl_pts) basis[:, 4:] = U * ml.mat(trans) #print npy.array(basis) T = basis * ml.mat(para) T *= para2[3] T += C2 - C if (fixed_bif >= 0) and (moving_bif >= 0): T[:, 2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) M += T new_trans_points = npy.array(M).copy() new_trans_points[:, :3] /= fixed_res[:3] new_trans_points = npy.insert(new_trans_points, [new_trans_points.shape[1]], moving_points[:, -1].reshape(-1, 1), axis=1) new_trans_points = npy.append(new_trans_points, npy.array([[-1, -1, -1, -1]]), axis=0) moving_points = movingData.getPointSet('Centerline').copy() moving_points = moving_points[npy.where(moving_points[:, 0] >= 0)] moving = moving_points[:, :3].copy() moving *= moving_res[:3] m = moving.shape[0] M = ml.mat(moving.copy()) C2 = npy.asmatrix(para2[4:7]) C2 = ml.repmat(C2, m, 1) C = npy.asmatrix(para2[:3]) C = ml.repmat(C, m, 1) moving -= C moving /= para2[3] basis = ml.zeros([m, n], dtype=npy.float32) basis[:, 0] = 1 basis[:, 1:4] = moving U = gutil.ComputeTPSKernel(moving, ctrl_pts) basis[:, 4:] = U * ml.mat(trans) #print npy.array(basis) T = basis * ml.mat(para) T *= para2[3] T += C2 - C if (fixed_bif >= 0) and (moving_bif >= 0): T[:, 2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) M += T result_center_points = npy.array(M).copy() result_center_points[:, :3] /= fixed_res[:3] result_center_points = npy.insert(result_center_points, [result_center_points.shape[1]], moving_points[:, -1].reshape(-1, 1), axis=1) result_center_points = npy.append(result_center_points, npy.array([[-1, -1, -1, -1]]), axis=0) #print result_center_points moving = ctrl_pts_backup.copy() m = moving.shape[0] M = ml.mat(moving.copy()) C = npy.asmatrix(para2[:3]) C = ml.repmat(C, m, 1) moving -= C moving /= para2[3] C2 = npy.asmatrix(para2[4:7]) C2 = ml.repmat(C2, m, 1) basis = ml.zeros([m, n], dtype=npy.float32) basis[:, 0] = 1 basis[:, 1:4] = moving U = gutil.ComputeTPSKernel(moving, ctrl_pts) basis[:, 4:] = U * ml.mat(trans) #print npy.array(basis) T = basis * ml.mat(para) T *= para2[3] T += C2 - C if (fixed_bif >= 0) and (moving_bif >= 0): T[:, 2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) M += T result_ctrl = npy.array(M).copy() #print result_ctrl image_type = fixedData.getITKImageType() transform_type = itk.ThinPlateSplineKernelTransform.D3 transform = transform_type.New() pointset_type = itk.PointSet.PD33S source_pointset = pointset_type.New() target_pointset = pointset_type.New() count = 0 for point in ctrl_pts_backup: tmp_point = itk.Point.D3() tmp_point[0] = point[0] tmp_point[1] = point[1] tmp_point[2] = point[2] source_pointset.SetPoint(count, tmp_point) count += 1 count = 0 for point in ctrl_pts_backup: tmp_point = itk.Point.D3() tmp_point[0] = point[0] tmp_point[1] = point[1] tmp_point[2] = point[2] target_pointset.SetPoint(count, tmp_point) count += 1 transform.SetSourceLandmarks(source_pointset) transform.SetTargetLandmarks(target_pointset) transform.ComputeWMatrix() """ # Test for TPS Transform moving_points = movingData.getPointSet('Centerline').copy() moving_points = moving_points[npy.where(moving_points[:, 0] >= 0)] moving = moving_points[:, :3].copy() moving *= moving_res[:3] for point in moving: tmp_point = itk.Point.D3() tmp_point[0] = point[0] tmp_point[1] = point[1] tmp_point[2] = point[2] rst_point = transform.TransformPoint(tmp_point) point[0] = rst_point[0] point[1] = rst_point[1] point[2] = rst_point[2] moving /= fixed_res[:3] print moving """ # image_type = fixedData.getITKImageType() # resampler = itk.ResampleImageFilter[image_type, image_type].New() # movingImage = movingData.getITKImage() # fixedImage = fixedData.getITKImage() # # resampler.SetTransform(transform) # resampler.SetInput(movingImage) # # region = fixedImage.GetLargestPossibleRegion() # # resampler.SetSize(region.GetSize()) # resampler.SetOutputSpacing(fixedImage.GetSpacing()) # resampler.SetOutputDirection(fixedImage.GetDirection()) # resampler.SetOutputOrigin(fixedImage.GetOrigin()) # resampler.SetDefaultPixelValue(0) # resampler.Update() # # outputImage = resampler.GetOutput() # image = itk.PyBuffer[image_type].GetArrayFromImage(outputImage) if isTime: return movingData.getData().copy(), { 'Contour': new_trans_points, 'Centerline': result_center_points }, [0, 0, 0], time2 - time1 return movingData.getData().copy(), { 'Contour': new_trans_points, 'Centerline': result_center_points }, [0, 0, 0]
def test_inf_var(self): (_, fv) = self.gp.inf(self.z) fvtrue = np.mat([7.339546, 5.321190]).T self.assertTrue(almostEqual(fvtrue, fv, 0.00001))
def test_inf_mean(self): (fm, _) = self.gp.inf(self.z) fmtrue = np.mat([1.0299129, 1.0030889]).T self.assertTrue(almostEqual(fmtrue, fm, 0.00001))
def test_SE_same(self): K = self.k(self.x) Ktrue = np.mat([[22026.46, 4093, 0.958], [4093, 22026.46, 0.178], [0.958, 0.178, 22026.46]]) self.assertTrue(almostEqual(Ktrue, K))
def NormalF(xv): 'Gaussian function' xv=matlib.mat(xv).reshape(m, 1) return coeff*np.exp(-0.5*float((xv-muv).T*covm_inv*(xv-muv)))
def test_SE_diff(self): K = self.k(self.x, self.z) Ktrue = np.mat([[332.40, 2184.98], [1788.81, 11758.44], [332.40, 14.41]]) self.assertTrue(almostEqual(Ktrue, K))
def setWidgetView(self, widget, color = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]): super(SurfaceView, self).setWidgetView(widget) if type(self.parent) is MdiChildRegistration: point_array_move = self.parent.getData('move').pointSet point_data_move = npy.array(point_array_move.getData('Contour')) point_data_result = npy.array(point_data_move) if point_data_result is None or not point_data_result.shape[0]: return self.spacing_mov = self.parent.getData('move').getResolution().tolist() self.spacing = self.parent.getData().getResolution().tolist() para = npy.array(self.parent.getData().getInfo().getData('transform')) R = ml.mat(para[:9].reshape(3, 3)) T = ml.mat(para[9:12].reshape(3, 1)) T = R.I * T T = -T point_data_result[:, :3] *= self.spacing_mov[:3] point_data_result[:, :3] = ml.mat(point_data_result[:, :3]) * R + ml.ones((point_data_result.shape[0], 1)) * T.T point_data_result[:, :3] /= self.spacing[:3] else: point_array_result = self.parent.getData().pointSet point_data_result = npy.array(point_array_result.getData('Contour')) point_array_move = point_array_result point_data_move = npy.array(point_array_move.getData('Contour')) zmin = int(npy.min(point_data_move[:, 2]) + 0.5) zmax = int(npy.max(point_data_move[:, 2]) + 0.5) self.spacing = self.parent.getData().getResolution().tolist() self.spacing = [float(x) / self.spacing[-1] for x in self.spacing] point_data_result[:, :2] *= self.spacing[:2] self.renderer = vtk.vtkRenderer() self.render_window = widget.GetRenderWindow() self.render_window.AddRenderer(self.renderer) self.window_interactor = vtk.vtkRenderWindowInteractor() self.render_window.SetInteractor(self.window_interactor) self.contours = [] self.delaunay3D = [] self.delaunayMapper = [] self.surface_actor = [] for cnt in range(3): self.contours.append(vtk.vtkPolyData()) self.delaunay3D.append(vtk.vtkDelaunay3D()) self.delaunayMapper.append(vtk.vtkDataSetMapper()) self.surface_actor.append(vtk.vtkActor()) point_result = point_data_result[npy.where(npy.round(point_data_result[:, -1]) == cnt)] point_move = point_data_move[npy.where(npy.round(point_data_move[:, -1]) == cnt)] if not point_result.shape[0]: continue self.cells = vtk.vtkCellArray() self.points = vtk.vtkPoints() l = 0 for i in range(zmin, zmax + 1): data = point_result[npy.where(npy.round(point_move[:, 2]) == i)] if data is not None: if data.shape[0] == 0: continue count = data.shape[0] points = vtk.vtkPoints() for j in range(count): points.InsertPoint(j, data[j, 0], data[j, 1], data[j, 2]) para_spline = vtk.vtkParametricSpline() para_spline.SetPoints(points) para_spline.ClosedOn() # The number of output points set to 10 times of input points numberOfOutputPoints = count * 10 self.cells.InsertNextCell(numberOfOutputPoints) for k in range(0, numberOfOutputPoints): t = k * 1.0 / numberOfOutputPoints pt = [0.0, 0.0, 0.0] para_spline.Evaluate([t, t, t], pt, [0] * 9) if pt[0] != pt[0]: print pt continue self.points.InsertPoint(l, pt[0], pt[1], pt[2]) self.cells.InsertCellPoint(l) l += 1 self.contours[cnt].SetPoints(self.points) self.contours[cnt].SetPolys(self.cells) self.delaunay3D[cnt].SetInput(self.contours[cnt]) self.delaunay3D[cnt].SetAlpha(2) self.delaunayMapper[cnt].SetInput(self.delaunay3D[cnt].GetOutput()) self.surface_actor[cnt].SetMapper(self.delaunayMapper[cnt]) self.surface_actor[cnt].GetProperty().SetDiffuseColor(color[cnt][0], color[cnt][1], color[cnt][2]) self.surface_actor[cnt].GetProperty().SetSpecularColor(1, 1, 1) self.surface_actor[cnt].GetProperty().SetSpecular(0.4) self.surface_actor[cnt].GetProperty().SetSpecularPower(50) self.renderer.AddViewProp(self.surface_actor[cnt]) self.renderer.ResetCamera() point = self.renderer.GetActiveCamera().GetFocalPoint() dis = self.renderer.GetActiveCamera().GetDistance() self.renderer.GetActiveCamera().SetViewUp(0, 0, 1) self.renderer.GetActiveCamera().SetPosition(point[0], point[1] - dis, point[2]) self.renderer.ResetCameraClippingRange() self.render_window.Render() # Manually set to trackball style self.window_interactor.SetKeyCode('t') self.window_interactor.CharEvent() self.window_interactor.GetInteractorStyle().AddObserver("KeyPressEvent", self.KeyPressCallback) self.window_interactor.GetInteractorStyle().AddObserver("CharEvent", self.KeyPressCallback)
def register(self, fixedData, movingData): clip1 = movingData.info.getData('clip') clip2 = fixedData.info.getData('clip') fixed_res = fixedData.getResolution().tolist() moving_res = movingData.getResolution().tolist() def iterationUpdate(): currentParameter = transform.GetParameters() print "M: %f P: %f %f %f" % ( optimizer.GetValue(), currentParameter.GetElement(0), currentParameter.GetElement(1), currentParameter.GetElement(2)) image_type = fixedData.getITKImageType() fixedImage = fixedData.getITKImage() movingImage = movingData.getITKImage() rescale_filter_fixed = itk.RescaleIntensityImageFilter[ image_type, image_type].New() rescale_filter_fixed.SetInput(fixedImage) rescale_filter_fixed.SetOutputMinimum(0) rescale_filter_fixed.SetOutputMaximum(255) rescale_filter_moving = itk.RescaleIntensityImageFilter[ image_type, image_type].New() rescale_filter_moving.SetInput(movingImage) rescale_filter_moving.SetOutputMinimum(0) rescale_filter_moving.SetOutputMaximum(255) registration = itk.ImageRegistrationMethod[image_type, image_type].New() imageMetric = itk.MattesMutualInformationImageToImageMetric[ image_type, image_type].New() transform = itk.TranslationTransform.New() optimizer = itk.RegularStepGradientDescentOptimizer.New() interpolator = itk.LinearInterpolateImageFunction[image_type, itk.D].New() registration.SetOptimizer(optimizer) registration.SetTransform(transform) registration.SetInterpolator(interpolator) registration.SetMetric(imageMetric) registration.SetFixedImage(rescale_filter_fixed.GetOutput()) registration.SetMovingImage(rescale_filter_moving.GetOutput()) registration.SetFixedImageRegion(fixedImage.GetBufferedRegion()) para = [ -clip1[4] * moving_res[0] + clip2[4] * fixed_res[0], -clip1[2] * moving_res[1] + clip2[2] * fixed_res[1], 0 ] transform.SetParameters(para) initialParameters = transform.GetParameters() print "Initial Registration Parameters " print initialParameters.GetElement(0) print initialParameters.GetElement(1) print initialParameters.GetElement(2) registration.SetInitialTransformParameters(initialParameters) # optimizer scale optimizerScales = itk.Array[itk.D](transform.GetNumberOfParameters()) optimizerScales.SetElement(0, 1.0) optimizerScales.SetElement(1, 1.0) optimizerScales.SetElement(2, 1.0) #imageMetric.UseAllPixelsOn() imageMetric.SetNumberOfHistogramBins(64) imageMetric.SetNumberOfSpatialSamples(800000) optimizer.MinimizeOn() optimizer.SetMaximumStepLength(2.00) optimizer.SetMinimumStepLength(0.001) optimizer.SetRelaxationFactor(0.8) optimizer.SetNumberOfIterations(200) iterationCommand = itk.PyCommand.New() iterationCommand.SetCommandCallable(iterationUpdate) optimizer.AddObserver(itk.IterationEvent(), iterationCommand) # Start the registration process try: registration.Update() except Exception: print "error" transform.SetParameters([0.0, 0.0, 0.0]) # Get the final parameters of the transformation finalParameters = registration.GetLastTransformParameters() print "Final Registration Parameters " print finalParameters.GetElement(0) print finalParameters.GetElement(1) print finalParameters.GetElement(2) # Use the final transform for resampling the moving image. parameters = transform.GetParameters() # Fail to use ResampleImageFilter x = parameters.GetElement(0) y = parameters.GetElement(1) z = parameters.GetElement(2) T = ml.mat([x, y, z]).T transform = sitk.Transform(3, sitk.sitkAffine) para = [1, 0, 0, 0, 1, 0, 0, 0, 1] + T.T.tolist()[0] transform.SetParameters(para) movingImage = movingData.getSimpleITKImage() fixedImage = fixedData.getSimpleITKImage() resultImage = sitk.Resample(movingImage, fixedImage, transform, sitk.sitkLinear, 0, sitk.sitkFloat32) return sitk.GetArrayFromImage(resultImage), {}, para + [0, 0, 0]
def analysis(self, data, point_data_fix=None, point_data_mov=None, point_data_mask=None, spacing_mov=None, useResult=False): if point_data_fix is None: point_data_fix = self.gui.dataModel[ data.getFixedIndex()].getPointSet('Contour').copy() point_data_mov = self.gui.dataModel[ data.getMovingIndex()].getPointSet('Contour').copy() point_data_mask = self.gui.dataModel[ data.getMovingIndex()].getPointSet('Mask').copy() spacing_mov = self.gui.dataModel[ data.getMovingIndex()].getResolution().tolist() self.spacing = data.getResolution().tolist() point_data_fix = point_data_fix[point_data_fix[:, 0] >= 0] bif = db.getBifurcation(point_data_fix) point_data_fix = util.augmentPointset(point_data_fix, 3, -1, bif, nn=20) point_data_fix[:, :3] *= self.spacing[:3] if point_data_mov is not None: point_data_mov = point_data_mov[point_data_mov[:, 0] >= 0] if not useResult: para = npy.array(data.info.getData('transform')).flatten() point_data_result = point_data_mov.copy() for point in point_data_mask: point_data_result = npy.delete( point_data_result, npy.where( (npy.abs(point_data_result[:, 2] - point[2]) < 0.0001) & (npy.round(point_data_result[:, -1]) == point[3])), axis=0) point_data_result[:, :3] *= spacing_mov[:3] R = ml.mat(para[:9]).reshape(3, 3) T = ml.mat(para[9:12]).T if para.shape[0] > 12: C = ml.mat(para[12:]).T else: C = ml.zeros([3, 1], dtype=npy.float32) T = R.I * T T = -T point_data_result[:, :3] = util.applyTransformForPoints( point_data_result[:, :3], npy.array([1.0, 1, 1]), npy.array([1.0, 1, 1]), R, T, C) else: point_data_result = data.getPointSet('Contour').copy() point_data_result = point_data_result[point_data_result[:, -1] >= 0] point_data_result[:, :3] *= self.spacing[:3] targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()] targetVertices = [ vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray() ] target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()] Locator = [ vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator() ] label_dis = [3, 2, 1] for i in range(3): for x in point_data_fix[ npy.round(point_data_fix[:, 3]) != label_dis[i]]: id = targetPoints[i].InsertNextPoint(x[0], x[1], x[2]) targetVertices[i].InsertNextCell(1) targetVertices[i].InsertCellPoint(id) target[i].SetPoints(targetPoints[i]) target[i].SetVerts(targetVertices[i]) Locator[i].SetDataSet(target[i]) Locator[i].SetNumberOfCellsPerBucket(1) Locator[i].BuildLocator() ''' Locator = vtk.vtkCellLocator() targetPoints = vtk.vtkPoints() targetVertices = vtk.vtkCellArray() target = vtk.vtkPolyData() for x in point_data_fix: id = targetPoints.InsertNextPoint(x[0], x[1], x[2]) targetVertices.InsertNextCell(1) targetVertices.InsertCellPoint(id) target.SetPoints(targetPoints) target.SetVerts(targetVertices) Locator.SetDataSet(target) Locator.SetNumberOfCellsPerBucket(1) Locator.BuildLocator() ''' id1 = id2 = vtk.mutable(0) dist = vtk.mutable(0.0) outPoint = [0.0, 0.0, 0.0] cnt_num = npy.array([0, 0, 0]) mean_dis = npy.array([0.0, 0.0, 0.0]) max_dis = npy.array([0.0, 0.0, 0.0]) for pt in point_data_result: cnt = int(pt[-1] + 0.5) Locator[cnt].FindClosestPoint(pt[:3].tolist(), outPoint, id1, id2, dist) dis = npy.sqrt(npy.sum((npy.array(outPoint) - pt[:3])**2)) mean_dis[cnt] += dis max_dis[cnt] = npy.max([max_dis[cnt], dis]) cnt_num[cnt] += 1 cnt_total = npy.sum(cnt_num) mean_whole = npy.sum(mean_dis) / cnt_total mean_dis /= cnt_num mean_dis[ mean_dis != mean_dis] = 0 # Replace the NAN in the mean distance max_whole = npy.max(max_dis) if self.gui is not None: message = "Error on Vessel 0: %0.2fmm (Total %d slices)\nError on Vessel 1: %0.2fmm (Total %d slices)\nError on Vessel 2: %0.2fmm (Total %d slices)\nWhole Error: %0.2fmm (Total %d slices)\n" \ % (mean_dis[0], cnt_num[0], mean_dis[1], cnt_num[1], mean_dis[2], cnt_num[2], mean_whole, cnt_total) + \ "-----------------------------------------------------------------------------\n" + \ "Max Error on Vessel 0: %0.2fmm\nMax Error on Vessel 1: %0.2fmm\nMax Error on Vessel 2: %0.2fmm\nTotal Max Error: %0.2fmm" \ % (max_dis[0], max_dis[1], max_dis[2], npy.max(max_dis)) self.gui.showErrorMessage("Centerline Registration Error", message) return mean_dis, mean_whole, max_dis, max_whole
def permute_knife(knife, pp): y = [] for p in pp: y.append(knife[0, p]) return mat.mat(np.array(y))
fig0_subplot=fig0.add_subplot(111, aspect='equal') fig0_subplot.grid(True) #plot fig0_subplot.clear() # for i, muv, covm in zip(range(i), muvl, covml): e=Covm2Ellipse(muvl[0], covml[0], _color='g') fig0_subplot.add_artist(e) e=Covm2Ellipse(muvl[1], covml[1], _color='r') fig0_subplot.add_artist(e) fig0_subplot.plot(datam[0, :], datam[1, :], 'ob') fig0_subplot.axis([-5, 5, -5, 5]) fig0 fig1=plt.figure(1) subplot1=fig1.add_subplot(111, aspect='equal') mum=matlib.mat(random.uniform(-2, 2, (2, 2))) test_covml=[GetCovm2D(2, 4, 60), GetCovm2D(3, 1, 90)] el=[Covm2Ellipse(mum[:, 0], test_covml[0], _color='r'), Covm2Ellipse(mum[:, 1], test_covml[1], _color='g')] #e1.set_color('r') #e1.set_alpha(0.5) subplot1.add_artist(el[0]) subplot1.add_artist(el[1]) subplot1.axis([-4, 4, -4, 4]) subplot1.grid(True) datam1=random.multivariate_normal(np.array(mum[:, 0]).reshape(-1), test_covml[0], 50) datam2=random.multivariate_normal(np.array(mum[:, 1]).reshape(-1), test_covml[1], 55) datam=np.append(datam1, datam2, 0).T; subplot1.plot(datam1[:,0], datam1[:, 1], 'ro') subplot1.plot(datam2[:,0], datam2[:, 1], 'go') fig1 #initialization
def compute_essential(F, K): """ Compute the Essential matrix, and R1, R2 """ return (K.T).dot(npm.mat(F)).dot(K)
def coord(*args): """Return a column vector with elements args""" return np.mat([args], dtype=npfloat).T
def __init__(self, alpha, A, dist, *args, **kwds): super(PhaseType, self).__init__(dist, *args, **kwds) self.alpha = ml.mat(alpha) self.A = ml.mat(A) self.dist._set_pars(alpha, A)
__author__ = 'oyakov' import numpy.matlib as ml a = ml.mat([[1, 2, 3], [3, 2, 1], [1, 1, 1]]) b = ml.mat([[1, 2, 3], [3, 2, 1], [1, 1, 1]]) print(a + b)
def register(self, fixedData, movingData, discard=False): index = self.gui.getDataIndex({ 'Contour': 0, 'Centerline': 1 }, 'Select the object') if index is None: return None, None, None if index == 0: fixed_points = fixedData.getPointSet('Contour') moving_points = movingData.getPointSet('Contour') else: fixed_points = fixedData.getPointSet('Centerline') moving_points = movingData.getPointSet('Centerline') fixed_res = fixedData.getResolution().tolist() moving_res = movingData.getResolution().tolist() fixed_points = fixed_points.copy()[npy.where(fixed_points[:, 0] >= 0)] moving_points = moving_points.copy()[npy.where( moving_points[:, 0] >= 0)] # Use the bifurcation as the initial position fixed_bif = db.getBifurcation(fixed_points) moving_bif = db.getBifurcation(moving_points) if (fixed_bif < 0) or (moving_bif < 0): fixed_min = 0 else: temp = moving_points[:, 2:] moving_delta = moving_bif - npy.min( temp[npy.where(npy.round(temp[:, 1]) == 0), 0]) fixed_min = fixed_bif - moving_delta * moving_res[-1] / fixed_res[ -1] #print moving_res #print fixed_res # Augmentation of pointset fixed = fixed_points[npy.where(fixed_points[:, 2] >= fixed_min)] moving = moving_points.copy() fixed = util.augmentPointset(fixed, int(fixed_res[-1] / moving_res[-1] + 0.5), moving.shape[0], fixed_bif) moving = util.augmentPointset( moving, int(moving_res[-1] / fixed_res[-1] + 0.5), fixed.shape[0], moving_bif) fixed = fixed[:, :3] moving = moving[:, :3] fixed[:, :3] *= fixed_res[:3] moving[:, :3] *= moving_res[:3] if (fixed_bif >= 0) and (moving_bif >= 0): fixed[:, 2] -= (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) print fixed.shape[0], moving.shape[0] #return None, None, None sourcePoints = vtk.vtkPoints() sourceVertices = vtk.vtkCellArray() for x in moving: id = sourcePoints.InsertNextPoint(x[0], x[1], x[2]) sourceVertices.InsertNextCell(1) sourceVertices.InsertCellPoint(id) source = vtk.vtkPolyData() source.SetPoints(sourcePoints) source.SetVerts(sourceVertices) targetPoints = vtk.vtkPoints() targetVertices = vtk.vtkCellArray() for x in fixed: id = targetPoints.InsertNextPoint(x[0], x[1], x[2]) targetVertices.InsertNextCell(1) targetVertices.InsertCellPoint(id) target = vtk.vtkPolyData() target.SetPoints(targetPoints) target.SetVerts(targetVertices) icp = vtk.vtkIterativeClosestPointTransform() icp.SetSource(source) icp.SetTarget(target) icp.GetLandmarkTransform().SetModeToRigidBody() icp.Modified() icp.Update() icp_filter = vtk.vtkTransformPolyDataFilter() icp_filter.SetInput(source) icp_filter.SetTransform(icp) icp_filter.Update() # Get the result transformation parameters matrix = icp.GetMatrix() T = ml.mat([ matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3) ]).T R = ml.mat([[ matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2) ], [ matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2) ], [ matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2) ]]).I if (fixed_bif >= 0) and (moving_bif >= 0): T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) moving_points = movingData.getPointSet('Contour').copy() moving_center = movingData.getPointSet('Centerline').copy() new_trans_points, result_center_points = util.resliceTheResultPoints( moving_points, moving_center, 20, moving_res, fixed_res, discard, R, T) T = -T T = R * T transform = sitk.Transform(3, sitk.sitkAffine) para = R.reshape(1, -1).tolist()[0] + T.T.tolist()[0] transform.SetParameters(para) movingImage = movingData.getSimpleITKImage() fixedImage = fixedData.getSimpleITKImage() resultImage = sitk.Resample(movingImage, fixedImage, transform, sitk.sitkLinear, 0, sitk.sitkFloat32) return sitk.GetArrayFromImage(resultImage), { 'Contour': trans_points, 'Centerline': result_center_points }, para + [0, 0, 0]
def __init__(self, config): self.A = np.mat(config["A"]) self.B = np.mat(config["B"]) self.C = np.mat(config["C"]) self.D = np.mat(config["D"]) self.F = np.mat(config["F"]) self.K = np.mat(config["K"]) self.Ki = np.mat(config["Ki"]) self.L = np.mat(config["L"]) self.ud = np.mat(config["ud"]) self.xd = np.mat(config["xd"]) self.r0 = np.mat(config["r0"]) self.u0 = np.mat(config["u0"]) self.dt = config["dt"] self.AmLC = self.A - self.L * self.C self.BmLD = self.B - self.L * self.D q, n = self.C.shape self.xh = np.zeros((n, 1)) self.xi = np.zeros((q, 1))
def projMatrix(alpha, h): ch = math.sqrt(1 - h**2) return np.mat([[math.cos(alpha), math.sin(alpha), 0], [-math.sin(alpha) * ch, math.cos(alpha) * ch, h]])
def register(self, fixedData, movingData, index = -1, discard = False, delta = 0, fov = 9999999.0, down_fix = 1, down_mov = 1, occ = 9999999.0, op = False, useMask = False, isTime = False, MaxRate = 0.2, aug = False, distance_fix = 0.3, distance_mov = 0.1): time1 = time.time() if index == -1: index = self.gui.getDataIndex({'Contour': 0, 'Centerline': 1}, 'Select the object') if index is None: return None, None, None if index == 0: fixed_points = fixedData.getPointSet('Contour').copy() moving_points = movingData.getPointSet('Contour').copy() else: fixed_points = fixedData.getPointSet('Centerline').copy() moving_points = movingData.getPointSet('Centerline').copy() fixed_bif = db.getBifurcation(fixed_points) moving_bif = db.getBifurcation(moving_points) if useMask: mask_points = movingData.getPointSet('Mask') for point in mask_points: moving_points = npy.delete(moving_points, npy.where((npy.abs(moving_points[:, 2] - point[2]) < 0.0001) & (npy.round(moving_points[:, -1]) == point[3])), axis = 0) fixed_res = fixedData.getResolution().tolist() moving_res = movingData.getResolution().tolist() fixed_points = fixed_points[npy.where(fixed_points[:, 0] >= 0)] moving_points = moving_points[npy.where(moving_points[:, 0] >= 0)] # Use the bifurcation as the initial position if (fixed_bif < 0) or (moving_bif < 0): fixed_min = 0 # Augmentation of pointset fixed = fixed_points.copy() moving = moving_points.copy() if index == 1 and aug: fixed = util.augmentCenterline(fixed, 1, 10) moving = util.augmentCenterline(moving, 1, 10) fix_dis = util.getAxisSin(fixed, 3 / fixed_res[2]) * distance_fix mov_dis = util.getAxisSin(moving, 3 / moving_res[2]) * distance_mov fixed = util.resampleCenterline(fixed, fix_dis / fixed_res[2]) moving = util.resampleCenterline(moving, mov_dis / moving_res[2]) fixed = fixed[npy.cast[npy.int32](npy.abs(fixed[:, 2] - fixed_bif)) % down_fix == 0] moving = moving[npy.cast[npy.int32](npy.abs(moving[:, 2] - moving_bif)) % down_mov == 0] fixed[:, :3] *= fixed_res[:3] moving[:, :3] *= moving_res[:3] if (fixed_bif >= 0) and (moving_bif >= 0): fixed[:, 2] -= (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta) # Prepare for ICP LandmarkTransform = vtk.vtkLandmarkTransform() LandmarkTransform.SetModeToRigidBody() MaxIterNum = 50 #MaxNum = 600 MaxNum = int(MaxRate * moving.shape[0] + 0.5) targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()] targetVertices = [vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray()] target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()] Locator = [vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator()] if index == 0: if not op: label_dis = [3, 3, 3] else: label_dis = [3, 2, 1] else: if op: label_dis = [3, 3, 3] else: label_dis = [3, 2, 1] for i in range(3): for x in fixed[npy.round(fixed[:, 3]) != label_dis[i]]: id = targetPoints[i].InsertNextPoint(x[0], x[1], x[2]) targetVertices[i].InsertNextCell(1) targetVertices[i].InsertCellPoint(id) target[i].SetPoints(targetPoints[i]) target[i].SetVerts(targetVertices[i]) Locator[i].SetDataSet(target[i]) Locator[i].SetNumberOfCellsPerBucket(1) Locator[i].BuildLocator() step = 1 if moving.shape[0] > MaxNum: ind = moving[:, 2].argsort() moving = moving[ind, :] step = moving.shape[0] / MaxNum nb_points = moving.shape[0] / step accumulate = vtk.vtkTransform() accumulate.PostMultiply() points1 = vtk.vtkPoints() points1.SetNumberOfPoints(nb_points) label = npy.zeros([MaxNum * 2], dtype = npy.int8) j = 0 for i in range(nb_points): points1.SetPoint(i, moving[j][0], moving[j][1], moving[j][2]) label[i] = moving[j][3] j += step closestp = vtk.vtkPoints() closestp.SetNumberOfPoints(nb_points) points2 = vtk.vtkPoints() points2.SetNumberOfPoints(nb_points) id1 = id2 = vtk.mutable(0) dist = vtk.mutable(0.0) outPoint = [0.0, 0.0, 0.0] p1 = [0.0, 0.0, 0.0] p2 = [0.0, 0.0, 0.0] iternum = 0 a = points1 b = points2 ''' path = sys.argv[0] if os.path.isfile(path): path = os.path.dirname(path) path += '/Data/Transform' wfile = open("%s/transform.txt" % path, 'w') matrix = accumulate.GetMatrix() T = ml.mat([matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3)]).T; R = ml.mat([[matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2)], [matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2)], [matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2)]]).I if (fixed_bif >= 0) and (moving_bif >= 0): T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta) saveTransform(wfile, T, R) ''' while True: for i in range(nb_points): Locator[label[i]].FindClosestPoint(a.GetPoint(i), outPoint, id1, id2, dist) closestp.SetPoint(i, outPoint) LandmarkTransform.SetSourceLandmarks(a) LandmarkTransform.SetTargetLandmarks(closestp) LandmarkTransform.Update() accumulate.Concatenate(LandmarkTransform.GetMatrix()) iternum += 1 if iternum >= MaxIterNum: break dist_err = 0 for i in range(nb_points): a.GetPoint(i, p1) LandmarkTransform.InternalTransformPoint(p1, p2) b.SetPoint(i, p2) dist_err += npy.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 + (p1[2] - p2[2]) ** 2) dist_err /= nb_points print "iter = %d: %f" % (iternum, dist_err) ''' matrix = accumulate.GetMatrix() T = ml.mat([matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3)]).T; R = ml.mat([[matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2)], [matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2)], [matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2)]]).I; if (fixed_bif >= 0) and (moving_bif >= 0): T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2]) saveTransform(wfile, T, R) ''' b, a = a, b time2 = time.time() #wfile.close() # Get the result transformation parameters matrix = accumulate.GetMatrix() T = ml.mat([matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3)]).T R = ml.mat([[matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2)], [matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2)], [matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2)]]).I #T = ml.mat([0, 0, 0]).T #R = ml.mat([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).T if (fixed_bif >= 0) and (moving_bif >= 0): T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta) # Resample the moving contour moving_points = movingData.getPointSet('Contour').copy() moving_center = movingData.getPointSet('Centerline').copy() #new_trans_points, result_center_points = util.resliceTheResultPoints(moving_points, moving_center, 20, moving_res, fixed_res, discard, R, T) new_trans_points, result_center_points = moving_points, moving_center result_center_points[:, :3] = util.applyTransformForPoints(result_center_points[:, :3], moving_res, fixed_res, R, T, ml.zeros([3, 1], dtype = npy.float32)) new_trans_points[:, :3] = util.applyTransformForPoints(new_trans_points[:, :3], moving_res, fixed_res, R, T, ml.zeros([3, 1], dtype = npy.float32)) T = -T T = R * T transform = sitk.Transform(3, sitk.sitkAffine) para = R.reshape(1, -1).tolist()[0] + T.T.tolist()[0] transform.SetParameters(para) movingImage = movingData.getSimpleITKImage() fixedImage = fixedData.getSimpleITKImage() resultImage = sitk.Resample(movingImage, fixedImage, transform, sitk.sitkLinear, 0, sitk.sitkFloat32) if isTime: return sitk.GetArrayFromImage(resultImage), {'Contour': new_trans_points, 'Centerline': result_center_points}, para + [0, 0, 0], time2 - time1 return sitk.GetArrayFromImage(resultImage), {'Contour': new_trans_points, 'Centerline': result_center_points}, para + [0, 0, 0]
def test_translate(self): t = Translate(1, 2) m = mt.mat('1 0 0; 0 1 0; 1 2 1') self.assertTrue((t.mat == m).all())
def register(self, fixedData, movingData, index=-1, discard=False, delta=0, fov=9999999.0, down_fix=1, down_mov=1, occ=9999999.0, useMask=False, isTime=False, MaxRate=0.2, aug=False, distance_fix=0.3, distance_mov=0.1, w_wrong=1.5): time1 = time.time() if index == -1: index = self.gui.getDataIndex({ 'Contour': 0, 'Centerline': 1 }, 'Select the object') if index is None: return None, None, None if index == 0: fixed_points = fixedData.getPointSet('Contour').copy() moving_points = movingData.getPointSet('Contour').copy() else: fixed_points = fixedData.getPointSet('Centerline').copy() moving_points = movingData.getPointSet('Centerline').copy() fixed_bif = db.getBifurcation(fixed_points) moving_bif = db.getBifurcation(moving_points) if useMask: mask_points = movingData.getPointSet('Mask') for point in mask_points: moving_points = npy.delete( moving_points, npy.where( (npy.abs(moving_points[:, 2] - point[2]) < 0.0001) & (npy.round(moving_points[:, -1]) == point[3])), axis=0) fixed_res = fixedData.getResolution().tolist() moving_res = movingData.getResolution().tolist() fixed_points = fixed_points[npy.where(fixed_points[:, 0] >= 0)] moving_points = moving_points[npy.where(moving_points[:, 0] >= 0)] # Use the bifurcation as the initial position if (fixed_bif < 0) or (moving_bif < 0): fixed_min = 0 # Augmentation of pointset fixed = fixed_points.copy() moving = moving_points.copy() if index == 1 and aug: fixed = util.augmentCenterline(fixed, 1, 10) moving = util.augmentCenterline(moving, 1, 10) fix_dis = util.getAxisSin(fixed, 3 / fixed_res[2]) * distance_fix mov_dis = util.getAxisSin(moving, 3 / moving_res[2]) * distance_mov fixed = util.resampleCenterline(fixed, fix_dis / fixed_res[2]) moving = util.resampleCenterline(moving, mov_dis / moving_res[2]) fixed = fixed[npy.cast[npy.int32](npy.abs(fixed[:, 2] - fixed_bif)) % down_fix == 0] moving = moving[npy.cast[npy.int32](npy.abs(moving[:, 2] - moving_bif)) % down_mov == 0] fixed[:, :3] *= fixed_res[:3] moving[:, :3] *= moving_res[:3] if (fixed_bif >= 0) and (moving_bif >= 0): fixed[:, 2] -= (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta) # Prepare for ICP LandmarkTransform = vtk.vtkLandmarkTransform() LandmarkTransform.SetModeToRigidBody() MaxIterNum = 50 #MaxNum = 600 MaxNum = int(MaxRate * moving.shape[0] + 0.5) targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()] targetVertices = [ vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray() ] target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()] Locator = [ vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator() ] for i in range(3): for x in fixed[npy.round(fixed[:, 3]) == i]: id = targetPoints[i].InsertNextPoint(x[0], x[1], x[2]) targetVertices[i].InsertNextCell(1) targetVertices[i].InsertCellPoint(id) target[i].SetPoints(targetPoints[i]) target[i].SetVerts(targetVertices[i]) Locator[i].SetDataSet(target[i]) Locator[i].SetNumberOfCellsPerBucket(1) Locator[i].BuildLocator() step = 1 if moving.shape[0] > MaxNum: ind = moving[:, 2].argsort() moving = moving[ind, :] step = moving.shape[0] / MaxNum nb_points = moving.shape[0] / step accumulate = vtk.vtkTransform() accumulate.PostMultiply() points1 = vtk.vtkPoints() points1.SetNumberOfPoints(nb_points) label = npy.zeros([MaxNum * 2], dtype=npy.int8) j = 0 for i in range(nb_points): points1.SetPoint(i, moving[j][0], moving[j][1], moving[j][2]) label[i] = moving[j][3] j += step closestp = vtk.vtkPoints() closestp.SetNumberOfPoints(nb_points) points2 = vtk.vtkPoints() points2.SetNumberOfPoints(nb_points) id1 = id2 = vtk.mutable(0) dist = vtk.mutable(0.0) outPoint = [0.0, 0.0, 0.0] p1 = [0.0, 0.0, 0.0] p2 = [0.0, 0.0, 0.0] iternum = 0 a = points1 b = points2 w_mat = [[1, w_wrong, w_wrong], [w_wrong, 1, 99999999], [w_wrong, 99999999, 1]] while True: for i in range(nb_points): min_dist = 99999999 min_outPoint = [0.0, 0.0, 0.0] for j in range(3): Locator[j].FindClosestPoint(a.GetPoint(i), outPoint, id1, id2, dist) dis = npy.sqrt( npy.sum((npy.array(outPoint) - a.GetPoint(i))**2)) if dis * w_mat[label[i]][j] < min_dist: min_dist = dis * w_mat[label[i]][j] min_outPoint = copy.deepcopy(outPoint) closestp.SetPoint(i, min_outPoint) LandmarkTransform.SetSourceLandmarks(a) LandmarkTransform.SetTargetLandmarks(closestp) LandmarkTransform.Update() accumulate.Concatenate(LandmarkTransform.GetMatrix()) iternum += 1 if iternum >= MaxIterNum: break for i in range(nb_points): a.GetPoint(i, p1) LandmarkTransform.InternalTransformPoint(p1, p2) b.SetPoint(i, p2) b, a = a, b time2 = time.time() # Get the result transformation parameters matrix = accumulate.GetMatrix() T = ml.mat([ matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3) ]).T R = ml.mat([[ matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2) ], [ matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2) ], [ matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2) ]]).I if (fixed_bif >= 0) and (moving_bif >= 0): T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta) # Resample the moving contour moving_points = movingData.getPointSet('Contour').copy() moving_center = movingData.getPointSet('Centerline').copy() new_trans_points, result_center_points = moving_points, moving_center result_center_points[:, :3] = util.applyTransformForPoints( result_center_points[:, :3], moving_res, fixed_res, R, T, ml.zeros([3, 1], dtype=npy.float32)) new_trans_points[:, :3] = util.applyTransformForPoints( new_trans_points[:, :3], moving_res, fixed_res, R, T, ml.zeros([3, 1], dtype=npy.float32)) T = -T T = R * T transform = sitk.Transform(3, sitk.sitkAffine) para = R.reshape(1, -1).tolist()[0] + T.T.tolist()[0] transform.SetParameters(para) movingImage = movingData.getSimpleITKImage() fixedImage = fixedData.getSimpleITKImage() resultImage = sitk.Resample(movingImage, fixedImage, transform, sitk.sitkLinear, 0, sitk.sitkFloat32) if isTime: return sitk.GetArrayFromImage(resultImage), { 'Contour': new_trans_points, 'Centerline': result_center_points }, para + [0, 0, 0], time2 - time1 return sitk.GetArrayFromImage(resultImage), { 'Contour': new_trans_points, 'Centerline': result_center_points }, para + [0, 0, 0]
def process(self, dataset, i): def autoDetectContour(point, cnt, start, end, delta, res, type): self.new_points = npy.append(self.new_points, point, 0) points = point[:, :-2] d = 20 count = 0 for i in range(start + delta, end + delta, delta): center = calCentroidFromContour(points).reshape(2) image = dataset[type].getData()[i, :, :].transpose().copy() image = (image - npy.min(image)) / (npy.max(image) - npy.min(image)) * 255 down = npy.max([npy.ceil(center[0] - d / res[0]), 0]) up = npy.min( [npy.floor(center[0] + d / res[0]), image.shape[0]]) left = npy.max([npy.ceil(center[1] - d / res[1]), 0]) right = npy.min( [npy.floor(center[1] + d / res[1]), image.shape[1]]) crop_image = image[down:up, left:right] center -= [down, left] result = ac_segmentation(center, crop_image) a1 = ac_area(points.transpose(), image.shape) a2 = ac_area(result, crop_image.shape) rate = a2 * 1.0 / a1 if rate >= min(1.5 + count * 0.2, 2.1) or rate <= 0.7: temp_array = points.copy() if cnt != 1 and rate > 0.7: count += 1 else: temp_array = result.transpose().copy() temp_array[:, :2] += [down, left] count = 0 points = temp_array.copy() temp_array = npy.insert(temp_array, 2, [[i], [cnt]], 1) self.new_points = npy.append(self.new_points, temp_array, 0) sys.stdout.write(str(i) + ',') sys.stdout.flush() print ' ' # Segmentation of data print 'Segment Data %s...' % self.ini.file.name_result[i] tmp = dataset['fix'].pointSet.data['Contour'] tmp = tmp[tmp[:, 0] >= 0] self.new_points = npy.array([[-1, -1, -1, -1]], dtype=npy.float32) bottom = int(npy.round(npy.min(tmp[:, 2]))) bif = int(db.getBifurcation(tmp) + 0.5) up = int(npy.round(npy.max(tmp[:, 2]))) bottom += (bif - bottom) / 2 up -= (up - bif) / 2 point_vital = [0] * 3 point_vital[0] = tmp[(npy.round(tmp[:, -1]) == 0) & (npy.round(tmp[:, 2]) == bottom)].copy() point_vital[1] = tmp[(npy.round(tmp[:, -1]) == 1) & (npy.round(tmp[:, 2]) == up)].copy() point_vital[2] = tmp[(npy.round(tmp[:, -1]) == 2) & (npy.round(tmp[:, 2]) == up)].copy() autoDetectContour(point_vital[0], 0, bottom, bif, 1, dataset['fix'].getResolution().tolist(), 'fix') autoDetectContour(point_vital[1], 1, up, bif, -1, dataset['fix'].getResolution().tolist(), 'fix') autoDetectContour(point_vital[2], 2, up, bif, -1, dataset['fix'].getResolution().tolist(), 'fix') print ' ' print 'Finish segmentation for fix data. ' pointset = {'Contour': self.new_points} dataset['fix'].pointSet.data['Centerline'] = calCenterlineFromContour( pointset) self.new_points_fix = self.new_points.copy() # For mov data tmp = dataset['mov'].pointSet.data['Contour'] tmp = tmp[tmp[:, 0] >= 0] self.new_points = npy.array([[-1, -1, -1, -1]], dtype=npy.float32) bottom = int(npy.round(npy.min(tmp[:, 2]))) bif = int(db.getBifurcation(tmp) + 0.5) up = int(npy.round(npy.max(tmp[:, 2]))) bottom += (bif - bottom) / 2 up -= (up - bif) / 2 point_vital = [0] * 3 point_vital[0] = tmp[(npy.round(tmp[:, -1]) == 0) & (npy.round(tmp[:, 2]) == bottom)].copy() point_vital[1] = tmp[(npy.round(tmp[:, -1]) == 1) & (npy.round(tmp[:, 2]) == up)].copy() point_vital[2] = tmp[(npy.round(tmp[:, -1]) == 2) & (npy.round(tmp[:, 2]) == up)].copy() autoDetectContour(point_vital[0], 0, bottom, bif, 1, dataset['mov'].getResolution().tolist(), 'mov') autoDetectContour(point_vital[1], 1, up, bif, -1, dataset['mov'].getResolution().tolist(), 'mov') autoDetectContour(point_vital[2], 2, up, bif, -1, dataset['mov'].getResolution().tolist(), 'mov') print ' ' print 'Finish segmentation for mov data. ' pointset = {'Contour': self.new_points} dataset['mov'].pointSet.data['Centerline'] = calCenterlineFromContour( pointset) self.new_points_mov = self.new_points.copy() # ICP with centerline without label print 'Register Data %s with ICP(centerline) without label...' % self.ini.file.name_result[ i] data, point, para = self.icp.register(dataset['fix'], dataset['mov'], 1, op=True) resultData = db.ResultData(data, db.ImageInfo(dataset['fix'].info.data), point) resultData.info.addData('fix', 1) resultData.info.addData('move', 2) resultData.info.addData('transform', para) print 'Done!' mean_dis, mean_whole, max_dis, max_whole = self.surfaceerror.analysis( resultData, dataset['fix'].getPointSet('Contour').copy(), dataset['mov'].getPointSet('Contour').copy(), dataset['mov'].getPointSet('Mask').copy(), dataset['mov'].getResolution().tolist()) print 'Contour Error Done! Whole mean is %0.2fmm.' % mean_whole dice_index, dice_index_all = self.areaerror.analysis( resultData, dataset['fix'].getPointSet('Contour').copy()) print 'Area Error Done! Whole Dice index is %0.3f.' % dice_index_all self.sheet2.write(0, i + 2, self.ini.file.name_result[i]) for j in range(3): self.sheet2.write(j + 1, i + 2, mean_dis[j]) self.sheet2.write(j + 5, i + 2, max_dis[j]) self.sheet2.write(j + 9, i + 2, dice_index[j]) self.sheet2.write(4, i + 2, mean_whole) self.sheet2.write(8, i + 2, max_whole) self.sheet2.write(12, i + 2, dice_index_all) self.book.save(self.path + self.ini.file.savedir + 'multicontrast_seg_feature.xls') del data, point, resultData # ICP with centerline with label print 'Register Data %s with ICP(centerline) with label...' % self.ini.file.name_result[ i] data, point, para = self.icp.register(dataset['fix'], dataset['mov'], 1, op=False) resultData = db.ResultData(data, db.ImageInfo(dataset['fix'].info.data), point) resultData.info.addData('fix', 1) resultData.info.addData('move', 2) resultData.info.addData('transform', para) print 'Done!' mean_dis, mean_whole, max_dis, max_whole = self.surfaceerror.analysis( resultData, dataset['fix'].getPointSet('Contour').copy(), dataset['mov'].getPointSet('Contour').copy(), dataset['mov'].getPointSet('Mask').copy(), dataset['mov'].getResolution().tolist()) print 'Contour Error Done! Whole mean is %0.2fmm.' % mean_whole dice_index, dice_index_all = self.areaerror.analysis( resultData, dataset['fix'].getPointSet('Contour').copy()) print 'Area Error Done! Whole Dice index is %0.3f.' % dice_index_all self.sheet4.write(0, i + 2, self.ini.file.name_result[i]) for j in range(3): self.sheet4.write(j + 1, i + 2, mean_dis[j]) self.sheet4.write(j + 5, i + 2, max_dis[j]) self.sheet4.write(j + 9, i + 2, dice_index[j]) self.sheet4.write(4, i + 2, mean_whole) self.sheet4.write(8, i + 2, max_whole) self.sheet4.write(12, i + 2, dice_index_all) self.book.save(self.path + self.ini.file.savedir + 'multicontrast_seg_feature.xls') del data, point, resultData fix_points = dataset['fix'].getPointSet('Contour').copy() dataset['fix'].pointSet.data['Contour'] = self.new_points_fix mov_points = dataset['mov'].getPointSet('Contour').copy() dataset['mov'].pointSet.data['Contour'] = self.new_points_mov print 'Saving Data %s...' % self.ini.file.name_result[i] db.saveMatData( self.path + self.ini.file.savedir + self.ini.file.name_result[i] + '_snap.mat', [dataset['fix']], 0) db.saveMatData( self.path + self.ini.file.savedir + self.ini.file.name_result[i] + '_merge.mat', [dataset['mov']], 0) print 'Done!' # ICP with contour without label print 'Register Data %s with ICP(contour) without label...' % self.ini.file.name_result[ i] data, point, para = self.icp.register(dataset['fix'], dataset['mov'], 0, op=False) resultData = db.ResultData(data, db.ImageInfo(dataset['fix'].info.data), point) resultData.info.addData('fix', 1) resultData.info.addData('move', 2) resultData.info.addData('transform', para) print 'Done!' mean_dis, mean_whole, max_dis, max_whole = self.surfaceerror.analysis( resultData, fix_points.copy(), mov_points.copy(), dataset['mov'].getPointSet('Mask').copy(), dataset['mov'].getResolution().tolist()) print 'Contour Error Done! Whole mean is %0.2fmm.' % mean_whole para = resultData.info.getData('transform') R = ml.mat(para[:9]).reshape(3, 3) T = ml.mat(para[9:12]).T T = R.I * T T = -T tmp_con, result_center_points = util.resliceTheResultPoints( mov_points, None, 20, dataset['mov'].getResolution().tolist(), dataset['fix'].getResolution().tolist(), False, R, T) resultData.pointSet.data['Contour'] = tmp_con dice_index, dice_index_all = self.areaerror.analysis( resultData, fix_points.copy()) print 'Area Error Done! Whole Dice index is %0.3f.' % dice_index_all self.sheet1.write(0, i + 2, self.ini.file.name_result[i]) for j in range(3): self.sheet1.write(j + 1, i + 2, mean_dis[j]) self.sheet1.write(j + 5, i + 2, max_dis[j]) self.sheet1.write(j + 9, i + 2, dice_index[j]) self.sheet1.write(4, i + 2, mean_whole) self.sheet1.write(8, i + 2, max_whole) self.sheet1.write(12, i + 2, dice_index_all) self.book.save(self.path + self.ini.file.savedir + 'multicontrast_seg_feature.xls') del data, point, resultData # ICP with contour with label print 'Register Data %s with ICP(contour) with label...' % self.ini.file.name_result[ i] data, point, para = self.icp.register(dataset['fix'], dataset['mov'], 0, op=True) resultData = db.ResultData(data, db.ImageInfo(dataset['fix'].info.data), point) resultData.info.addData('fix', 1) resultData.info.addData('move', 2) resultData.info.addData('transform', para) print 'Done!' mean_dis, mean_whole, max_dis, max_whole = self.surfaceerror.analysis( resultData, fix_points.copy(), mov_points.copy(), dataset['mov'].getPointSet('Mask').copy(), dataset['mov'].getResolution().tolist()) print 'Contour Error Done! Whole mean is %0.2fmm.' % mean_whole para = resultData.info.getData('transform') R = ml.mat(para[:9]).reshape(3, 3) T = ml.mat(para[9:12]).T T = R.I * T T = -T tmp_con, result_center_points = util.resliceTheResultPoints( mov_points, None, 20, dataset['mov'].getResolution().tolist(), dataset['fix'].getResolution().tolist(), False, R, T) resultData.pointSet.data['Contour'] = tmp_con dice_index, dice_index_all = self.areaerror.analysis( resultData, fix_points.copy()) print 'Area Error Done! Whole Dice index is %0.3f.' % dice_index_all self.sheet3.write(0, i + 2, self.ini.file.name_result[i]) for j in range(3): self.sheet3.write(j + 1, i + 2, mean_dis[j]) self.sheet3.write(j + 5, i + 2, max_dis[j]) self.sheet3.write(j + 9, i + 2, dice_index[j]) self.sheet3.write(4, i + 2, mean_whole) self.sheet3.write(8, i + 2, max_whole) self.sheet3.write(12, i + 2, dice_index_all) self.book.save(self.path + self.ini.file.savedir + 'multicontrast_seg_feature.xls') del data, point, resultData del self.new_points, fix_points, self.new_points_fix, self.new_points_mov, mov_points, tmp_con, result_center_points
|- matrix(data[, dtype, copy]) |- 可以使用字节字流构建 |- asmatrix(data[, dtype]) |- 把数组转换为矩阵 创建特殊矩阵的函数 empty(shape[, dtype, order]) |- 空矩阵 zeros(shape[, dtype, order]) |- 0矩阵 ones(shape[, dtype, order]) Matrix of ones. |- 值位1的矩阵 eye(n[, M, k, dtype, order]) |- 对角线为1的矩阵 identity(n[, dtype]) |- 单位方阵 rand(*args) |- 随机矩阵,取值范围(0-1) randn(*args) |- 服从标准正态分布的矩阵,取值范围(-inf, inf) """ import numpy.matlib as mb print(mb.mat([1, 2, 3])) print(mb.matrix([1, 2, 3])) print(mb.rand(3, 3)) print(mb.randn(3, 3))