1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
// Software Guide : BeginLatex
//
// This example illustrates a realistic pipeline for solving a full deformable registration problem.
//
// First the two images are roughly aligned by using a transform
// initialization, then they are registered using a rigid transform, that in
// turn, is used to initialize a registration with an affine transform. The
// transform resulting from the affine registration is used as the bulk
// transform of a BSplineTransform. The deformable registration is
// computed, and finally the resulting transform is used to resample the moving
// image.
//
// Software Guide : EndLatex
#include "itkImageRegistrationMethod.h"
#include "itkMattesMutualInformationImageToImageMetric.h"
#include "itkTimeProbesCollectorBase.h"
#include "itkMemoryProbesCollectorBase.h"
// Software Guide : BeginLatex
//
// The following are the most relevant headers to this example.
//
// \index{itk::VersorRigid3DTransform!header}
// \index{itk::AffineTransform!header}
// \index{itk::BSplineTransform!header}
// \index{itk::RegularStepGradientDescentOptimizer!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkCenteredTransformInitializer.h"
#include "itkVersorRigid3DTransform.h"
#include "itkAffineTransform.h"
#include "itkBSplineTransform.h"
#include "itkRegularStepGradientDescentOptimizer.h"
// Software Guide : EndCodeSnippet
#include "itkBSplineResampleImageFunction.h"
#include "itkBSplineDecompositionImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkResampleImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkSquaredDifferenceImageFilter.h"
#include "itkTransformFileReader.h"
// The following section of code implements a Command observer
// used to monitor the evolution of the registration process.
//
#include "itkCommand.h"
class CommandIterationUpdate : public itk::Command
{
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro( Self );
protected:
CommandIterationUpdate() {};
public:
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef const OptimizerType * OptimizerPointer;
void Execute(itk::Object *caller, const itk::EventObject & event) ITK_OVERRIDE
{
Execute( (const itk::Object *)caller, event);
}
void Execute(const itk::Object * object, const itk::EventObject & event) ITK_OVERRIDE
{
OptimizerPointer optimizer = static_cast< OptimizerPointer >( object );
if( !(itk::IterationEvent().CheckEvent( &event )) )
{
return;
}
std::cout << optimizer->GetCurrentIteration() << " ";
std::cout << optimizer->GetValue() << " ";
std::cout << std::endl;
}
};
int main( int argc, char *argv[] )
{
if( argc < 4 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " fixedImageFile movingImageFile outputImagefile ";
std::cerr << " [differenceOutputfile] [differenceBeforeRegistration] ";
std::cerr << " [deformationField] ";
std::cerr << " [useExplicitPDFderivatives ] [useCachingBSplineWeights ] ";
std::cerr << " [filenameForFinalTransformParameters] ";
std::cerr << " [numberOfGridNodesInsideImageInOneDimensionCoarse] ";
std::cerr << " [numberOfGridNodesInsideImageInOneDimensionFine] ";
std::cerr << " [maximumStepLength] [maximumNumberOfIterations]";
std::cerr << std::endl;
return EXIT_FAILURE;
}
const unsigned int ImageDimension = 3;
typedef signed short PixelType;
typedef itk::Image< PixelType, ImageDimension > FixedImageType;
typedef itk::Image< PixelType, ImageDimension > MovingImageType;
const unsigned int SpaceDimension = ImageDimension;
const unsigned int SplineOrder = 3;
typedef double CoordinateRepType;
typedef itk::VersorRigid3DTransform< double > RigidTransformType;
typedef itk::AffineTransform< double, SpaceDimension > AffineTransformType;
typedef itk::BSplineTransform<
CoordinateRepType,
SpaceDimension,
SplineOrder > DeformableTransformType;
typedef itk::CenteredTransformInitializer< RigidTransformType,
FixedImageType,
MovingImageType
> TransformInitializerType;
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef itk::MattesMutualInformationImageToImageMetric<
FixedImageType,
MovingImageType > MetricType;
typedef itk:: LinearInterpolateImageFunction<
MovingImageType,
double > InterpolatorType;
typedef itk::ImageRegistrationMethod<
FixedImageType,
MovingImageType > RegistrationType;
MetricType::Pointer metric = MetricType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
InterpolatorType::Pointer interpolator = InterpolatorType::New();
RegistrationType::Pointer registration = RegistrationType::New();
registration->SetMetric( metric );
registration->SetOptimizer( optimizer );
registration->SetInterpolator( interpolator );
// Auxiliary identity transform.
typedef itk::IdentityTransform<double,SpaceDimension> IdentityTransformType;
IdentityTransformType::Pointer identityTransform = IdentityTransformType::New();
//
// Read the Fixed and Moving images.
//
typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;
typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;
FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();
MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();
fixedImageReader->SetFileName( argv[1] );
movingImageReader->SetFileName( argv[2] );
try
{
fixedImageReader->Update();
movingImageReader->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput();
registration->SetFixedImage( fixedImage );
registration->SetMovingImage( movingImageReader->GetOutput() );
//
// Add a time and memory probes collector for profiling the computation time
// of every stage.
//
itk::TimeProbesCollectorBase chronometer;
itk::MemoryProbesCollectorBase memorymeter;
//
// Setup the metric parameters
//
metric->SetNumberOfHistogramBins( 50 );
FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion();
const unsigned int numberOfPixels = fixedRegion.GetNumberOfPixels();
metric->ReinitializeSeed( 76926294 );
if( argc > 7 )
{
// Define whether to calculate the metric derivative by explicitly
// computing the derivatives of the joint PDF with respect to the Transform
// parameters, or doing it by progressively accumulating contributions from
// each bin in the joint PDF.
metric->SetUseExplicitPDFDerivatives( atoi( argv[7] ) );
}
if( argc > 8 )
{
// Define whether to cache the BSpline weights and indexes corresponding to
// each one of the samples used to compute the metric. Enabling caching will
// make the algorithm run faster but it will have a cost on the amount of memory
// that needs to be allocated. This option is only relevant when using the
// BSplineTransform.
metric->SetUseCachingOfBSplineWeights( atoi( argv[8] ) );
}
//
// Initialize a rigid transform by using Image Intensity Moments
//
TransformInitializerType::Pointer initializer = TransformInitializerType::New();
RigidTransformType::Pointer rigidTransform = RigidTransformType::New();
initializer->SetTransform( rigidTransform );
initializer->SetFixedImage( fixedImageReader->GetOutput() );
initializer->SetMovingImage( movingImageReader->GetOutput() );
initializer->MomentsOn();
std::cout << "Starting Rigid Transform Initialization " << std::endl;
memorymeter.Start( "Rigid Initialization" );
chronometer.Start( "Rigid Initialization" );
initializer->InitializeTransform();
chronometer.Stop( "Rigid Initialization" );
memorymeter.Stop( "Rigid Initialization" );
std::cout << "Rigid Transform Initialization completed" << std::endl;
std::cout << std::endl;
registration->SetFixedImageRegion( fixedRegion );
registration->SetInitialTransformParameters( rigidTransform->GetParameters() );
registration->SetTransform( rigidTransform );
//
// Define optimizer normaliztion to compensate for different dynamic range
// of rotations and translations.
//
typedef OptimizerType::ScalesType OptimizerScalesType;
OptimizerScalesType optimizerScales( rigidTransform->GetNumberOfParameters() );
const double translationScale = 1.0 / 1000.0;
optimizerScales[0] = 1.0;
optimizerScales[1] = 1.0;
optimizerScales[2] = 1.0;
optimizerScales[3] = translationScale;
optimizerScales[4] = translationScale;
optimizerScales[5] = translationScale;
optimizer->SetScales( optimizerScales );
optimizer->SetMaximumStepLength( 0.2000 );
optimizer->SetMinimumStepLength( 0.0001 );
optimizer->SetNumberOfIterations( 200 );
//
// The rigid transform has 6 parameters we use therefore a few samples to run
// this stage.
//
// Regulating the number of samples in the Metric is equivalent to performing
// multi-resolution registration because it is indeed a sub-sampling of the
// image.
metric->SetNumberOfSpatialSamples( 10000L );
//
// Create the Command observer and register it with the optimizer.
//
CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
optimizer->AddObserver( itk::IterationEvent(), observer );
std::cout << "Starting Rigid Registration " << std::endl;
try
{
memorymeter.Start( "Rigid Registration" );
chronometer.Start( "Rigid Registration" );
registration->Update();
chronometer.Stop( "Rigid Registration" );
memorymeter.Stop( "Rigid Registration" );
std::cout << "Optimizer stop condition = "
<< registration->GetOptimizer()->GetStopConditionDescription()
<< std::endl;
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
std::cout << "Rigid Registration completed" << std::endl;
std::cout << std::endl;
rigidTransform->SetParameters( registration->GetLastTransformParameters() );
//
// Perform Affine Registration
//
AffineTransformType::Pointer affineTransform = AffineTransformType::New();
affineTransform->SetCenter( rigidTransform->GetCenter() );
affineTransform->SetTranslation( rigidTransform->GetTranslation() );
affineTransform->SetMatrix( rigidTransform->GetMatrix() );
registration->SetTransform( affineTransform );
registration->SetInitialTransformParameters( affineTransform->GetParameters() );
optimizerScales = OptimizerScalesType( affineTransform->GetNumberOfParameters() );
optimizerScales[0] = 1.0;
optimizerScales[1] = 1.0;
optimizerScales[2] = 1.0;
optimizerScales[3] = 1.0;
optimizerScales[4] = 1.0;
optimizerScales[5] = 1.0;
optimizerScales[6] = 1.0;
optimizerScales[7] = 1.0;
optimizerScales[8] = 1.0;
optimizerScales[9] = translationScale;
optimizerScales[10] = translationScale;
optimizerScales[11] = translationScale;
optimizer->SetScales( optimizerScales );
optimizer->SetMaximumStepLength( 0.2000 );
optimizer->SetMinimumStepLength( 0.0001 );
optimizer->SetNumberOfIterations( 200 );
//
// The Affine transform has 12 parameters we use therefore a more samples to run
// this stage.
//
// Regulating the number of samples in the Metric is equivalent to performing
// multi-resolution registration because it is indeed a sub-sampling of the
// image.
metric->SetNumberOfSpatialSamples( 50000L );
std::cout << "Starting Affine Registration " << std::endl;
try
{
memorymeter.Start( "Affine Registration" );
chronometer.Start( "Affine Registration" );
registration->Update();
chronometer.Stop( "Affine Registration" );
memorymeter.Stop( "Affine Registration" );
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
std::cout << "Affine Registration completed" << std::endl;
std::cout << std::endl;
affineTransform->SetParameters( registration->GetLastTransformParameters() );
//
// Perform Deformable Registration
//
DeformableTransformType::Pointer bsplineTransformCoarse = DeformableTransformType::New();
unsigned int numberOfGridNodesInOneDimensionCoarse = 5;
DeformableTransformType::PhysicalDimensionsType fixedPhysicalDimensions;
DeformableTransformType::MeshSizeType meshSize;
DeformableTransformType::OriginType fixedOrigin;
for( unsigned int i=0; i< SpaceDimension; i++ )
{
fixedOrigin[i] = fixedImage->GetOrigin()[i];
fixedPhysicalDimensions[i] = fixedImage->GetSpacing()[i] *
static_cast<double>(
fixedImage->GetLargestPossibleRegion().GetSize()[i] - 1 );
}
meshSize.Fill( numberOfGridNodesInOneDimensionCoarse - SplineOrder );
bsplineTransformCoarse->SetTransformDomainOrigin( fixedOrigin );
bsplineTransformCoarse->SetTransformDomainPhysicalDimensions(
fixedPhysicalDimensions );
bsplineTransformCoarse->SetTransformDomainMeshSize( meshSize );
bsplineTransformCoarse->SetTransformDomainDirection(
fixedImage->GetDirection() );
typedef DeformableTransformType::ParametersType ParametersType;
unsigned int numberOfBSplineParameters = bsplineTransformCoarse->GetNumberOfParameters();
optimizerScales = OptimizerScalesType( numberOfBSplineParameters );
optimizerScales.Fill( 1.0 );
optimizer->SetScales( optimizerScales );
ParametersType initialDeformableTransformParameters( numberOfBSplineParameters );
initialDeformableTransformParameters.Fill( 0.0 );
bsplineTransformCoarse->SetParameters( initialDeformableTransformParameters );
registration->SetInitialTransformParameters( bsplineTransformCoarse->GetParameters() );
registration->SetTransform( bsplineTransformCoarse );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Next we set the parameters of the RegularStepGradientDescentOptimizer object.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
optimizer->SetMaximumStepLength( 10.0 );
optimizer->SetMinimumStepLength( 0.01 );
optimizer->SetRelaxationFactor( 0.7 );
optimizer->SetNumberOfIterations( 50 );
// Software Guide : EndCodeSnippet
// Optionally, get the step length from the command line arguments
if( argc > 11 )
{
optimizer->SetMaximumStepLength( atof( argv[12] ) );
}
// Optionally, get the number of iterations from the command line arguments
if( argc > 12 )
{
optimizer->SetNumberOfIterations( atoi( argv[13] ) );
}
//
// The BSpline transform has a large number of parameters, we use therefore a
// much larger number of samples to run this stage.
//
// Regulating the number of samples in the Metric is equivalent to performing
// multi-resolution registration because it is indeed a sub-sampling of the
// image.
metric->SetNumberOfSpatialSamples( numberOfBSplineParameters * 100 );
std::cout << std::endl << "Starting Deformable Registration Coarse Grid" << std::endl;
try
{
memorymeter.Start( "Deformable Registration Coarse" );
chronometer.Start( "Deformable Registration Coarse" );
registration->Update();
chronometer.Stop( "Deformable Registration Coarse" );
memorymeter.Stop( "Deformable Registration Coarse" );
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
std::cout << "Deformable Registration Coarse Grid completed" << std::endl;
std::cout << std::endl;
OptimizerType::ParametersType finalParameters =
registration->GetLastTransformParameters();
bsplineTransformCoarse->SetParameters( finalParameters );
// Software Guide : BeginLatex
//
// Once the registration has finished with the low resolution grid, we
// proceed to instantiate a higher resolution
// \code{BSplineTransform}.
//
// Software Guide : EndLatex
DeformableTransformType::Pointer bsplineTransformFine = DeformableTransformType::New();
unsigned int numberOfGridNodesInOneDimensionFine = 5;
meshSize.Fill( numberOfGridNodesInOneDimensionFine - SplineOrder );
bsplineTransformFine->SetTransformDomainOrigin( fixedOrigin );
bsplineTransformFine->SetTransformDomainPhysicalDimensions(
fixedPhysicalDimensions );
bsplineTransformFine->SetTransformDomainMeshSize( meshSize );
bsplineTransformFine->SetTransformDomainDirection(
fixedImage->GetDirection() );
numberOfBSplineParameters = bsplineTransformFine->GetNumberOfParameters();
ParametersType parametersHigh( numberOfBSplineParameters );
parametersHigh.Fill( 0.0 );
// Software Guide : BeginLatex
//
// Now we need to initialize the BSpline coefficients of the higher resolution
// transform. This is done by first computing the actual deformation field
// at the higher resolution from the lower resolution BSpline coefficients.
// Then a BSpline decomposition is done to obtain the BSpline coefficient of
// the higher resolution transform.
//
// Software Guide : EndLatex
unsigned int counter = 0;
for ( unsigned int k = 0; k < SpaceDimension; k++ )
{
typedef DeformableTransformType::ImageType ParametersImageType;
typedef itk::ResampleImageFilter<ParametersImageType,ParametersImageType> ResamplerType;
ResamplerType::Pointer upsampler = ResamplerType::New();
typedef itk::BSplineResampleImageFunction<ParametersImageType,double> FunctionType;
FunctionType::Pointer function = FunctionType::New();
upsampler->SetInput( bsplineTransformCoarse->GetCoefficientImages()[k] );
upsampler->SetInterpolator( function );
upsampler->SetTransform( identityTransform );
upsampler->SetSize( bsplineTransformFine->GetCoefficientImages()[k]->
GetLargestPossibleRegion().GetSize() );
upsampler->SetOutputSpacing( bsplineTransformFine->GetCoefficientImages()[k]->
GetSpacing() );
upsampler->SetOutputOrigin( bsplineTransformFine->GetCoefficientImages()[k]->
GetOrigin() );
typedef itk::BSplineDecompositionImageFilter<ParametersImageType,ParametersImageType>
DecompositionType;
DecompositionType::Pointer decomposition = DecompositionType::New();
decomposition->SetSplineOrder( SplineOrder );
decomposition->SetInput( upsampler->GetOutput() );
decomposition->Update();
ParametersImageType::Pointer newCoefficients = decomposition->GetOutput();
// copy the coefficients into the parameter array
typedef itk::ImageRegionIterator<ParametersImageType> Iterator;
Iterator it( newCoefficients, bsplineTransformFine->GetCoefficientImages()[k]->
GetLargestPossibleRegion() );
while ( !it.IsAtEnd() )
{
parametersHigh[ counter++ ] = it.Get();
++it;
}
}
optimizerScales = OptimizerScalesType( numberOfBSplineParameters );
optimizerScales.Fill( 1.0 );
optimizer->SetScales( optimizerScales );
bsplineTransformFine->SetParameters( parametersHigh );
// Software Guide : BeginLatex
//
// We now pass the parameters of the high resolution transform as the initial
// parameters to be used in a second stage of the registration process.
//
// Software Guide : EndLatex
std::cout << "Starting Registration with high resolution transform" << std::endl;
// Software Guide : BeginCodeSnippet
registration->SetInitialTransformParameters(
bsplineTransformFine->GetParameters() );
registration->SetTransform( bsplineTransformFine );
//
// The BSpline transform at fine scale has a very large number of parameters,
// we use therefore a much larger number of samples to run this stage. In
// this case, however, the number of transform parameters is closer to the
// number of pixels in the image. Therefore we use the geometric mean of the
// two numbers to ensure that the number of samples is larger than the number
// of transform parameters and smaller than the number of samples.
//
// Regulating the number of samples in the Metric is equivalent to performing
// multi-resolution registration because it is indeed a sub-sampling of the
// image.
const unsigned long numberOfSamples =
static_cast<unsigned long>(
std::sqrt( static_cast<double>( numberOfBSplineParameters ) *
static_cast<double>( numberOfPixels ) ) );
metric->SetNumberOfSpatialSamples( numberOfSamples );
try
{
memorymeter.Start( "Deformable Registration Fine" );
chronometer.Start( "Deformable Registration Fine" );
registration->Update();
chronometer.Stop( "Deformable Registration Fine" );
memorymeter.Stop( "Deformable Registration Fine" );
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
// Software Guide : EndCodeSnippet
std::cout << "Deformable Registration Fine Grid completed" << std::endl;
std::cout << std::endl;
// Report the time and memory taken by the registration
chronometer.Report( std::cout );
memorymeter.Report( std::cout );
finalParameters = registration->GetLastTransformParameters();
bsplineTransformFine->SetParameters( finalParameters );
typedef itk::ResampleImageFilter<
MovingImageType,
FixedImageType > ResampleFilterType;
ResampleFilterType::Pointer resample = ResampleFilterType::New();
resample->SetTransform( bsplineTransformFine );
resample->SetInput( movingImageReader->GetOutput() );
resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );
resample->SetOutputOrigin( fixedImage->GetOrigin() );
resample->SetOutputSpacing( fixedImage->GetSpacing() );
resample->SetOutputDirection( fixedImage->GetDirection() );
// This value is set to zero in order to make easier to perform
// regression testing in this example. However, for didactic
// exercise it will be better to set it to a medium gray value
// such as 100 or 128.
resample->SetDefaultPixelValue( 0 );
typedef signed short OutputPixelType;
typedef itk::Image< OutputPixelType, ImageDimension > OutputImageType;
typedef itk::CastImageFilter<
FixedImageType,
OutputImageType > CastFilterType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
CastFilterType::Pointer caster = CastFilterType::New();
writer->SetFileName( argv[3] );
caster->SetInput( resample->GetOutput() );
writer->SetInput( caster->GetOutput() );
std::cout << "Writing resampled moving image...";
try
{
writer->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
std::cout << " Done!" << std::endl;
typedef itk::SquaredDifferenceImageFilter<
FixedImageType,
FixedImageType,
OutputImageType > DifferenceFilterType;
DifferenceFilterType::Pointer difference = DifferenceFilterType::New();
WriterType::Pointer writer2 = WriterType::New();
writer2->SetInput( difference->GetOutput() );
// Compute the difference image between the
// fixed and resampled moving image.
if( argc > 4 )
{
difference->SetInput1( fixedImageReader->GetOutput() );
difference->SetInput2( resample->GetOutput() );
writer2->SetFileName( argv[4] );
std::cout << "Writing difference image after registration...";
try
{
writer2->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
std::cout << " Done!" << std::endl;
}
// Compute the difference image between the
// fixed and moving image before registration.
if( argc > 5 )
{
writer2->SetFileName( argv[5] );
difference->SetInput1( fixedImageReader->GetOutput() );
resample->SetTransform( identityTransform );
std::cout << "Writing difference image before registration...";
try
{
writer2->Update();
}
catch( itk::ExceptionObject & err )
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
std::cout << " Done!" << std::endl;
}
// Generate the explicit deformation field resulting from
// the registration.
if( argc > 6 )
{
typedef itk::Vector< float, ImageDimension > VectorType;
typedef itk::Image< VectorType, ImageDimension > DisplacementFieldType;
DisplacementFieldType::Pointer field = DisplacementFieldType::New();
field->SetRegions( fixedRegion );
field->SetOrigin( fixedImage->GetOrigin() );
field->SetSpacing( fixedImage->GetSpacing() );
field->SetDirection( fixedImage->GetDirection() );
field->Allocate();
typedef itk::ImageRegionIterator< DisplacementFieldType > FieldIterator;
FieldIterator fi( field, fixedRegion );
fi.GoToBegin();
DeformableTransformType::InputPointType fixedPoint;
DeformableTransformType::OutputPointType movingPoint;
DisplacementFieldType::IndexType index;
VectorType displacement;
while( ! fi.IsAtEnd() )
{
index = fi.GetIndex();
field->TransformIndexToPhysicalPoint( index, fixedPoint );
movingPoint = bsplineTransformFine->TransformPoint( fixedPoint );
displacement = movingPoint - fixedPoint;
fi.Set( displacement );
++fi;
}
typedef itk::ImageFileWriter< DisplacementFieldType > FieldWriterType;
FieldWriterType::Pointer fieldWriter = FieldWriterType::New();
fieldWriter->SetInput( field );
fieldWriter->SetFileName( argv[6] );
std::cout << "Writing deformation field ...";
try
{
fieldWriter->Update();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception thrown " << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
std::cout << " Done!" << std::endl;
}
// Optionally, save the transform parameters in a file
if( argc > 9 )
{
std::cout << "Writing transform parameter file ...";
std::ofstream parametersFile;
parametersFile.open( argv[9] );
parametersFile << finalParameters << std::endl;
parametersFile.close();
std::cout << " Done!" << std::endl;
}
return EXIT_SUCCESS;
}
|