Example #1
0
    def KeyPressCallback(self, obj, event):
        ch = self.parent.window_interactor.GetKeySym()
        if ch == 'Return':
            if (self.X1, self.Y1) == (self.X2, self.Y2):
                return

            point = npy.round(self.getAllPoint())
            if self.parent.dimension:
                max = npy.max(point, axis=0)
                min = npy.min(point, axis=0)
                bound = [(min[i], max[i] + 1) for i in range(2)]
                bound = bound[::-1]
            else:
                point[0, self.parent.view] = 0
                point[1,
                      self.parent.view] = self.parent.parent.getData().getData(
                      ).shape[0] - 1
                max = npy.max(point, axis=0)
                min = npy.min(point, axis=0)
                bound = [(min[i], max[i] + 1) for i in range(3)]
                bound = bound[::-1]

            info = db.ImageInfo(self.parent.parent.getData().getInfo().data)
            info.setName(None)
            if not self.parent.dimension:
                orientation = npy.array([1, 0, 0, 0, 1, 0])
                info.addData('orientation', orientation)
                resolution = self.parent.parent.getData().getResolution()[::-1]
                info.addData('resolution', resolution)
                view, flip = db.getViewAndFlipFromOrientation(
                    orientation, resolution.shape[0])
                info.addData('view', view)
                info.addData('flip', flip)
                info.addData(
                    'clip',
                    npy.array([
                        bound[0][0], bound[0][1], bound[1][0], bound[1][1],
                        bound[2][0], bound[2][1]
                    ]))
                data = db.BasicData(
                    data=self.parent.parent.getData().getData()[
                        bound[0][0]:bound[0][1], bound[1][0]:bound[1][1],
                        bound[2][0]:bound[2][1]],
                    info=info)
            else:
                info.addData(
                    'clip',
                    npy.array(
                        [bound[0][0], bound[0][1], bound[1][0], bound[1][1]]))
                data = db.BasicData(
                    data=self.parent.parent.getData().getData()[
                        bound[0][0]:bound[0][1], bound[1][0]:bound[1][1]],
                    info=info)

            self.parent.parent.gui.addNewDataView(data)
Example #2
0
    def load(self, i):
        dataset = {'result': [], 'fix': []}
        data, info, point = db.loadMatData(
            self.path + self.ini.file.datadir + self.ini.file.name_result[i] +
            '_icp_cen.mat', None)
        dataset['result'] = db.BasicData(data, info, point)

        data, info, point = db.loadMatData(
            self.path + self.ini.file.datadir + '/Contour/' +
            self.ini.file.name_fix[i] + '.mat', None)
        dataset['fix'] = db.BasicData(data, info, point)

        print 'Data %s loaded!' % self.ini.file.name_result[i]

        return dataset
Example #3
0
    def run(self, *args, **kwargs):
        #num, ok = self.gui.getInputPara(self.gui.win, 'centerX')
        #if not ok or num is None:
        #    return []
        num = 100
        centerx = float(num)
        #num, ok = self.gui.getInputPara(self.gui.win, 'centerY')
        #if not ok or num is None:
        #    return []
        num = 100
        centery = float(num)
        #num, ok = self.gui.getInputPara(self.gui.win, 'Radius', 30.0)
        #if not ok or num is None:
        #    return []
        num = 5
        radius = float(num)
        #num, ok = self.gui.getInputPara(self.gui.win, 'ResolutionX', 1.0)
        #if not ok or num is None:
        #    return []
        num = 1
        info = self.getInfo(res=[1.0, 1.0, float(num)], ori=0)
        image = self.getImage(size=[150, 200, 300],
                              radius=radius,
                              center=[centerx, centery, 0],
                              black=100,
                              gray=0)
        #point = self.getPointSet(size = [150, 200, 300], radius = radius, ori = 0, center = [centerx, centery, 0])
        point = {}

        phantomData = db.BasicData(data=image, info=info, pointSet=point)
        return [phantomData]
Example #4
0
    def load(self, i):
        dataset = {'mov': [], 'fix': [], 'seg': []}

        data, info, point = db.loadMatData(
            self.path + self.ini.file.datadir + '/Contour/' +
            self.ini.file.name_fix[i] + '.mat', None)
        fileData = db.BasicData(data, info, point)
        dataset['fix'] = fileData

        data, info, point = db.loadMatData(
            self.savepath + self.ini.file.name_result[i] + '_mr.mat', None)
        fileData = db.BasicData(data, info, point)
        dataset['seg'] = fileData
        print 'Data %s loaded!' % self.ini.file.name_result[i]

        return dataset
 def load(self, k, i):
     dataset = {'mov': [], 'fix': []}
     
     data, info, point = db.loadMatData(self.path + self.ini.file.datadir + '/Contour/'
         + self.ini.file.name_fix[i] + '.mat', None)
     point['Centerline'] = calCenterlineFromContour(point)
     fileData = db.BasicData(data, info, point)
     dataset['fix'] = fileData
     
     data, info, point = db.loadMatData(self.path + self.ini.file.datadir + '/Contour/'
         + self.ini.file.name_mov[i] + '.mat', None)
     point['Centerline'] = calCenterlineFromContour(point)
     fileData = db.BasicData(data, info, point)
     dataset['mov'] = fileData
     print 'Data %s loaded!' % self.ini.file.name_result[i]
         
     return dataset
Example #6
0
    def load(self, i):
        dataset = {'us': [], 'mr': []}

        data, info, point = db.loadMatData(
            self.path + self.ini.file.datadir + '/Contour/' +
            self.ini.file.name_fix[i] + '.mat', None)
        fileData = db.BasicData(data, info, point)
        dataset['mr'] = fileData

        data, info, point = db.loadMatData(
            self.path + self.ini.file.datadir + '/Contour/' +
            self.ini.file.name_mov[i] + '.mat', None)
        fileData = db.BasicData(data, info, point)
        dataset['us'] = fileData
        print 'Data %s loaded!' % self.ini.file.name_result[i]

        return dataset
Example #7
0
 def load(self, dir):
     result = []
     for name in dir:
         data, info, point = db.loadRawData(name)
         import numpy
         print numpy.sum(data)
         fileData = db.BasicData(data, info, point)
         result.append(fileData)
     return result
Example #8
0
 def load(self, dir):
     result = []
     for name in dir:
         data, info, point = db.loadMatData(name, self.gui.dataModel)
         if info.getData('fix') is not None:
             fileData = db.ResultData(data, info, point)
         else:
             fileData = db.BasicData(data, info, point)
         result.append(fileData)
     return result
Example #9
0
 def load(self, dir):
     try:
         data, names = db.loadDicomArrayFromDir(dir)
     except Exception:
         self.gui.showErrorMessage("Memory error", "Data exceeded memory limit! If this problem occurs again, please restart the application.")
         return []
     
     # Format: z * x * y
     if type(data) == tuple:
         data = npy.concatenate((data[0], data[1]), axis = 0)
     if data.shape[0] == 1:
         data = data.reshape(data.shape[1:])
         
     info = self.loadDicomInfo(names[0], len(data.shape))
     fileData = db.BasicData(data = data, info = info)
     
     return [fileData]
 def register(self, fixedData, movingData, regPara = [(40.0, 1000.0, "SSD")], w2 = 1.0, true_fixed_points = None, true_moving_points = None): # For simple test
     # Initial data
     fixed_res = fixedData.getResolution().tolist()
     moving_res = movingData.getResolution().tolist()
     
     fixed_points = fixedData.getPointSet('Contour')
     moving_points = movingData.getPointSet('Contour')
     fixed_points_cen = fixedData.getPointSet('Centerline')
     moving_points_cen = movingData.getPointSet('Centerline')
     
     fixed_points_ori = fixed_points.copy()[npy.where(fixed_points[:, 0] >= 0)]
     moving_points_ori = moving_points.copy()[npy.where(moving_points[:, 0] >= 0)]
     fixed_points_cen_ori = fixed_points_cen.copy()[npy.where(fixed_points_cen[:, 0] >= 0)]
     moving_points_cen_ori = moving_points_cen.copy()[npy.where(moving_points_cen[:, 0] >= 0)]
     
     if true_fixed_points is None:
         true_fixed_points = fixed_points_ori
     if true_moving_points is None:
         true_moving_points = moving_points_ori
     
     fixed_points = fixed_points_ori.copy()
     moving_points = moving_points_ori.copy()
     fixed_points_cen = fixed_points_cen_ori.copy()
     moving_points_cen = moving_points_cen_ori.copy()
     
     fix_img = fixedData.getData()
     mov_img = movingData.getData()
     
     init_time = 0.0
     time1 = time.time()
     # Calculate the initial rigid transformation for 9 points T0
     fix_key_point = eutil.getKeyPoints(fixed_points_cen, fixed_res)
     mov_key_point = eutil.getKeyPoints(moving_points_cen, moving_res)
     T0, mov_bif = eutil.getRigidTransform(fix_key_point, mov_key_point) # 4 * 4 Matrix
     moving_points = eutil.applyRigidTransformOnPoints(moving_points, moving_res, T0)
     moving_points_cen_result = eutil.applyRigidTransformOnPoints(moving_points_cen, moving_res, T0)
     crop_fixed_index, crop_moving_index = eutil.cropCenterline(fixed_points_cen, moving_points_cen_result, fixed_res, moving_res, fix_key_point[0, 2] / fixed_res[2], mov_bif[2] / moving_res[2])
     
     # Use GMMREG for centerline-based rigid registration T1
     gmm = GmmregPointsetRegistration(self.gui)
     new_fixedData = db.BasicData(fix_img, db.ImageInfo(fixedData.getInfo().data), 
         {'Contour': fixed_points, 'Centerline': fixed_points_cen[crop_fixed_index]})
     new_movingData = db.BasicData(mov_img, db.ImageInfo(movingData.getInfo().data), 
         {'Contour': moving_points, 'Centerline': moving_points_cen_result[crop_moving_index]})
     tmp_img, points, para = gmm.register(new_fixedData, new_movingData, 1, False, "rigid")
     T1 = eutil.getMatrixFromGmmPara(para)
     T_init = T0 * T1
     moving_points = points['Contour'].copy()
     moving_points_cen_result = points['Centerline'].copy()
     del new_movingData
     
     # Use GMMREG for centerline-based TPS registration
     new_movingData = db.BasicData(mov_img, db.ImageInfo(fixedData.getInfo().data), 
         {'Contour': moving_points, 'Centerline': moving_points_cen_result}) # The image has been resampled into fixed resolution
     tmp_img, points, para = gmm.register(new_fixedData, new_movingData, 1, False, "EM_TPS")
     result_points_cen = points['Centerline'].copy()
     result_points_cen = result_points_cen[result_points_cen[:, -1] >= 0]
     result_points_cen[:, :3] *= fixed_res
     del new_movingData
     del new_fixedData
     del moving_points_cen_result
     
     # Save the images for Elastix registration
     ee.writeImageFile(fixedData, "fix")
     ee.writeImageFile(movingData, "mov")
     fix_binary_mask = eutil.getBinaryImageFromSegmentation(fix_img, fixed_points_ori)
     fix_binary_data = db.BasicData(fix_binary_mask, db.ImageInfo(fixedData.getInfo().data))
     ee.writeImageFile(fix_binary_data, "fixmm")
     del fix_binary_data
     del fix_binary_mask
     fix_binary_mask = eutil.getBinaryImageFromSegmentation(fix_img, true_fixed_points)
     fix_binary_data = db.BasicData(fix_binary_mask, db.ImageInfo(fixedData.getInfo().data))
     ee.writeImageFile(fix_binary_data, "fixmmm")
     del fix_binary_data
     del fix_binary_mask
     mov_binary_mask = eutil.getBinaryImageFromSegmentation(mov_img, moving_points_ori)
     mov_binary_data = db.BasicData(mov_binary_mask, db.ImageInfo(movingData.getInfo().data))
     ee.writeImageFile(mov_binary_data, "movmm")
     del mov_binary_data
     del mov_binary_mask
     mov_binary_mask = eutil.getBinaryImageFromSegmentation(mov_img, true_moving_points)
     mov_binary_data = db.BasicData(mov_binary_mask, db.ImageInfo(movingData.getInfo().data))
     ee.writeImageFile(mov_binary_data, "movmmm")
     del mov_binary_data
     del mov_binary_mask
     
     fix_binary_mask = eutil.getMaskFromCenterline(fix_img, fixed_points_cen_ori, fixed_res)
     fix_binary_data = db.BasicData(fix_binary_mask, db.ImageInfo(fixedData.getInfo().data))
     ee.writeImageFile(fix_binary_data, "fixm")
     del fix_binary_data
     del fix_binary_mask
     mov_binary_mask = eutil.getMaskFromCenterline(mov_img, moving_points_cen_ori, moving_res)
     mov_binary_data = db.BasicData(mov_binary_mask, db.ImageInfo(movingData.getInfo().data))
     ee.writeImageFile(mov_binary_data, "movm")
     del mov_binary_data
     del mov_binary_mask
     
     tmp = moving_points_cen.copy()
     tmp[:, :3] *= moving_res
     ee.writePointsetFile(tmp[crop_moving_index], "movp.txt")
     ee.writePointsetFile(result_points_cen, "fixp.txt")
     
     init_para_inv = eutil.getElastixParaFromMatrix(T_init.I)
     ee.writeTransformFile(init_para_inv, fix_img.shape, fixed_res, type = "MI") # For transformation of image
     ee.writeTransformFile(init_para_inv, fix_img.shape, fixed_res, "transparassd.txt") # For transformation of image
     init_para = eutil.getElastixParaFromMatrix(T_init)
     ee.writeTransformFile(init_para, fix_img.shape, fixed_res, "transpara2.txt") # For transformation of points
     
     # Apply the initial transformation (It seems -t0 didn't work in Elastix)
     ee.run_executable(type = "transformix", mov = "movp.txt", tp = "transpara2.txt")
     ee.writePointsetFileFromResult("Output/outputpoints.txt", "movp0.txt")
     
     tmp = moving_points_ori.copy()
     tmp[:, :3] *= moving_res
     ee.writePointsetFile(tmp, "mov.txt")
     ee.run_executable(type = "transformix", mov = "mov.txt", tp = "transpara2.txt") # Transform the moving segmentation result using initial transformation
     ee.writePointsetFileFromResult("Output/outputpoints.txt", "mov0.txt")
     
     ee.changeOutputBSplineOrder("transpara.txt", 3)
     ee.run_executable(type = "transformix", mov = "mov.mhd", tp = "transpara.txt", outDir = "")
     ee.renameImage("result", "mov0")
     ee.changeOutputBSplineOrder("transpara.txt", 0)
     ee.run_executable(type = "transformix", mov = "movmm.mhd", tp = "transparassd.txt", outDir = "")
     ee.renameImage("result", "movmm0")
     ee.run_executable(type = "transformix", mov = "movm.mhd", tp = "transparassd.txt", outDir = "")
     ee.renameImage("result", "movm0")
     ee.run_executable(type = "transformix", mov = "movmmm.mhd", tp = "transparassd.txt", outDir = "")
     ee.renameImage("result", "movmmm0")
     
     sa = SurfaceErrorAnalysis(None)
     
     # Start registration of different parameters
     cnt = len(regPara)
     result = npy.zeros([cnt, 3], dtype = npy.float32)
     fix_img_mask = ee.readImageFile("fixmmm.mhd")
     time2 = time.time()
     init_time = time2 - time1
     for i in range(0, cnt):
         if regPara[i][2] == "MI" and regPara[i][1] > 0:
             ww = regPara[i][1] / 1000
         else:
             ww = regPara[i][1]
         
         isRigid = regPara[i][0] < 0
         # Save Elastix registration configuration
         ee.writeParameterFile("para_rigid.txt", "rigid", regPara[i][2], regPara[i][0], ww, w2)
         if not isRigid:
             ee.writeParameterFile("para_spline.txt", "bspline", regPara[i][2], regPara[i][0], ww, w2)
         
         # Use Elastix for hybrid registration
         if isRigid:
             para_elastix = ["para_rigid.txt"]
         else:
             para_elastix = ["para_rigid.txt", "para_spline.txt"]
         
         if regPara[i][2] == "SSD":
             mov_name = "movmm0.mhd"
             fix_name = "fixmm.mhd"
         else:
             mov_name = "mov0.mhd"
             fix_name = "fix.mhd"
         time1 = time.time()
         code = ee.run_executable(type = "elastix", para = para_elastix, 
             fix = fix_name, mov = mov_name, movm = "movm0.mhd", movp = "movp0.txt", mask = (regPara[i][2] != "SSD"))
         time2 = time.time()
         if code != 0:
             print "Elastix error!"
             continue
         
         # Read the output files into self data formats
         ee.changeOutputBSplineOrder("Output/TransformParameters.0.txt", 0)
         if not isRigid:
             ee.changeOutputBSplineOrder("Output/TransformParameters.1.txt", 0)
             ee.run_executable(type = "transformix", mov = "movmmm0.mhd", tp = "Output/TransformParameters.1.txt") # Non-rigid transformation
             ee.changeOutputInitTransform("Output/TransformParameters.1.txt")
         else:
             ee.run_executable(type = "transformix", mov = "movmmm0.mhd", tp = "Output/TransformParameters.0.txt")
             ee.changeOutputBSplineOrder("Output/TransformParameters.0.txt", 0)
             
         result_img_mask = ee.readImageFile("Output/result.mhd")
         if regPara[i][2] == "SSD":
             # Transform the segmentation result for evaluation
             '''
             if isRigid:
                 result_img_mask = ee.readImageFile("Output/result.0.mhd")
             else:
                 result_img_mask = ee.readImageFile("Output/result.1.mhd")
             '''
             if cnt == 1:
             #if True:
                 ee.changeOutputBSplineOrder("Output/TransformParameters.0.txt", 3)
                 if not isRigid:
                     ee.changeOutputBSplineOrder("Output/TransformParameters.1.txt", 3)
                     ee.run_executable(type = "transformix", mov = "mov0.mhd", tp = "Output/TransformParameters.1.txt") # Non-rigid transformation
                     ee.changeOutputInitTransform("Output/TransformParameters.1.txt")
                 else:
                     ee.run_executable(type = "transformix", mov = "mov0.mhd", tp = "Output/TransformParameters.0.txt")
                 
                 result_img = ee.readImageFile("Output/result.mhd")
                 print i, 'SSD'
             
         else:
             if cnt == 1:
             #if True:
                 if isRigid:
                     result_img = ee.readImageFile("Output/result.0.mhd")
                     print i, 'Other'
                 else:
                     result_img = ee.readImageFile("Output/result.1.mhd")
             
             
             
         ee.generateInverseTransformFile("Output/TransformParameters.0.txt", "fix.mhd")
         
         # Delete the mask slice from the moving points
         tmp = true_moving_points.copy()
         for point in movingData.getPointSet('Mask'):
             tmp = npy.delete(tmp, npy.where((npy.abs(tmp[:, 2] - point[2]) < 0.0001) & (npy.round(tmp[:, -1]) == point[3])), axis = 0)
         tmp[:, :3] *= moving_res
         ee.writePointsetFile(tmp, "movm.txt")
         ee.run_executable(type = "transformix", mov = "movm.txt", tp = "transpara2.txt") # Transform the moving segmentation result using initial transformation
         ee.writePointsetFileFromResult("Output/outputpoints.txt", "mov0m.txt")
         ee.run_executable(type = "transformix", mov = "mov0m.txt", tp = "TransformParameters.0.txt") # Transform the moving segmentation result using rigid transformation
         if not isRigid:
             ee.generateInverseTransformFile("Output/TransformParameters.1.txt", "fix.mhd")
             ee.writePointsetFile(ee.readPointsetFile("Output/outputpoints.txt"), "Output/outputpoints2.txt")
             ee.run_executable(type = "transformix", mov = "Output/outputpoints2.txt", tp = "TransformParameters.0.txt") # Non-rigid transformation
         
         result_con = tmp.copy()
         result_con[:, :3] = ee.readPointsetFile("Output/outputpoints.txt")
         result_con[:, :3] /= fixed_res
         
         result_pointset = {'Contour': result_con}
         
         if cnt > 1:
         #if False:
             dataset = db.BasicData(npy.array([[[0]]]), fixedData.getInfo(), result_pointset)
             mean_dis, mean_whole, max_dis, max_whole = sa.analysis(dataset, point_data_fix = true_fixed_points, useResult = True)
             del dataset
             
             dice_index = eutil.calDiceIndexFromMask(fix_img_mask, result_img_mask)
             del result_img_mask
             
             del result_pointset
             del result_con
                 
             result[i, :] = [mean_whole, dice_index, time2 - time1]# + init_time]
             print "Result of spacing %fmm, weight %f and metric %s: %fmm, %f. " % (regPara[i][0], ww, regPara[i][2], mean_whole, dice_index)
         
         '''
         # Save the result
         resultData = db.ResultData(result_img, db.ImageInfo(fixedData.info.data), result_pointset)
         resultData.info.addData('fix', 1)
         resultData.info.addData('move', 2)
         resultData.info.addData('transform', [0, 0, 0])
         db.saveMatData('D:/Python src/MIRVAP/Result/Result' + str(i) + '_37L.mat', [resultData, fixedData, movingData], 0)
         del resultData
         '''
     
     del fix_img_mask
     if cnt > 1:
         result_img = None
         result_pointset = None
     else:
         result = [0, 0, 0]
     return result_img, result_pointset, result
Example #11
0
 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 register(self, fixedData, movingData, index = -1, isRigid = False, isTime = False): # For simple test
     if index == -1:
         if self.gui is not None:
             index = self.gui.getDataIndex({'Contour': 0, 'Centerline': 1}, 'Select the object')
         else:
             index = 1
     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()
     # Initial data
     fixed_res = fixedData.getResolution().tolist()
     moving_res = movingData.getResolution().tolist()
     
     fixed_points_con = fixedData.getPointSet('Contour')
     moving_points_con = movingData.getPointSet('Contour')
     fixed_points_cen = fixedData.getPointSet('Centerline')
     moving_points_cen = movingData.getPointSet('Centerline')
     
     fixed_points_ori = fixed_points.copy()[npy.where(fixed_points[:, 0] >= 0)]
     moving_points_ori = moving_points.copy()[npy.where(moving_points[:, 0] >= 0)]
     fixed_points_con_ori = fixed_points_con.copy()[npy.where(fixed_points_con[:, 0] >= 0)]
     moving_points_con_ori = moving_points_con.copy()[npy.where(moving_points_con[:, 0] >= 0)]
     fixed_points_cen_ori = fixed_points_cen.copy()[npy.where(fixed_points_cen[:, 0] >= 0)]
     moving_points_cen_ori = moving_points_cen.copy()[npy.where(moving_points_cen[:, 0] >= 0)]
     
     fixed_points = fixed_points_ori.copy()
     moving_points = moving_points_ori.copy()
     fixed_points_con = fixed_points_con_ori.copy()
     moving_points_con = moving_points_con_ori.copy()
     fixed_points_cen = fixed_points_cen_ori.copy()
     moving_points_cen = moving_points_cen_ori.copy()
     
     init_time = 0.0
     time1 = time.time()
     
     fix_img = fixedData.getData()
     mov_img = movingData.getData()
     
     # Calculate the initial rigid transformation for 9 points T0
     fix_key_point = eutil.getKeyPoints(fixed_points_cen, fixed_res)
     mov_key_point = eutil.getKeyPoints(moving_points_cen, moving_res)
     T0, mov_bif = eutil.getRigidTransform(fix_key_point, mov_key_point) # 4 * 4 Matrix
     moving_points = eutil.applyRigidTransformOnPoints(moving_points, moving_res, T0)
     moving_points_con = eutil.applyRigidTransformOnPoints(moving_points_con, moving_res, T0)
     moving_points_cen_result = eutil.applyRigidTransformOnPoints(moving_points_cen, moving_res, T0)
     crop_fixed_index, crop_moving_index = eutil.cropCenterline(fixed_points_cen, moving_points_cen_result, fixed_res, moving_res, fix_key_point[0, 2] / fixed_res[2], mov_bif[2] / moving_res[2])
     
     # Use GMMREG for centerline-based rigid registration T1
     gmm = GmmregPointsetRegistration(self.gui)
     new_fixedData = db.BasicData(fix_img, db.ImageInfo(fixedData.getInfo().data), 
         {'Contour': fixed_points_con, 'Centerline': fixed_points_cen[crop_fixed_index]})
     new_movingData = db.BasicData(mov_img, db.ImageInfo(movingData.getInfo().data), 
         {'Contour': moving_points_con, 'Centerline': moving_points_cen_result[crop_moving_index]})
     tmp_img, points, para = gmm.register(new_fixedData, new_movingData, index, False, "rigid")
     T1 = eutil.getMatrixFromGmmPara(para)
     T_init = T0 * T1
     moving_points = points['Contour'].copy()
     moving_points_cen_result = points['Centerline'].copy()
     del new_movingData
     
     # Use GMMREG for centerline-based TPS registration
     if not isRigid:
         new_movingData = db.BasicData(mov_img, db.ImageInfo(fixedData.getInfo().data), 
             {'Contour': moving_points, 'Centerline': moving_points_cen_result}) # The image has been resampled into fixed resolution
         tmp_img, points, para = gmm.register(new_fixedData, new_movingData, index, False, "EM_TPS")
     time2 = time.time()
     
     sa = SurfaceErrorAnalysis(None)
     dataset = db.BasicData(npy.array([[[0]]]), fixedData.getInfo(), points)
     mean_dis, mean_whole, max_dis, max_whole = sa.analysis(dataset, point_data_fix = fixed_points_con.copy(), useResult = True)
     del dataset
     print mean_dis
     print mean_whole
     
     if isTime:
         return tmp_img, points, [mean_dis, mean_whole], time2 - time1
     return tmp_img, points, [mean_dis, mean_whole]
Example #13
0
    def process(self, dataset, i):
        def autoDetectContour(point, cnt, start, end, delta):
            self.new_points = npy.append(self.new_points, point, 0)
            points = point[:, :-2]
            count = 0
            for j in range(start + delta, end + delta, delta):
                center = calCentroidFromContour(points).reshape(2)
                image = dataset['fix'].getData()[j, :, :].transpose().copy()
                image = (image - npy.min(image)) / (npy.max(image) -
                                                    npy.min(image)) * 255
                result = ac_segmentation(center, image)

                a1 = ac_area(points.transpose(), image.shape)
                a2 = ac_area(result, 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()
                    count = 0
                points = temp_array.copy()
                temp_array = npy.insert(temp_array, 2, [[j], [cnt]], 1)
                self.new_points = npy.append(self.new_points, temp_array, 0)

                sys.stdout.write(str(j) + ',')
                sys.stdout.flush()
            print ' '

        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)
        time1 = time.time()
        bottom = int(npy.round(npy.min(tmp[:, 2])))
        bif = int(db.getBifurcation(tmp) + 0.5)
        up = int(npy.round(npy.max(tmp[:, 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)
        autoDetectContour(point_vital[1], 1, up, bif, -1)
        autoDetectContour(point_vital[2], 2, up, bif, -1)
        time2 = time.time()
        '''
        # Use centerline for contour
        j = 0
        for center in tmp:
            image = dataset['fix'].getData()[npy.round(center[2]), :, :].transpose().copy()
            image = (image - npy.min(image)) / (npy.max(image) - npy.min(image)) * 255
            result = ac_segmentation(center[:2], image)
            
            point_array = npy.insert(result.transpose(), 2, [[center[2]],[center[3]]], axis = 1)
            new_points = npy.append(new_points, point_array, 0)
            
            j += 1
            if j % 10 == 0:
                sys.stdout.write(str(j) + ',')
                sys.stdout.flush()
        '''
        print ' '
        print 'Done! Time for segmentation is %0.2fs' % (time2 - time1)
        pointset = {'Contour': self.new_points}
        pointset['Centerline'] = calCenterlineFromContour(pointset)
        print 'Saving Data %s...' % self.ini.file.name_result[i]
        new_data = db.BasicData(dataset['fix'].data,
                                db.ImageInfo(dataset['fix'].info.data),
                                pointset)
        db.saveMatData(
            self.savepath + self.ini.file.name_result[i] + '_mr.mat',
            [new_data], 0)
        print 'Done!'
        mean_dis, mean_whole, max_dis, max_whole = self.contourerror.analysis(
            new_data, dataset['fix'].getPointSet('Contour').copy())
        print 'Contour Error Done! Whole mean is %0.2fmm.' % mean_whole
        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(4, i + 2, mean_whole)
        self.sheet1.write(5, i + 2, time2 - time1)

        self.book.save(self.path + self.ini.file.savedir +
                       'Test_segmentation_final_refined.xls')

        # ICP with centerline
        print 'Register Data %s with ICP(centerline)...' % self.ini.file.name_result[
            i]
        time1 = time.time()
        data, point, para = self.icp.register(new_data, dataset['mov'], 1)
        time2 = time.time()
        print 'Done! Time for registration is %0.2fs' % (time2 - time1)
        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)
        mean_dis, mean_whole, max_dis, max_whole = self.contourerror.analysis(
            resultData, dataset['fix'].getPointSet('Contour').copy())
        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.sheet2.write(13, i + 2, time2 - time1)

        self.book.save(self.path + self.ini.file.savedir +
                       'Test_segmentation_final_refined2.xls')
        del data, point, resultData