static void Main(string[] args)
        {
            if (args.Length < 8)
            {
                Console.WriteLine("Missing Parameters ");
                Console.WriteLine("Usage: " + System.AppDomain.CurrentDomain.FriendlyName +
                                  "inputImage initialModel outputImage cannyThreshold " +
                                  "cannyVariance advectionWeight initialModelIsovalue maximumIterations ");
                return;
            }

            string inputFilename        = args[0];
            string initialModelFilename = args[1];

            string outputFilename = args[2];

            double cannyThreshold      = double.Parse(args[3], CultureInfo.InvariantCulture);
            double cannyVariance       = double.Parse(args[4], CultureInfo.InvariantCulture);
            double advectionWeight     = double.Parse(args[5], CultureInfo.InvariantCulture);
            double intialModelIsovalue = double.Parse(args[6], CultureInfo.InvariantCulture);
            uint   maxIterations       = uint.Parse(args[7], CultureInfo.InvariantCulture);

            // Read input image

            SitkImage inputImage   = SimpleITK.ReadImage(inputFilename, PixelId.sitkFloat32);
            SitkImage initialModel = SimpleITK.ReadImage(initialModelFilename, PixelId.sitkFloat32);

            //  The input image will be processed with a few iterations of
            //  feature-preserving diffusion.  We create a filter and set the
            //  appropriate parameters.

            GradientAnisotropicDiffusionImageFilter diffusion = new GradientAnisotropicDiffusionImageFilter();

            diffusion.SetConductanceParameter(1.0);
            diffusion.SetTimeStep(0.125);
            diffusion.SetNumberOfIterations(5);
            SitkImage diffusedImage = diffusion.Execute(inputImage);

            // As with the other ITK level set segmentation filters, the terms of the
            // CannySegmentationLevelSetImageFilter level set equation can be
            // weighted by scalars.  For this application we will modify the relative
            // weight of the advection term.  The propagation and curvature term weights
            // are set to their defaults of 0 and 1, respectively.

            CannySegmentationLevelSetImageFilter cannySegmentation = new CannySegmentationLevelSetImageFilter();

            cannySegmentation.SetAdvectionScaling(advectionWeight);
            cannySegmentation.SetCurvatureScaling(1.0);
            cannySegmentation.SetPropagationScaling(0.0);

            //  The maximum number of iterations is specified from the command line.
            //  It may not be desirable in some applications to run the filter to
            //  convergence.  Only a few iterations may be required.

            cannySegmentation.SetMaximumRMSError(0.01);
            cannySegmentation.SetNumberOfIterations(maxIterations);

            //  There are two important parameters in the
            //  CannySegmentationLevelSetImageFilter to control the behavior of the
            //  Canny edge detection.  The variance parameter controls the
            //  amount of Gaussian smoothing on the input image.  The threshold
            //  parameter indicates the lowest allowed value in the output image.
            //  Thresholding is used to suppress Canny edges whose gradient magnitudes
            //  fall below a certain value.

            cannySegmentation.SetThreshold(cannyThreshold);
            cannySegmentation.SetVariance(cannyVariance);

            // Finally, it is very important to specify the isovalue of the surface in
            // the initial model input image. In a binary image, for example, the
            // isosurface is found midway between the foreground and background values.

            cannySegmentation.SetIsoSurfaceValue(intialModelIsovalue);

            SitkImage output = cannySegmentation.Execute(initialModel, diffusedImage);

            BinaryThresholdImageFilter thresholder = new BinaryThresholdImageFilter();

            thresholder.SetUpperThreshold(10.0);
            thresholder.SetLowerThreshold(0.0);

            thresholder.SetOutsideValue(0);
            thresholder.SetInsideValue(255);
            output = thresholder.Execute(output);


            output = SimpleITK.Cast(output, PixelIDValueEnum.sitkUInt8);

            SimpleITK.WriteImage(output, outputFilename);

            // Print out some useful information
            Console.WriteLine("");
            Console.WriteLine("Max. no. iterations: {0}", cannySegmentation.GetNumberOfIterations());
            Console.WriteLine("Max. RMS error: {0}", cannySegmentation.GetMaximumRMSError());
            Console.WriteLine("");
            Console.WriteLine("No. elpased iterations: {0}", cannySegmentation.GetElapsedIterations());
            Console.WriteLine("RMS change: {0}", cannySegmentation.GetRMSChange());
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: inputImage outputImage");
                return;
            }

            string inputFilename  = args[0];
            string outputFilename = args[1];

            // Read input image
            SitkImage input = SimpleITK.ReadImage(inputFilename);

            // Cast so we know the the pixel type
            input = SimpleITK.Cast(input, PixelId.sitkFloat32);

            // calculate the number of pixels
            VectorUInt32 size = input.GetSize();
            int          len  = 1;

            for (int dim = 0; dim < input.GetDimension(); dim++)
            {
                len *= (int)size[dim];
            }
            IntPtr buffer = input.GetBufferAsFloat();

            // There are two ways to access the buffer:

            // (1) Access the underlying buffer as a pointer in an "unsafe" block
            // (note that in C# "unsafe" simply means that the compiler can not
            // perform full type checking), and requires the -unsafe compiler flag
            // unsafe {
            //   float* bufferPtr = (float*)buffer.ToPointer();

            //   // Now the byte pointer can be accessed as per Brad's email
            //   // (of course this example is only a 2d single channel image):
            //   // This is a 1-D array but can be access as a 3-D. Given an
            //   // image of size [xS,yS,zS], you can access the image at
            //   // index [x,y,z] as you wish by image[x+y*xS+z*xS*yS],
            //   // so x is the fastest axis and z is the slowest.
            //   for (int j = 0; j < size[1]; j++) {
            //     for (int i = 0; i < size[0]; i++) {
            //       float pixel = bufferPtr[i + j*size[1]];
            //       // Do something with pixel here
            //     }
            //   }
            // }

            // (2) Copy the buffer to a "safe" array (i.e. a fully typed array)
            // (note that this means memory is duplicated)
            float[] bufferAsArray = new float[len]; // Allocates new memory the size of input
            Marshal.Copy(buffer, bufferAsArray, 0, len);
            double total = 0.0;

            for (int j = 0; j < size[1]; j++)
            {
                for (int i = 0; i < size[0]; i++)
                {
                    float pixel = bufferAsArray[i + j * size[1]];
                    total += pixel;
                }
            }
            Console.WriteLine("Pixel value total: {0}", total);

            // Set buffer of new SimpleITK Image from managed array.
            // bufferAsArray could also have come from a bmp,png,etc...

            uint width  = input.GetWidth();
            uint height = input.GetHeight();

            SitkImage outImage       = new SitkImage(width, height, PixelId.sitkFloat32);
            IntPtr    outImageBuffer = outImage.GetBufferAsFloat();

            Marshal.Copy(bufferAsArray, 0, outImageBuffer, (int)(size[0] * size[1]));

            //
            // Write out the resulting file
            //
            outImage = SimpleITK.RescaleIntensity(outImage, 0, 255);
            outImage = SimpleITK.Cast(outImage, PixelId.sitkUInt8);

            SimpleITK.WriteImage(outImage, outputFilename);
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            if (args.Length < 9)
            {
                Console.WriteLine("Missing Parameters ");
                Console.WriteLine("Usage: " + System.AppDomain.CurrentDomain.FriendlyName +
                                  " inputImage outputImage seedX seedY " +
                                  " Sigma SigmoidAlpha SigmoidBeta TimeThreshold");
                return;
            }

            string inputFilename  = args[0];
            string outputFilename = args[1];

            uint[] seedPosition = { Convert.ToUInt32(args[2]), Convert.ToUInt32(args[3]), 0 };

            double sigma         = double.Parse(args[4], CultureInfo.InvariantCulture);
            double alpha         = double.Parse(args[5], CultureInfo.InvariantCulture);;
            double beta          = double.Parse(args[6], CultureInfo.InvariantCulture);
            double timeThreshold = double.Parse(args[7], CultureInfo.InvariantCulture);
            double stoppingTime  = double.Parse(args[8], CultureInfo.InvariantCulture);

            // Read input image

            SitkImage inputImage = SimpleITK.ReadImage(inputFilename, PixelIDValueEnum.sitkFloat32);

            //  The input image will be processed with a few iterations of
            //  feature-preserving diffusion.  We create a filter and set the
            //  appropriate parameters.

            CurvatureAnisotropicDiffusionImageFilter smoothing = new CurvatureAnisotropicDiffusionImageFilter();

            smoothing.SetTimeStep(0.125);
            smoothing.SetNumberOfIterations(5);
            smoothing.SetConductanceParameter(9.0);
            SitkImage smoothingOutput = smoothing.Execute(inputImage);

            SitkImage gradientMagnitudeOutput = SimpleITK.GradientMagnitudeRecursiveGaussian(smoothingOutput, sigma);

            SitkImage sigmoidOutput = SimpleITK.Sigmoid(gradientMagnitudeOutput, alpha, beta, 1.0, 0.0);


            FastMarchingImageFilter fastMarching = new FastMarchingImageFilter();

            //VectorUIntList trialPoints; Add trialPoints into list if using multiple seeds. Here we only use one seedpoint

            VectorUInt32 trialPoint = new VectorUInt32(3);

            trialPoint.Add(seedPosition[0]);
            trialPoint.Add(seedPosition[1]);
            trialPoint.Add(seedPosition[2]);

            fastMarching.AddTrialPoint(trialPoint);

            //  Since the front representing the contour will propagate continuously
            //  over time, it is desirable to stop the process once a certain time has
            //  been reached. This allows us to save computation time under the
            //  assumption that the region of interest has already been computed. The
            //  value for stopping the process is defined with the method
            //  SetStoppingValue(). In principle, the stopping value should be a
            //  little bit higher than the threshold value.

            fastMarching.SetStoppingValue(stoppingTime);

            SitkImage fastmarchingOutput = fastMarching.Execute(sigmoidOutput);

            BinaryThresholdImageFilter thresholder = new BinaryThresholdImageFilter();

            thresholder.SetLowerThreshold(0.0);
            thresholder.SetUpperThreshold(timeThreshold);
            thresholder.SetOutsideValue(0);
            thresholder.SetInsideValue(255);
            SitkImage result = thresholder.Execute(fastmarchingOutput);

            SimpleITK.WriteImage(result, outputFilename);
        }
        static void Main(string[] args)
        {
            if (args.Length < 6)
            {
                Console.WriteLine("Missing Parameters ");
                Console.WriteLine("Usage: " + System.AppDomain.CurrentDomain.FriendlyName +
                                  " inputImage outputImage" +
                                  " lowerThreshold upperThreshold seedX seedY [seed2X seed2Y ... ]");
                return;
            }

            string inputFilename  = args[0];
            string outputFilename = args[1];

            double lowerThreshold = double.Parse(args[2], CultureInfo.InvariantCulture);
            double upperThreshold = double.Parse(args[3], CultureInfo.InvariantCulture);

            //
            // Read the image
            //

            SitkImage inputImage = SimpleITK.ReadImage(inputFilename, PixelIDValueEnum.sitkFloat32);

            //
            // Blur using CurvatureFlowImageFilter
            //
            CurvatureFlowImageFilter blurFilter = new sitk.CurvatureFlowImageFilter();

            blurFilter.SetNumberOfIterations(5);
            blurFilter.SetTimeStep(0.125);
            inputImage = blurFilter.Execute(inputImage);


            //
            // Set up ConnectedThresholdImageFilter for segmentation
            //

            ConnectedThresholdImageFilter segmentationFilter = new sitk.ConnectedThresholdImageFilter();

            segmentationFilter.SetLower(lowerThreshold);
            segmentationFilter.SetUpper(upperThreshold);
            segmentationFilter.SetReplaceValue(255);

            for (uint i = 4; i + 1 < args.Length; i += 2)
            {
                VectorUInt32 seed = new VectorUInt32(new uint[] { Convert.ToUInt32(args[i]), Convert.ToUInt32(args[i + 1]), 0 });
                segmentationFilter.AddSeed(seed);
                Console.WriteLine("Adding a seed at: ");
                for (int j = 0; j + 1 < seed.Count; j++)
                {
                    Console.WriteLine(seed[j] + " ");
                }
            }
            SitkImage outImage = segmentationFilter.Execute(inputImage);

            //
            // Write out the resulting file
            //

            SimpleITK.WriteImage(outImage, outputFilename);

            return;
        }