Esempio n. 1
0
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)
Esempio n. 2
0
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)
Esempio n. 3
0
    def _defaultParams(self):
        """ Overload to create all default params.
        """
        params = AbstractRegistration._defaultParams(self)
        params.mapping = 'backward'

        params.update(
            pyelastix.get_default_params(self.transformation_type).as_dict())
        return params
Esempio n. 4
0
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
Esempio n. 5
0
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 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
Esempio n. 7
0
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
Esempio n. 8
0
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)
            x = math.floor((width - newsize) / 2)
            y = math.floor((height - newsize) / 2)
            img_crop = img[y:y + newsize, x:x + newsize]
            cv2.imwrite(file, img_crop)

#Gets template images for registration.
template1 = imageio.imread('./Images/Templates/1.jpg')
template2 = imageio.imread('./Images/Templates/2.jpg')
template3 = imageio.imread('./Images/Templates/3.jpg')

templates = [
    template1[:, :, 1].astype('float32'), template2[:, :, 1].astype('float32'),
    template3[:, :, 1].astype('float32')
]

params = pyelastix.get_default_params(type='AFFINE')
#Sets desired resolution, higher resolution the better.
params.NumberOfResolutions = 2


#Function to register group of images to one tempalte
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,
Esempio n. 10
0
from pprint import pprint



immov = np.load("MovImage_mod.npy")
imfix = np.load("FixImage_mod.npy")
#immov = np.load("MovImage_Mk1o1_transf_mod.npy")
#imfix = np.load("FixImage_Mk1o1_mod.npy")
imfix = imfix/(imfix.max()/255.0)
immov = immov/(immov.max()/255.0)
#immov = np.max(immov) - immov
#imfix = np.max(imfix) - imfix

print(immov.shape)

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)
Esempio n. 11
0
# Pick one lib to visualize the result, matplotlib or visvis
#import visvis as plt
import matplotlib.pyplot as plt


# 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])