public void Apply()
        {
            if (this.SelectedImageGraphicProvider == null)
            {
                return;
            }

            ImageGraphic image = this.SelectedImageGraphicProvider.ImageGraphic;

            if (image == null)
            {
                return;
            }

            if (!(image is GrayscaleImageGraphic))
            {
                return;
            }

            itkImageBase input  = ItkHelper.CreateItkImage(image as GrayscaleImageGraphic);
            itkImageBase output = itkImage.New(input);

            ItkHelper.CopyToItkImage(image as GrayscaleImageGraphic, input);

            String mangledType            = input.MangledTypeString;
            CastImageFilterType castToIF2 = CastImageFilterType.New(mangledType + "IF2");

            SmoothingFilterType smoothingFilter = SmoothingFilterType.New("IF2IF2");

            smoothingFilter.TimeStep             = 0.125;
            smoothingFilter.NumberOfIterations   = 5;
            smoothingFilter.ConductanceParameter = 9.0;

            GradientMagnitudeFilterType gradientMagnitudeFilter = GradientMagnitudeFilterType.New("IF2IF2");

            gradientMagnitudeFilter.Sigma = 1.0;

            SigmoidFilterType sigmoidFilter = SigmoidFilterType.New("IF2IF2");

            sigmoidFilter.OutputMinimum = 0.0;
            sigmoidFilter.OutputMaximum = 1.0;
            sigmoidFilter.Alpha         = -0.5; //-0.3
            sigmoidFilter.Beta          = 3.0;  //2.0

            FastMarchingFilterType fastMarchingFilter = FastMarchingFilterType.New("IF2IF2");
            double seedValue = 0.0;

            int[]    seedPosition = { 256, 256 };// user input
            itkIndex seedIndex    = new itkIndex(seedPosition);

            itkLevelSetNode[] trialPoints = { new itkLevelSetNode(seedValue, seedIndex) };
            fastMarchingFilter.TrialPoints   = trialPoints;
            fastMarchingFilter.StoppingValue = 100;

            BinaryThresholdFilterType binaryThresholdFilter = BinaryThresholdFilterType.New("IF2" + mangledType); //to UC2?

            binaryThresholdFilter.UpperThreshold = 100.0;                                                         //200
            binaryThresholdFilter.LowerThreshold = 0.0;
            binaryThresholdFilter.OutsideValue   = 0;
            if (image.BitsPerPixel == 16)
            {
                binaryThresholdFilter.InsideValue = (image as GrayscaleImageGraphic).ModalityLut.MaxInputValue;//32767;
            }
            else
            {
                binaryThresholdFilter.InsideValue = 255;
            }

            //intensityFilterType intensityFilter = intensityFilterType.New("UC2" + mangledType);
            //intensityFilter.OutputMinimum = 0;
            //if (image.BitsPerPixel == 16)
            //    intensityFilter.OutputMaximum = (image as GrayscaleImageGraphic).ModalityLut.MaxInputValue;//32767;
            //else
            //    intensityFilter.OutputMaximum = 255;

            // Make data stream connections
            castToIF2.SetInput(input);
            smoothingFilter.SetInput(castToIF2.GetOutput());
            gradientMagnitudeFilter.SetInput(smoothingFilter.GetOutput());
            sigmoidFilter.SetInput(gradientMagnitudeFilter.GetOutput());
            fastMarchingFilter.SetInput(sigmoidFilter.GetOutput());
            binaryThresholdFilter.SetInput(fastMarchingFilter.GetOutput());
            //intensityFilter.SetInput(binaryThresholdFilter.GetOutput());

            //smoothingFilter.Update();
            fastMarchingFilter.OutputSize = input.BufferedRegion.Size;//?
            binaryThresholdFilter.Update();

            binaryThresholdFilter.GetOutput(output);
            ItkHelper.CopyFromItkImage(image as GrayscaleImageGraphic, output);
            image.Draw();

            input.Dispose();
            output.Dispose();
        }
        public void Apply()
        {
            if (this.SelectedImageGraphicProvider == null)
            {
                return;
            }

            ImageGraphic image = this.SelectedImageGraphicProvider.ImageGraphic;

            if (image == null)
            {
                return;
            }

            if (!(image is GrayscaleImageGraphic))
            {
                return;
            }

            byte[] pixels = image.PixelData.Raw;

            itkImageBase   input  = ItkHelper.CreateItkImage(image as GrayscaleImageGraphic);
            itkImageRegion region = input.LargestPossibleRegion;

            itkImageBase output = itkImage.New(input);

            ItkHelper.CopyToItkImage(image as GrayscaleImageGraphic, input);

            String mangledType            = input.MangledTypeString;
            CastImageFilterType castToIF2 = CastImageFilterType.New(mangledType + "IF2");

            castToIF2.SetInput(input);

            FilterType filter = FilterType.New("IF2IF2");

            filter.SetInput(castToIF2.GetOutput());

            // TODO: need to allow user to set parameters of filter
            filter.LowerThreshold = 90;
            filter.UpperThreshold = 127;
            //filter.OutsideValue = 0;
            // smoothing the edge
            double[] error = { 0.01, 0.01 };
            filter.MaximumError = error;
            double[] var = { 1.0, 1.0 };
            filter.Variance = var;

            intensityFilterType intensityFilter = intensityFilterType.New("IF2" + mangledType);

            intensityFilter.SetInput(filter.GetOutput());
            intensityFilter.OutputMinimum = 0;
            if (image.BitsPerPixel == 16)
            {
                intensityFilter.OutputMaximum = (image as GrayscaleImageGraphic).ModalityLut.MaxInputValue;//32767;
            }
            else
            {
                intensityFilter.OutputMaximum = 255;
            }
            intensityFilter.Update();

#if DEBUG
            bool debug = false;
            if (debug)
            {
                itkImageBase outputIF2 = itkImage.New("IF2");
                filter.GetOutput(outputIF2);
                float min = float.MaxValue, max = float.MinValue;
                unsafe
                {
                    fixed(byte *pDstByte = image.PixelData.Raw)
                    {
                        itkImageRegionConstIterator_IF2 itkIt = new itkImageRegionConstIterator_IF2(outputIF2, region);
                        byte *pDst   = (byte *)pDstByte;
                        int   height = image.Rows;
                        int   width  = image.Columns;

                        for (int y = 0; y < height; y++)
                        {
                            for (int x = 0; x < width; x++)
                            {
                                float f = itkIt.Get().ValueAsF;
                                if (f > max)
                                {
                                    max = f;
                                }
                                if (f < min)
                                {
                                    min = f;
                                }
                                pDst[0] = (byte)itkIt.Get().ValueAsF;
                                pDst++;
                                itkIt++;
                            }
                        }
                    }
                }
                Console.WriteLine("min max "); Console.Write(min); Console.Write(" "); Console.WriteLine(max);
            }
#endif

            intensityFilter.GetOutput(output);
            ItkHelper.CopyFromItkImage(image as GrayscaleImageGraphic, output);
            image.Draw();

            filter.Dispose();
            intensityFilter.Dispose();
            input.Dispose();
            output.Dispose();
        }
        public void Apply()
        {
            if (this.SelectedImageGraphicProvider == null)
            {
                return;
            }

            ImageGraphic image = this.SelectedImageGraphicProvider.ImageGraphic;

            if (image == null)
            {
                return;
            }

            if (!(image is GrayscaleImageGraphic))
            {
                return;
            }

            byte[] pixels = image.PixelData.Raw;

            itkImageBase   input  = ItkHelper.CreateItkImage(image as GrayscaleImageGraphic);
            itkImageRegion region = input.LargestPossibleRegion;

            itkImageBase output = itkImage.New(input);

            ItkHelper.CopyToItkImage(image as GrayscaleImageGraphic, input);

            string mangledType            = input.MangledTypeString;
            string mangledType2           = input.PixelType.MangledTypeString;
            CastImageFilterType castToIF2 = CastImageFilterType.New(mangledType + "IF2");

            castToIF2.SetInput(input);

            FilterType filter = FilterType.New("IF2IF2");

            filter.SetInput(castToIF2.GetOutput());

            intensityFilterType intensityFilter = intensityFilterType.New("IF2" + mangledType);

            intensityFilter.SetInput(filter.GetOutput());
            intensityFilter.OutputMinimum = 0;
            if (image.BitsPerPixel == 16)
            {
                intensityFilter.OutputMaximum = (image as GrayscaleImageGraphic).ModalityLut.MaxInputValue;
            }
            else
            {
                intensityFilter.OutputMaximum = 255;
            }
            intensityFilter.Update();


            intensityFilter.GetOutput(output);
            ItkHelper.CopyFromItkImage(image as GrayscaleImageGraphic, output);
            image.Draw();

            filter.Dispose();
            intensityFilter.Dispose();
            input.Dispose();
            output.Dispose();
        }
    static void Main(string[] args) {
        try {
            // Get input parameters
            if (args.Length < 3) {
                Console.WriteLine("Missing Parameters");
                Console.Write("Usage: " + Environment.GetCommandLineArgs()[0] + " ");
                Console.Write("fixedImageFile movingImageFile ");
                Console.Write("outputImagefile ");
                Console.WriteLine("[checkerBoardBefore] [checkerBoardAfter]");
                return;
            }

            // Create components
            TransformType transform = TransformType.New();
            OptimizerType optimizer = OptimizerType.New();
            InterpolatorType interpolator = InterpolatorType.New();
            MetricType metric = MetricType.New();
            RegistrationType registration = RegistrationType.New();
            registration.SetOptimizer(optimizer);
            registration.SetTransform(transform);
            registration.SetInterpolator(interpolator);
            registration.SetMetric(metric);

            // Set metric parameters
            metric.FixedImageStandardDeviation = 0.4;
            metric.MovingImageStandardDeviation = 0.4;

            // Read input images
            ImageType fixedImage = ImageType.New();
            fixedImage.Read(args[0]);
            ImageType movingImage = ImageType.New();
            movingImage.Read(args[1]);

            // Normailize
            NormalizeFilterType fixedNormalizer = NormalizeFilterType.New();
            NormalizeFilterType movingNormalizer = NormalizeFilterType.New();
            GaussianFilterType fixedSmoother = GaussianFilterType.New();
            GaussianFilterType movingSmoother = GaussianFilterType.New();
            fixedSmoother.Variance = new double[] { 2.0, 2.0 };
            movingSmoother.Variance = new double[] { 2.0, 2.0 };

            // Setup pipeline
            fixedNormalizer.SetInput(fixedImage);
            movingNormalizer.SetInput(movingImage);
            fixedSmoother.SetInput(fixedNormalizer.GetOutput());
            movingSmoother.SetInput(movingNormalizer.GetOutput());
            ImageType fixedSmootherOutput = ImageType.New();
            fixedSmoother.GetOutput(fixedSmootherOutput);
            ImageType movingSmootherOutput = ImageType.New();
            movingSmoother.GetOutput(movingSmootherOutput);
            registration.SetFixedImage(fixedSmootherOutput);
            registration.SetMovingImage(movingSmootherOutput);

            // Set requested region
            fixedNormalizer.Update();
            ImageType fixedNormalizerOutput = ImageType.New();
            fixedNormalizer.GetOutput(fixedNormalizerOutput);
            RegionType fixedImageRegion = fixedNormalizerOutput.BufferedRegion;
            fixedImage.RequestedRegion = fixedImageRegion;
            //registration.FixedImageRegion = fixedImageRegion

            // Set initial parameters
            ParametersType initialParameters =
                new ParametersType(transform.NumberOfParameters);
            initialParameters[0] = 0.0;
            initialParameters[1] = 0.0;
            registration.InitialTransformParameters = initialParameters;

            // Set metric sampling
            int numberOfPixels = fixedImageRegion.Size[0] * fixedImageRegion.Size[1];
            int numberOfSamples = (int)((double)numberOfPixels * 0.01);
            metric.NumberOfSpatialSamples = (uint)numberOfSamples;

            // Setup optimizer
            optimizer.LearningRate = 15.0;
            optimizer.NumberOfIterations = 200;
            optimizer.Maximize = true;

            // Listen for iteration events
            optimizer.Iteration += OnOptimizerIterationEvent;

            // Start registration
            registration.StartRegistration();
            Console.WriteLine(optimizer.StopCondition);

            // Get results
            ParametersType finalParameters = registration.LastTransformParameters;
            double TranslationAlongX = finalParameters[0];
            double TranslationAlongY = finalParameters[1];
            uint numberOfIterations = optimizer.NumberOfIterations;
            double bestValue = optimizer.GetValue();

            // Print results
            Console.WriteLine("Result=");
            Console.WriteLine(String.Format(" Translation X = {0}", TranslationAlongX));
            Console.WriteLine(String.Format(" Translation Y = {0}", TranslationAlongY));
            Console.WriteLine(String.Format(" Iterations    = {0}", numberOfIterations));
            Console.WriteLine(String.Format(" Metric value  = {0}", bestValue));
            Console.WriteLine(String.Format(" Numb. Samples = {0}", numberOfSamples));

            // Setup resample filter
            TransformType finalTransform = TransformType.New();
            finalTransform.Parameters = finalParameters;
            //finalTransform.FixedParameters = transform.FixedParameters;
            ResampleFilterType resample = ResampleFilterType.New();
            resample.SetTransform(finalTransform);
            resample.SetInput(movingImage);
            resample.OutputSize = fixedImage.LargestPossibleRegion.Size;
            resample.OutputSpacing = fixedImage.Spacing;
            resample.OutputOrigin = fixedImage.Origin;
            resample.DefaultPixelValue = 100;

            // Write resampled output
            OutputImageType output = OutputImageType.New();
            CastFilterType caster = CastFilterType.New(movingImage, output);
            caster.SetInput(resample.GetOutput());
            caster.Update();
            caster.GetOutput(output);
            output.Write(args[2]);

            // Generate checkerboards before registration
            CheckerBoardType checker = CheckerBoardType.New();
            checker.SetInput1(fixedImage);
            checker.SetInput2(movingImage);
            checker.Update();
            ImageType checkerOut = ImageType.New();
            checker.GetOutput(checkerOut);
            caster.SetInput(checkerOut);
            caster.Update();
            caster.GetOutput(output);
            if (args.Length > 3) {
                output.Write(args[3]);
            }

            // Generate checkerboards after registration
            checker.SetInput1(fixedImage);
            checker.SetInput2(resample.GetOutput());
            checker.Update();
            checker.GetOutput(checkerOut);
            caster.SetInput(checkerOut);
            caster.Update();
            caster.GetOutput(output);
            if (args.Length > 4) {
                output.Write(args[4]);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }