Skip to content

Instantly share code, notes, and snippets.

@maxpietsch
Last active October 25, 2021 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxpietsch/846defaabdce9fe7cfb3a348ae609dee to your computer and use it in GitHub Desktop.
Save maxpietsch/846defaabdce9fe7cfb3a348ae609dee to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
def usage(cmdline):
cmdline.set_author('Max Pietsch')
cmdline.set_synopsis('Landmark-based manual alignment')
cmdline.add_description('Calculates the rigid transformation between two images based on three or more matching landmarks.')
cmdline.add_argument('fixed', help='The reference input image')
cmdline.add_argument('moving', help='The moving input image')
cmdline.add_argument('rigid', help='The output transformation')
cmdline.add_argument('-show', action='store_true', help='Show the transformed moving with the fixed image overlaid')
cmdline.add_example_usage('To calculate the rigid transformation between two images based on landmarks',
'mralign fixed.mif moving.mif rigid')
def parse_coords(fixed, moving):
from mrtrix3 import app, run, MRtrixError
annotation = run.command('mrview ' + fixed + ' ' + moving).stdout.rstrip().split('\n')
n_anno = len(annotation)
app.console("annotation:")
for line in annotation:
app.console(line)
if n_anno % 2 != 0 or n_anno < 6:
raise MRtrixError('requires at least 3 coordinates for each image')
with open('F', 'w') as f:
f.write('\n'.join(annotation[:n_anno//2]))
with open('M', 'w') as f:
f.write('\n'.join(annotation[n_anno//2:]))
def execute():
import shutil
from mrtrix3 import MRtrixError, app, image, path, run
# check input and output
if len(image.Header(path.from_user(app.ARGS.moving, False)).size()) < 3:
raise MRtrixError('Input image must be at least 3D')
if len(image.Header(path.from_user(app.ARGS.fixed, False)).size()) < 3:
raise MRtrixError('Input image must be at least 3D')
app.check_output_path(app.ARGS.rigid)
app.make_scratch_dir()
app.goto_scratch_dir()
app.console('open view options tool, mark 3+ landmarks with the cross hair and "copy" their positions in sequence, repeat for other image')
parse_coords(path.from_user(app.ARGS.fixed), path.from_user(app.ARGS.moving))
run.command('transformcalc M F align_vertices_rigid rigid')
if app.ARGS.show:
run.command('mrtransform ' + path.from_user(app.ARGS.moving) + ' -linear rigid -reorient no - | ' +
' mrview - -overlay.load ' + path.from_user(app.ARGS.fixed) + ' -overlay.opa 0.2')
run.function(shutil.copy, 'rigid', path.from_user(app.ARGS.rigid, False))
# Execute the script
import mrtrix3
mrtrix3.execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment