def main(): params = px.get_default_params() moving_image = '/Users/ian/Programming/hart/mri-images/PQ_forearm_cropped_for_ITK-SNAP_biascorr.nii' fixed_image = '/Users/ian/Programming/hart/mri-images/sub3_forearm_cropped_for_ITK-SNAP.nii' px.register(moving_image, fixed_image, params, verbose=2)
def test_register_affine_gray(): # Get fixed image image_fixed = imageio.imread('imageio:chelsea.png') image_fixed = color.rgb2gray(image_fixed) # Generate moving image image_moving = transform.rotate(image_fixed, angle=15, resize=True) # Convert both images to float32 image_fixed = image_fixed.astype('float32') image_moving = image_moving.astype('float32') # Initialize and adjust the parameters params = pyelastix.get_default_params(type='AFFINE') params.FixedInternalImagePixelType = "float" params.MovingInternalImagePixelType = "float" params.ResultImagePixelType = "float" params.NumberOfResolutions = 3 params.MaximumNumberOfIterations = 1000 # Register image_registered, field = pyelastix.register( image_moving, image_fixed, params) # Check the results assert image_registered == pytest.approx(image_fixed, rel=1)
def register(files, template): for file in files: print(file) cur_image = imageio.imread(file) cur_image = cur_image[:, :, 1].astype('float32') output_image = None output_image, field = pyelastix.register(cur_image, template, params, exact_params=False, verbose=0) imageio.imwrite(file, output_image)
def registration(to_register, reference): #internal elastix parameters params = pyelastix.get_default_params(type='RIGID') params.NumberOfResolutions = 8 params.AutomaticTransformInitialization = True params.AutomaticScalesEstimation = False params.NumberOfHistogramBins = 64 params.MaximumStepLength = 5.0 params.MaximumNumberOfIterations = 2000 registered, field = pyelastix.register(to_register, reference, params) return registered
def deform(im_fix, im_mov): im_fix = np.ascontiguousarray(im_fix) im_mov = np.ascontiguousarray(im_mov) # Get params and change a few values params = pyelastix.get_default_params(type='BSPLINE') params.NumberOfResolutions = 4 params.MaximumNumberOfIterations = 500 params.FinalGridSpacingInVoxels = 10 # Apply the registration (im1 and im2 can be 2D or 3D) im_deformed, field = pyelastix.register(im_mov, im_fix, params, verbose=0) return im_deformed, field
def register_img(pet_series, pct_series): """ Perform registration using pyelastix library. Input image series and outputs transformed image and transformation field. Both written to text file. Output Format: image_array = str(dict{patient: arrays}) transform_array = str(dict{patient: arrays}) """ pet_image = {key: sitk.GetArrayFromImage(value) for key, value in pet_series.items()} pct_image = {key: sitk.GetArrayFromImage(value) for key, value in pct_series.items()} print(type(pet_image["HN-CHUM-001"])) print(np.shape(pet_image["HN-CHUM-001"])) rigid_params = pyx.get_default_params(type='RIGID') spline_params = pyx.get_default_params(type='BSPLINE') params = rigid_params + spline_params print(params) transform_img = {} transform_field = {} transform_array = {} reg_time = {} for key, value in pct_image.items(): toc = timeit.default_timer() transform_img[key], transform_field[key] = pyx.register( pet_image[key], value, params, exact_params=False, verbose=1) tic = timeit.default_timer() reg_time[key] = tic - toc print("Registration Done") image_array = {key: np.array(value).tolist() for key, value in transform_img.items()} transform_array = {key: np.array(value).tolist() for key, value in transform_field.items()} show_image(image_array["HN-CHUM-001"]) for key, value in transform_array.items(): with open(".\\Transform_Fields\\{}.json".format(key), "w+") as f: json.dump(value, f, indent=4, separators=(',', ':')) for key, value in image_array.items(): with open(".\\Transform_Images\\{}.json".format(key), "w+") as f: json.dump(value, f, indent=4, separators=(',', ':')) with open("registration_file.json", "w+") as f: json.dump(reg_time, f, indent=4, separators=(',', ':')) print("Done Writing Files") return image_array, transform_array
def _register_with_elastix(fixed, moving, transform='AffineTransform', elastix_params=None, name=None, verbose=False ): if name is not None and verbose: print('Elastix align on {}'.format(name)) # Set the parameters. Pyelastix offers automatic and sensible defaults if transform == 'AffineTransform': params = pyelastix.get_default_params(type='AFFINE') else: params = pyelastix.get_default_params() # Modify the parameters as desired by input if params.Transform != transform: warnings.warn('Transform in default settings does not match selected transform!') for param, val in elastix_params.items(): setattr(params, param, val) # Hard-coded as integers won't work params.ResultImagePixelType = "float" # The registration result, _ = pyelastix.register( np.array(moving).astype('float32'), np.array(fixed).astype('float32'), params, verbose=0 ) # The result is read only when it comes out of pyelastix -- copying and replacing fixes that result = result.copy() # Getting back the input datatype if moving.dtype == 'uint8': result[result < 0] = 0 result[result > 255] = 255 elif moving.dtype == 'uint16': result[result < 0] = 0 result[result > 65535] = 65535 else: raise NotImplementedError return result.astype(moving.dtype)
def _register(self, verbose=1, fig=None): # Compile params params_elastix = pyelastix.Parameters() # this is not a dict! for key, val in self.params2.items(): setattr(params_elastix, key, val) for key, val in self.params.items(): setattr(params_elastix, key, val) # Get images if isinstance(self, ElastixGroupwiseRegistration): im1, im2 = self._ims, None else: im1, im2 = self._ims[0], self._ims[1] # Use elastix # todo: what about keyword exactparams? im, fields = pyelastix.register(im1, im2, params_elastix, verbose=verbose) # Field is a a tuple of arrays, or a list of tuple of arrays if not isinstance(self, ElastixGroupwiseRegistration): fields = [fields] # For each deformation in the potentially groupwise registration process ... for i in range(len(fields)): field = fields[i] # Reverse (Elastix uses x-y-z order) field = [f for f in reversed(field)] # Set resulting deforms self._deforms[i] = DeformationFieldBackward(*field) # Also set deformed image self._deformed_image = im
import pyelastix as px params = px.get_default_params() moving_image = '/Users/ian/Programming/hart/mri-images/PQ_forearm_cropped_for_ITK-SNAP_biascorr.nii' fixed_image = '/Users/ian/Programming/hart/mri-images/sub3_forearm_cropped_for_ITK-SNAP.nii' px.register(moving_image, fixed_image, params, verbose=2)
params = pyelastix.get_default_params("RIGID") params.MaximumNumberOfIterations = 1000 params.NumberOfResolutions = 10 params.Metric = "AdvancedMeanSquares" params.AutomaticScalesEstimation = True params.MaximumStepLength = 20.0 params.DefaultPixelValue = 0 pprint(params.as_dict()) immov_deformed, field, transfo = pyelastix.register(immov, imfix, params, verbose=3) with open("transformation.txt", "w+") as f: f.write(transfo) imtr = pyelastix.transform(immov, "transformation.txt") # #print() #print(transfo) #print() #print(immov_deformed.shape) #immov_deformed = immov_deformed/(immov_deformed.max()/255.0) imtr = imtr/(imtr.max()/255.0) # #np.save("MovImage_mod_registered.npy", immov_deformed) #
# Read image data im1 = imageio.imread('chelsea.png') im2 = imageio.imread('chelsea_morph1.png') #im2 = imageio.imread('https://dl.dropboxusercontent.com/u/1463853/images/chelsea_morph1.png') # Select one channel (grayscale), and make float im1 = im1[:,:,1].astype('float32') im2 = im2[:,:,1].astype('float32') # Get default params and adjust params = pyelastix.get_default_params() params.NumberOfResolutions = 3 print(params) # Register! im3, field = pyelastix.register(im1, im2, params) # Visualize the result fig = plt.figure(1); plt.clf() plt.subplot(231); plt.imshow(im1) plt.subplot(232); plt.imshow(im2) plt.subplot(234); plt.imshow(im3) plt.subplot(235); plt.imshow(field[0]) plt.subplot(236); plt.imshow(field[1]) # Enter mainloop if hasattr(plt, 'use'): plt.use().Run() # visvis else: plt.show() # mpl