Commit f19c6f56 authored by Sean Fitzgibbon's avatar Sean Fitzgibbon
Browse files

Added comment

parent 1aad409a
......@@ -65,6 +65,9 @@
# University, to negotiate a licence. Contact details are:
# Innovation@innovation.ox.ac.uk quoting reference BS/9564.
#
#
#
# Adapted by Sean Fitz 2021
"""
......@@ -181,7 +184,6 @@ def run(cnf=None, **options):
os.path.join(p.general.outputdir, f"moving.{ext}")
moving = tirl.scripts.mnd.inout.load_image(scope=globals(), **p.moving)
if p.fixed.export is True:
ext = ts.EXTENSIONS["TImage"]
p.fixed.export = os.path.join(p.general.outputdir, f"fixed.{ext}")
......@@ -210,15 +212,6 @@ def run(cnf=None, **options):
fixed, *p.preprocessing.fixed, scope=globals(), other=moving, cnf=p)
fixed.centralise(weighted=True)
# if p.moving.snapshot is True:
# print(moving.mask.shape)
# plt.imsave(op.join(p.general.outputdir, 'moving_mask.png'), moving.mask)
#
# if p.fixed.snapshot is True:
# print(fixed.mask.shape)
# plt.imsave(op.join(p.general.outputdir, 'fixed_mask.png'), fixed.mask)
# Run the registration routine
try:
register(fixed, moving, p)
......@@ -507,25 +500,10 @@ def rotation_search2d(fixed, moving, cnf):
tx_rotation.parameters.set_upper_bounds(best_params[0] + step / 2)
tx_rotation.parameters.unlock()
# moving_mnd = CostMIND(moving, fixed, maskmode="and", normalise=True).mind(moving)
# np.save('grot_moving_mind', moving_mnd.data)
#
# fixed_mnd = CostMIND(moving, fixed, maskmode="and", normalise=True).mind(fixed)
# np.save('grot_fixed_mind', fixed_mnd.data)
#
# np.save('moving_mask', moving_mnd.mask)
# np.save('fixed_mask', fixed_mnd.mask)
# Return to full resolution after the rotation search
fixed.resample(1, copy=False)
moving.resample(1, copy=False)
# moving_mnd = CostMIND(moving, fixed, maskmode="and", normalise=True).mind(moving)
# np.save('grot_moving_mind_full', moving_mnd.data)
#
# fixed_mnd = CostMIND(moving, fixed, maskmode="and", normalise=True).mind(fixed)
# np.save('grot_fixed_mind_full', fixed_mnd.data)
def rigid2d(fixed, moving, cnf):
"""
......@@ -554,7 +532,6 @@ def rigid2d(fixed, moving, cnf):
ub = ub + np.finfo(lb.dtype).eps
og.set_bounds(lb, ub)
# Set cost function
# cost = CostMI(moving_smooth, fixed_smooth, normalise=True)
cost = CostMIND(moving_smooth, fixed_smooth, normalise=True)
# Start optimisation
OptNL(og, cost, method="LN_BOBYQA", visualise=q.visualise,
......@@ -569,9 +546,6 @@ def rigid2d(fixed, moving, cnf):
fixed.resample(1, copy=False)
moving.resample(1, copy=False)
# np.save('grot_moving_mind_rigid', cost.mind(moving).data)
# np.save('grot_fixed_mind_rigid', cost.mind(fixed).data)
def affine2d(fixed, moving, cnf):
"""
......@@ -593,8 +567,6 @@ def affine2d(fixed, moving, cnf):
moving_smooth = moving.smooth(sm, copy=True)
# Prepare transformation to optimise
tx_affine = fixed_smooth.domain.chain["affine"]
# Set cost function
# cost = CostMI(moving_smooth, fixed_smooth, normalise=True)
cost = CostMIND(moving_smooth, fixed_smooth, normalise=True)
# Start optimisation
OptNL(tx_affine, cost, method="LN_BOBYQA",
......@@ -609,50 +581,9 @@ def affine2d(fixed, moving, cnf):
fixed.resample(1, copy=False)
moving.resample(1, copy=False)
# np.save('grot_moving_mind_affine', cost.mind(moving).data)
# np.save('grot_fixed_mind_affine', cost.mind(fixed).data)
def diffreg2d(fixed, moving, cnf):
"""
Performs a non-linear registration. The transformation is parameterised as
a dense displacement field. The cost is MIND, and diffusion regularisation
is used to create smoothness in the deformation field.
"""
p = AttrMap(cnf)
q = p.regparams.nonlinear
logger = logging.getLogger(p.logger)
# Scaling-smoothing iteration
for i, (sc, sm) in enumerate(zip(q.scaling, q.smoothing)):
logger.debug(f"Scale: {sc}, smoothing: {sm} px...")
# Prepare images for the current iteration
fixed.resample(1 / sc, copy=False)
moving.resample(1 / sc, copy=False)
fixed_smooth = fixed.smooth(sm, copy=True)
moving_smooth = moving.smooth(sm, copy=True)
# Prepare transformation to optimise
tx_nonlinear = fixed_smooth.domain.chain[-1]
# Set cost and regulariser
cost = CostMIND(moving_smooth, fixed_smooth, sigma=float(q.sigma),
truncate=float(q.truncate), kernel=MK_FULL)
regularisation = DiffusionRegulariser(
tx_nonlinear, weight=float(q.regweight))
# Optimise the non-linear transformation
GNOptimiserDiffusion(
tx_nonlinear, cost, regularisation, maxiter=int(q.maxiter[i]),
xtol_rel=q.xtol_rel, xtol_abs=q.xtol_abs, visualise=q.visualise,
logger=logger)()
# Transfer optimised transformations to the non-smoothed images
fixed.domain = fixed_smooth.domain
moving.domain = moving_smooth.domain
else:
# Restore the original resolution of the images
fixed.resample(1, copy=False)
moving.resample(1, copy=False)
# AUXILIARY FUNCTIONS
# AUXILIARY FUNCTIONS
# These functions may be used within other functions of the script. Their usage
......@@ -718,29 +649,29 @@ def match_fixed_resolution(img, **kwargs):
return img
def resample40(img, **kwargs):
p = AttrMap(kwargs.get("cnf"))
logger = logging.getLogger(p.logger)
# def resample40(img, **kwargs):
# p = AttrMap(kwargs.get("cnf"))
# logger = logging.getLogger(p.logger)
logger.info(f"Shape of the 2D image before resampling: {img.shape}.")
logger.info(f"Resolution of the 2D image before resampling: {img.resolution}.")
factors = np.divide(img.resolution, 0.04)
# logger.info(f"Shape of the 2D image before resampling: {img.shape}.")
# logger.info(f"Resolution of the 2D image before resampling: {img.resolution}.")
# factors = np.divide(img.resolution, 0.04)
img = img.resample(*factors, copy=True)
img.reset_resmgr()
img.storage = MEM
img.domain.storage = MEM
logger.info(f"Shape of the 2D image after resampling: {img.shape}.")
logger.info(f"Resolution of the 2D image after resampling: {img.resolution}.")
# img = img.resample(*factors, copy=True)
# img.reset_resmgr()
# img.storage = MEM
# img.domain.storage = MEM
# logger.info(f"Shape of the 2D image after resampling: {img.shape}.")
# logger.info(f"Resolution of the 2D image after resampling: {img.resolution}.")
# Save low-resolution image
fp, fn = os.path.split(p.histology.file)
fn, ext = os.path.splitext(fn)
filename = os.path.join(p.general.outputdir, f"{fn}_lowres.{SNAPSHOT_EXT}")
img.snapshot(filename, overwrite=True)
logger.info(f"Saved low-resolution snapshot of the 2D image to: {filename}")
# # Save low-resolution image
# fp, fn = os.path.split(p.histology.file)
# fn, ext = os.path.splitext(fn)
# filename = os.path.join(p.general.outputdir, f"{fn}_lowres.{SNAPSHOT_EXT}")
# img.snapshot(filename, overwrite=True)
# logger.info(f"Saved low-resolution snapshot of the 2D image to: {filename}")
return img
# return img
def moving_preprocessing(histo, **kwargs):
......@@ -862,7 +793,6 @@ def pad(timg, **kwargs):
padded.domain.chain = chain
return padded
# PROGRAM FLOW CONTROL
def register_slide_to_slide(moving, fixed, out, config):
......@@ -884,52 +814,5 @@ def register_slide_to_slide(moving, fixed, out, config):
config["general"]["logfile"] = f'{out}/logfile.log'
config["general"]["paramlogfile"] = f'{out}/paramlog.log'
# # Override verbose option in configurations
# cnf["general"]["verbose"] = args.verbose
# Run registration script
# print(config)
run(config)
# def create_cli(parser):
# """
# Sets up the CLI argument parser instance.
# """
# parser.add_argument("--moving", metavar="image",
# help="Moving slide", default=None, type=str,
# required=True)
# parser.add_argument("--fixed", metavar="image",
# help="Fixed slide", default=None, type=str,
# required=True)
# parser.add_argument("--out", metavar="dir",
# help="Output directory", default=None, type=str,
# required=True)
# parser.add_argument("--config", metavar="cnf_file.json",
# help="configuration file", default='default.json', type=str,
# required=False)
# parser.add_argument("-v", "--verbose", default=False, action="store_true",
# help="Print status messages to the command line",
# required=False)
# return parser
# def main(*args):
# """ Main program code. """
# parser = argparse.ArgumentParser(
# prog="slice-register.py",
# description="Registers a histology slide to "
# "another histology slide.")
# parser = create_cli(parser)
# if args:
# register_slide_to_slide(parser.parse_args(args))
# else:
# parser.print_help()
# if __name__ == "__main__":
# main(*sys.argv[1:])
run(config)
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment