예제 #1
0
        static void Main(string[] args)
        {
            try {
                if (args.Length < 2)
                {
                    Console.WriteLine("Usage: DicomSeriesReader <input_directory> <output_file>");
                    return;
                }

                Console.WriteLine("Reading Dicom directory: " + args[0]);
                ImageSeriesReader reader = new ImageSeriesReader();

                VectorString dicom_names = ImageSeriesReader.GetGDCMSeriesFileNames(args[0]);
                reader.SetFileNames(dicom_names);

                Image image = reader.Execute();

                VectorUInt32 size = image.GetSize();
                Console.WriteLine("Image size: " + size[0] + " " + size[1] + " " + size[2]);

                Console.WriteLine("Writing image: " + args[1]);
                ImageFileWriter writer = new ImageFileWriter();
                writer.SetFileName(args[1]);
                writer.Execute(image);

                if (Environment.GetEnvironmentVariable("SITK_NOSHOW") == null)
                {
                    SimpleITK.Show(image, "Dicom Series");
                }
            } catch (Exception ex) {
                Console.WriteLine("Usage: DicomSeriesReader <input_directory> <output_file>");
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// Initializes the reader asynchronous.
        /// </summary>
        /// <param name="path">The location of the image.</param>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>
        /// A <see cref="Task" /> representing the asynchronous operation.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// path
        /// or
        /// ct
        /// </exception>
        /// <exception cref="AmiException">The ITK image could not be read.</exception>
        public async Task InitAsync(string path, CancellationToken ct)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (ct == null)
            {
                throw new ArgumentNullException(nameof(ct));
            }

            await SemaphoreSlim.WaitAsync();

            try
            {
                Image = await itkUtil.ReadImageAsync(path, ct);

                if (Image == null)
                {
                    throw new AmiException("The ITK image could not be read.");
                }

                size       = Image.GetSize();
                axisImages = new Dictionary <AxisType, Image>();
            }
            finally
            {
                SemaphoreSlim.Release();
            }
        }
예제 #3
0
    public void OnDICOMLoaded(object obj = null)
    {
        DICOM dicom = obj as DICOM;

        if (dicom == null)
        {
            return;
        }
        if (dicom.dimensions != 3)
        {
            return;
        }

        Image volume = dicom.image;

        Debug.Log("Width: " + volume.GetWidth() + ", height: " + volume.GetHeight() + ", depth: " + volume.GetDepth());

        VectorUInt32 position = new VectorUInt32 {
            volume.GetWidth() / 2,
                     volume.GetHeight() / 2,
                     volume.GetDepth() / 2
        };
        // Asumes that the pixel type stored in the image is grayscale int32:
        int value = volume.GetPixelAsInt16(position);

        Debug.Log("Value of center pixel: " + value);
    }
예제 #4
0
        /// <inheritdoc/>
        public Image ResampleImage2D(Image image, int outputSize)
        {
            Ensure.ArgumentNotNull(image, nameof(image));

            var dimension = image.GetDimension();

            if (dimension != 2)
            {
                throw new NotSupportedException($"The dimension ({dimension}) of the provided image is not supported.");
            }

            var inputSize      = image.GetSize();
            var inputSpacing   = image.GetSpacing();
            var inputDirection = image.GetDirection();
            var inputOrigin    = image.GetOrigin();

            double oldw = inputSize[0] * inputSpacing[0];
            double oldh = inputSize[1] * inputSpacing[1];
            double neww, newh = 0;
            double rw = oldw / outputSize;
            double rh = oldh / outputSize;

            if (rw > rh)
            {
                newh = oldh / rw;
                neww = outputSize;
            }
            else
            {
                neww = oldw / rh;
                newh = outputSize;
            }

            var outputSpacing = new VectorDouble()
            {
                inputSpacing[0] * inputSize[0] / neww,
                inputSpacing[1] * inputSize[1] / newh
            };

            var actualSize = new VectorUInt32()
            {
                Convert.ToUInt32(neww),
                Convert.ToUInt32(newh)
            };

            // https://itk.org/ITKExamples/src/Filtering/ImageGrid/ResampleAnImage/Documentation.html
            ResampleImageFilter filter = new ResampleImageFilter();

            filter.SetReferenceImage(image);
            filter.SetSize(actualSize);
            filter.SetOutputSpacing(outputSpacing);
            Image output = filter.Execute(image);

            filter.Dispose();

            return(output);
        }
예제 #5
0
        static void Main(string[] args)
        {
            try {
                // Create an image
                PixelIDValueEnum pixelType = PixelIDValueEnum.sitkUInt8;
                VectorUInt32     imageSize = new VectorUInt32(new uint[] { 128, 128 });
                Image            image     = new Image(imageSize, pixelType);

                // Create a face image
                VectorDouble faceSize   = new VectorDouble(new double[] { 64, 64 });
                VectorDouble faceCenter = new VectorDouble(new double[] { 64, 64 });
                Image        face       = SimpleITK.GaussianSource(pixelType, imageSize, faceSize, faceCenter);

                // Create eye images
                VectorDouble eyeSize    = new VectorDouble(new double[] { 5, 5 });
                VectorDouble eye1Center = new VectorDouble(new double[] { 48, 48 });
                VectorDouble eye2Center = new VectorDouble(new double[] { 80, 48 });
                Image        eye1       = SimpleITK.GaussianSource(pixelType, imageSize, eyeSize, eye1Center, 150);
                Image        eye2       = SimpleITK.GaussianSource(pixelType, imageSize, eyeSize, eye2Center, 150);

                // Apply the eyes to the face
                face = SimpleITK.Subtract(face, eye1);
                face = SimpleITK.Subtract(face, eye2);
                face = SimpleITK.BinaryThreshold(face, 200, 255, 255);


                // Create the mouth
                VectorDouble mouthRadii  = new VectorDouble(new double[] { 30, 20 });
                VectorDouble mouthCenter = new VectorDouble(new double[] { 64, 76 });
                Image        mouth       = SimpleITK.GaussianSource(pixelType, imageSize, mouthRadii, mouthCenter);
                mouth = SimpleITK.BinaryThreshold(mouth, 200, 255, 255);
                mouth = SimpleITK.Subtract(255, mouth);

                // Paste the mouth onto the face
                VectorUInt32 mouthSize = new VectorUInt32(new uint[] { 64, 18 });
                VectorInt32  mouthLoc  = new VectorInt32(new int[] { 32, 76 });
                face = SimpleITK.Paste(face, mouth, mouthSize, mouthLoc, mouthLoc);

                // Apply the face to the original image
                image = SimpleITK.Add(image, face);

                // Display the results
                if (Environment.GetEnvironmentVariable("SITK_NOSHOW") == null)
                {
                    SimpleITK.Show(image, "Hello World: CSharp", true);
                }
            } catch (Exception ex) {
                Console.WriteLine(ex);
            }
        }
예제 #6
0
        public Bitmap konwertujObraz(Image obraz1, int przekroj = 0)
        {
            uint r = obraz1.GetWidth();
            //  VectorUInt32 w = new VectorUInt32(new[] { r, 512, 4 + 1 });

            VectorInt32 start = new VectorInt32(new[] { 0, 0, 0 });
            VectorInt32 size1 = new VectorInt32(new[] { 512, 512, 1 });

            obraz1 = WybierzPrzekroj(obraz1, przekroj);
            IntensityWindowingImageFilter normalize = new IntensityWindowingImageFilter();

            normalize.SetOutputMinimum(0);
            normalize.SetOutputMaximum(255);
            obraz1 = normalize.Execute(obraz1);

            PixelIDValueEnum u = PixelIDValueEnum.sitkFloat32;
            int          len   = 1;
            Image        input = SimpleITK.Cast(obraz1, u);
            VectorUInt32 size  = input.GetSize();

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

            float[] bufferAsArray = new float[len];
            float[,] newData = new float[size[0], size[1]];
            Marshal.Copy(buffer, bufferAsArray, 0, len);
            obrazBitmap = new Bitmap(Convert.ToInt32(size[0]), Convert.ToInt32(size[1]));
            for (int j = 0; j < size[1]; j++)
            {
                for (int i = 0; i < size[0]; i++)
                {
                    var bur = bufferAsArray[j * size[1] + i];
                    System.Drawing.Color newColor = System.Drawing.Color.FromArgb((int)bur, 0, 0, 0);
                    obrazBitmap.SetPixel(j, i, newColor);
                }
            }
            Color s = obrazBitmap.GetPixel(34, 56);

            return(obrazBitmap);
        }
예제 #7
0
        /// <inheritdoc/>
        public Image ResampleImage3D(Image image, int outputSize)
        {
            Ensure.ArgumentNotNull(image, nameof(image));

            var dimension = image.GetDimension();

            if (dimension != 3)
            {
                throw new NotSupportedException($"The dimension ({dimension}) of the provided image is not supported.");
            }

            var outputSizeConverted = Convert.ToUInt32(outputSize);
            var inputSize           = image.GetSize();
            var inputSpacing        = image.GetSpacing();

            var desiredSize = new VectorUInt32()
            {
                outputSizeConverted,
                outputSizeConverted,
                outputSizeConverted
            };

            var outputSpacing = new VectorDouble()
            {
                inputSpacing[0] * inputSize[0] / desiredSize[0],
                inputSpacing[1] * inputSize[1] / desiredSize[1],
                inputSpacing[2] * inputSize[2] / desiredSize[2]
            };

            // https://itk.org/Wiki/ITK/Examples/ImageProcessing/ResampleImageFilter
            ResampleImageFilter filter = new ResampleImageFilter();

            filter.SetReferenceImage(image);
            filter.SetTransform(new ScaleTransform(image.GetDimension()));
            filter.SetInterpolator(InterpolatorEnum.sitkLinear);
            filter.SetSize(desiredSize);
            filter.SetOutputSpacing(outputSpacing);
            Image output = filter.Execute(image);

            filter.Dispose();

            return(output);
        }
예제 #8
0
        /// <summary>
        /// Resamples the three-dimensional ITK image to the desired size.
        /// </summary>
        /// <param name="image">The three-dimensional ITK image.</param>
        /// <param name="desiredSize">The desired size.</param>
        /// <returns>
        /// The resampled three-dimensional ITK image.
        /// </returns>
        /// <exception cref="ArgumentNullException">image</exception>
        /// <exception cref="NotSupportedException">The dimension ({dimension}) of the provided image is not supported.</exception>
        public Image ResampleImage3D(Image image, uint desiredSize)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            var dimension = image.GetDimension();

            if (dimension != 3)
            {
                throw new NotSupportedException($"The dimension ({dimension}) of the provided image is not supported.");
            }

            var inputSize    = image.GetSize();
            var inputSpacing = image.GetSpacing();

            var outputSize = new VectorUInt32()
            {
                desiredSize,
                desiredSize,
                desiredSize
            };

            var outputSpacing = new VectorDouble()
            {
                inputSpacing[0] * inputSize[0] / outputSize[0],
                inputSpacing[1] * inputSize[1] / outputSize[1],
                inputSpacing[2] * inputSize[2] / outputSize[2]
            };

            // https://itk.org/Wiki/ITK/Examples/ImageProcessing/ResampleImageFilter
            var filter = new ResampleImageFilter();

            filter.SetReferenceImage(image);
            filter.SetTransform(new ScaleTransform(image.GetDimension()));
            filter.SetInterpolator(InterpolatorEnum.sitkLinear);
            filter.SetSize(outputSize);
            filter.SetOutputSpacing(outputSpacing);
            return(filter.Execute(image));
        }
예제 #9
0
        /// <inheritdoc/>
        public async Task InitAsync(string path, CancellationToken ct)
        {
            Ensure.ArgumentNotNull(path, nameof(path));
            Ensure.ArgumentNotNull(ct, nameof(ct));

            await SemaphoreSlim.WaitAsync();

            try
            {
                Image = await itkUtil.ReadImageAsync(path, ct);

                if (Image == null)
                {
                    throw new AmiException("The ITK image could not be read.");
                }

                size = Image.GetSize();
            }
            finally
            {
                SemaphoreSlim.Release();
            }
        }
예제 #10
0
        static void Main(string[] args)
        {
            try {
                if (args.Length < 1)
                {
                    Console.WriteLine("Usage: ImageIOSelection image_input_file");
                    return;
                }

                // Find out which image IOs are supported
                ImageFileReader         reader    = new ImageFileReader();
                itk.simple.VectorString image_ios = reader.GetRegisteredImageIOs();
                Console.Write("The supported image IOs are: ");
                for (int i = 0; i < image_ios.Count; i++)
                {
                    Console.Write(image_ios[i] + " ");
                }
                Console.WriteLine("\n--------------------");

                // Another option is to just print the reader and see which
                // IOs are supported
                Console.WriteLine(reader.ToString());
                Console.WriteLine("--------------------");

                // Force the use of a specific IO. If the IO doesn't support
                // reading the image type it will throw an exception.
                reader.SetImageIO("PNGImageIO");
                reader.SetFileName(args[0]);
                Image image = reader.Execute();
                Console.WriteLine("Read image: " + args[0]);

                VectorUInt32 size = image.GetSize();
                Console.WriteLine("Image size: " + size[0] + " " + size[1]);
            } catch (Exception ex) {
                Console.WriteLine("Read failed: " + ex);
            }
        }
        public static int[] fGetDatasetLength()
        {
            Class.manageImg managerView = HttpContext.Current.Session["managerView"] as Class.manageImg;
            String          sPath       = managerView.sCurrentImageFolder[0];

            String[] sFilenames;

            if (sPath == null)
            {
                throw new ArgumentException("path variable in manageImg is not specified!");
            }
            else
            {
                sFilenames = (System.IO.Directory.EnumerateFiles(sPath, "*.*", SearchOption.AllDirectories).Where(s => Constant.lsExtensions.Any(e => s.EndsWith(e)))).ToArray();
                int[] iSize = new int[] { 0, 0, 0 };
                // get dataset length and set hiddenfield
                itk.simple.Image itkImage   = SimpleITK.ReadImage(sFilenames[0]); // Es wird nur das erste Listenelement ausgelesen?
                VectorUInt32     UInt32Size = itkImage.GetSize();
                iSize[0] = unchecked ((int)UInt32Size[0]);
                iSize[1] = unchecked ((int)UInt32Size[1]);
                iSize[2] = unchecked ((int)UInt32Size[2]);
                return(iSize);
            }
        }
예제 #12
0
        static void Main(string[] args)
        {
            try {
                if (args.Length < 1) {
                    Console.WriteLine("Usage: RTKFirstReconstruction <output>");
                    return;
                }

                // Defines the RTK geometry object
                ThreeDCircularProjectionGeometry geometry = new ThreeDCircularProjectionGeometry();
                uint numberOfProjections = 360;
                float firstAngle = 0;
                float angularArc = 360;
                float sid = 600; // source to isocenter distance in mm
                float sdd = 1200; // source to detector distance in mm
                float isox = 0; // X coordinate on the projection image of isocenter
                float isoy = 0; // Y coordinate on the projection image of isocenter
                for (int x = 0; x < numberOfProjections; x++)
                  {
                  float angle = firstAngle + x * angularArc / numberOfProjections;
                  geometry.AddProjection(sid, sdd, angle, isox, isoy);
                  }
                ConstantImageSource constantImageSource = new ConstantImageSource();
                VectorDouble origin = new VectorDouble(3);
                origin.Add(-127.0);
                origin.Add(-127.0);
                origin.Add(-127.0);
                VectorUInt32 sizeOutput = new VectorUInt32(3);
                sizeOutput.Add(256);
                sizeOutput.Add(256);
                sizeOutput.Add(numberOfProjections);
                VectorDouble spacing = new VectorDouble(3);
                spacing.Add(1.0);
                spacing.Add(1.0);
                spacing.Add(1.0);

                constantImageSource.SetOrigin(origin);
                constantImageSource.SetSpacing(spacing);
                constantImageSource.SetSize(sizeOutput);
                constantImageSource.SetConstant(0.0);
                Image source = constantImageSource.Execute();

                RayEllipsoidIntersectionImageFilter rei = new RayEllipsoidIntersectionImageFilter();
                VectorDouble semiprincipalaxis = new VectorDouble(3);
                semiprincipalaxis.Add(50.0);
                semiprincipalaxis.Add(50.0);
                semiprincipalaxis.Add(50.0);

                VectorDouble center = new VectorDouble(3);
                center.Add(0.0);
                center.Add(0.0);
                center.Add(0.0);
                // Set GrayScale value, axes, center...
                rei.SetDensity(20);
                rei.SetAngle(0);
                rei.SetCenter(center);
                rei.SetAxis(semiprincipalaxis);
                rei.SetGeometry(geometry);
                Image reiImage = rei.Execute(source);

                // Create reconstructed image
                ConstantImageSource constantImageSource2 = new ConstantImageSource();
                VectorUInt32 sizeOutput2 = new VectorUInt32(3);
                sizeOutput2.Add(256);
                sizeOutput2.Add(256);
                sizeOutput2.Add(256);
                constantImageSource2.SetOrigin(origin);
                constantImageSource2.SetSpacing(spacing);
                constantImageSource2.SetSize(sizeOutput2);
                constantImageSource2.SetConstant(0.0);
                Image source2 = constantImageSource2.Execute();

                Console.WriteLine("Performing reconstruction");
                FDKConeBeamReconstructionFilter feldkamp = new FDKConeBeamReconstructionFilter();
                feldkamp.SetGeometry(geometry);
                feldkamp.SetTruncationCorrection(0.0);
                feldkamp.SetHannCutFrequency(0.0);
                Image image = feldkamp.Execute(source2, reiImage);

                ImageFileWriter writer = new ImageFileWriter();
                writer.SetFileName(args[0]);
                writer.Execute(image);

            } catch (Exception ex) {
                Console.WriteLine(ex);
            }
        }
예제 #13
0
        /// <summary>
        /// Resamples the two-dimensional ITK image to the desired size.
        /// </summary>
        /// <param name="image">The two-dimensional ITK image.</param>
        /// <param name="desiredSize">The desired size.</param>
        /// <returns>
        /// The resampled two-dimensional ITK image.
        /// </returns>
        /// <exception cref="ArgumentNullException">image</exception>
        /// <exception cref="NotSupportedException">The dimension ({dimension}) of the provided image is not supported.</exception>
        public Image ResampleImage2D(Image image, uint desiredSize)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            var dimension = image.GetDimension();

            if (dimension != 2)
            {
                throw new NotSupportedException($"The dimension ({dimension}) of the provided image is not supported.");
            }

            var inputSize      = image.GetSize();
            var inputSpacing   = image.GetSpacing();
            var inputDirection = image.GetDirection();
            var inputOrigin    = image.GetOrigin();

            var outputSize = new VectorUInt32()
            {
                desiredSize,
                desiredSize
            };

            double oldw = inputSize[0] * inputSpacing[0];
            double oldh = inputSize[1] * inputSpacing[1];
            double neww, newh = 0;
            double rw = oldw / desiredSize;
            double rh = oldh / desiredSize;

            if (rw > rh)
            {
                newh = oldh / rw;
                neww = desiredSize;
            }
            else
            {
                neww = oldw / rh;
                newh = desiredSize;
            }

            var outputSpacing = new VectorDouble()
            {
                inputSpacing[0] * inputSize[0] / neww,
                inputSpacing[1] * inputSize[1] / newh
            };

            var actualSize = new VectorUInt32()
            {
                (uint)neww,
                (uint)newh
            };

            // https://itk.org/ITKExamples/src/Filtering/ImageGrid/ResampleAnImage/Documentation.html
            var resampleFilter = new ResampleImageFilter();

            resampleFilter.SetReferenceImage(image);
            resampleFilter.SetSize(actualSize);
            resampleFilter.SetOutputSpacing(outputSpacing);

            var outputImage = resampleFilter.Execute(image);

            return(outputImage);
        }
예제 #14
0
        /// <summary>Main entry point.</summary>
        public static int Main(string[] args)
        {
            int success = ExitSuccess;
            try {
                Image image = new Image(100, 100, PixelId.sitkInt8);
                Image image2 = new Image(100, 100, PixelId.sitkInt8);

                image += 10;
                image -= 1;
                CheckHash(image, "1cda91cc1bf474a25d6365f7fa7ef1fc75b3c7c9", ref success);
                image *= 2;
                image /= 3;
                CheckHash(image, "856f68940ff670209aa9d60f38fc4cca1880f647", ref success);

                // image with just one 7 reset zero
                image *= 0;
                VectorUInt32 idx = new VectorUInt32();
                idx.Add(0);
                idx.Add(0);
                image.SetPixelAsInt8( idx, 7 );

                // Unary operators
                CheckHash(-image, "fe7e0c8ac8252189cf5766a352397bc62dd42e4d", ref success);
                CheckHash(+image, "6cccaa2d5c958e79ebd5ca4a0b00bee747797c8d", ref success);
                CheckHash(!image, "f4695dbf5bc9ea2796b2e4f360ea4b5ecbf70c37", ref success);
                CheckHash(~image, "746470f03126f653cc23265e0b1c1fe16a952745", ref success);
                CheckHash(image, "6cccaa2d5c958e79ebd5ca4a0b00bee747797c8d", ref success);

                // Comparison operators
                CheckHash( image < 7, "f4695dbf5bc9ea2796b2e4f360ea4b5ecbf70c37", ref success);
                CheckHash( image > 7, "f907b7bf318b79fd6b9da589646f8b1dac77d0c8", ref success);
                CheckHash( image <= 7, "cef864600fc947062ac359fe9a7cc049c7273b8e", ref success);
                CheckHash( image >= 7, "52f583bfeb07a6c4c5a26b28f8ae180bf8e0079b", ref success);

                CheckHash( image < image2, "f907b7bf318b79fd6b9da589646f8b1dac77d0c8", ref success);
                CheckHash( image > image2, "52f583bfeb07a6c4c5a26b28f8ae180bf8e0079b", ref success);
                CheckHash( image <= image2, "f4695dbf5bc9ea2796b2e4f360ea4b5ecbf70c37", ref success);
                CheckHash( image >= image2, "cef864600fc947062ac359fe9a7cc049c7273b8e", ref success);

                // Binary bitwise operators
                image &= 5;;
                image |= 7;
                image ^= 8;
                CheckHash(image, "0c26e6610c876b83cf681688eb8e80b952a394ce", ref success);

                image &= image;
                image ^= image;
                image |= image;
                CheckHash( image, "f907b7bf318b79fd6b9da589646f8b1dac77d0c8", ref success);  // just zeros

                // image of 1s
                image *= 0;
                image += 1;

                image += image;
                image -= image;
                image *= image;
                image /= image;
                CheckHash(image, "287046eafd10b9984977f6888ea50ea50fe846b5", ref success);

            } catch (Exception ex) {
                success = ExitFailure;
                Console.WriteLine(ex);
            }
            return success;
        }
        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;
        }
예제 #16
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);
        }
예제 #17
0
        static void Main(string[] args)
        {
            try {
                if (args.Length < 2)
                {
                    Console.WriteLine("Usage: N4BiasFieldCorrection inputImage outputImage"
                                      + " [shrinkFactor] [maskImage] [numberOfIterations]"
                                      + " [numberOfFittingLevels]\n");

                    return;
                }
                // Read input image
                Image inputImage = sitk.ReadImage(args[0], PixelIDValueEnum.sitkFloat32);
                Image image      = inputImage;


                Image maskImage;
                if (args.Length > 3)
                {
                    maskImage = sitk.ReadImage(args[3], PixelIDValueEnum.sitkUInt8);
                }
                else
                {
                    maskImage = sitk.OtsuThreshold(image, 0, 1, 200);
                }

                if (args.Length > 2)
                {
                    uint   s       = UInt32.Parse(args[2]);
                    uint[] s_array = new uint[image.GetDimension()];
                    for (uint i = 0; i < image.GetDimension(); i++)
                    {
                        s_array[i] = s;
                    }
                    VectorUInt32 shrink = new VectorUInt32(s_array);
                    image     = sitk.Shrink(inputImage, shrink);
                    maskImage = sitk.Shrink(maskImage, shrink);
                }

                N4BiasFieldCorrectionImageFilter corrector
                    = new N4BiasFieldCorrectionImageFilter();

                uint numFittingLevels = 4;

                if (args.Length > 5)
                {
                    numFittingLevels = UInt32.Parse(args[5]);
                }

                if (args.Length > 4)
                {
                    uint   it       = UInt32.Parse(args[4]);
                    uint[] it_array = new uint[numFittingLevels];
                    for (uint i = 0; i < numFittingLevels; i++)
                    {
                        it_array[i] = it;
                    }
                    VectorUInt32 iterations = new VectorUInt32(it_array);
                    corrector.SetMaximumNumberOfIterations(iterations);
                }

                Image corrected_image = corrector.Execute(image, maskImage);

                Image log_bias_field = corrector.GetLogBiasFieldAsImage(inputImage);

                Image bias_field = sitk.Divide(inputImage, sitk.Exp(log_bias_field));

                sitk.WriteImage(corrected_image, args[1]);

                if (Environment.GetEnvironmentVariable("SITK_NOSHOW") == null)
                {
                    SimpleITK.Show(corrected_image, "N4 Corrected");
                }
            } catch (Exception ex) {
                Console.WriteLine(ex);
            }
        }
예제 #18
0
        static void Main(string[] args)
        {
            try {
                if (args.Length < 1)
                {
                    Console.WriteLine("Usage: RTKFirstReconstruction <output>");
                    return;
                }

                // Defines the RTK geometry object
                ThreeDCircularProjectionGeometry geometry = new ThreeDCircularProjectionGeometry();
                uint  numberOfProjections = 360;
                float firstAngle          = 0;
                float angularArc          = 360;
                float sid  = 600;  // source to isocenter distance in mm
                float sdd  = 1200; // source to detector distance in mm
                float isox = 0;    // X coordinate on the projection image of isocenter
                float isoy = 0;    // Y coordinate on the projection image of isocenter
                for (int x = 0; x < numberOfProjections; x++)
                {
                    float angle = firstAngle + x * angularArc / numberOfProjections;
                    geometry.AddProjection(sid, sdd, angle, isox, isoy);
                }
                ConstantImageSource constantImageSource = new ConstantImageSource();
                VectorDouble        origin = new VectorDouble(3);
                origin.Add(-127.0);
                origin.Add(-127.0);
                origin.Add(-127.0);
                VectorUInt32 sizeOutput = new VectorUInt32(3);
                sizeOutput.Add(256);
                sizeOutput.Add(256);
                sizeOutput.Add(numberOfProjections);
                VectorDouble spacing = new VectorDouble(3);
                spacing.Add(1.0);
                spacing.Add(1.0);
                spacing.Add(1.0);

                constantImageSource.SetOrigin(origin);
                constantImageSource.SetSpacing(spacing);
                constantImageSource.SetSize(sizeOutput);
                constantImageSource.SetConstant(0.0);
                Image source = constantImageSource.Execute();

                RayEllipsoidIntersectionImageFilter rei = new RayEllipsoidIntersectionImageFilter();
                VectorDouble semiprincipalaxis          = new VectorDouble(3);
                semiprincipalaxis.Add(50.0);
                semiprincipalaxis.Add(50.0);
                semiprincipalaxis.Add(50.0);

                VectorDouble center = new VectorDouble(3);
                center.Add(0.0);
                center.Add(0.0);
                center.Add(0.0);
                // Set GrayScale value, axes, center...
                rei.SetDensity(20);
                rei.SetAngle(0);
                rei.SetCenter(center);
                rei.SetAxis(semiprincipalaxis);
                rei.SetGeometry(geometry);
                Image reiImage = rei.Execute(source);


                // Create reconstructed image
                ConstantImageSource constantImageSource2 = new ConstantImageSource();
                VectorUInt32        sizeOutput2          = new VectorUInt32(3);
                sizeOutput2.Add(256);
                sizeOutput2.Add(256);
                sizeOutput2.Add(256);
                constantImageSource2.SetOrigin(origin);
                constantImageSource2.SetSpacing(spacing);
                constantImageSource2.SetSize(sizeOutput2);
                constantImageSource2.SetConstant(0.0);
                Image source2 = constantImageSource2.Execute();

                Console.WriteLine("Performing reconstruction");
                FDKConeBeamReconstructionFilter feldkamp = new FDKConeBeamReconstructionFilter();
                feldkamp.SetGeometry(geometry);
                feldkamp.SetTruncationCorrection(0.0);
                feldkamp.SetHannCutFrequency(0.0);
                Image image = feldkamp.Execute(source2, reiImage);

                ImageFileWriter writer = new ImageFileWriter();
                writer.SetFileName(args[0]);
                writer.Execute(image);
            } catch (Exception ex) {
                Console.WriteLine(ex);
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            // image ID, brightness and contrast value
            Int32  iID, iBVal, iRot, iNoFiles;
            Double dCVal;
            String sPath;

            // response type
            context.Response.ContentType = "image/png";

            // get and convert image parameters
            if (context.Request.QueryString["NqC3ke"] != null)  // ID
            {
                iID = Convert.ToInt32(context.Request.QueryString["NqC3ke"]);
            }
            else
            {
                throw new ArgumentException("No image id specified");
            }

            if (context.Request.QueryString["tXt9X3"] != null)  // brightness
            {
                iBVal = Convert.ToInt32(context.Request.QueryString["tXt9X3"]);
            }
            else
            {
                throw new ArgumentException("No image brightness specified");
            }

            if (context.Request.QueryString["XwjRGm"] != null)  // contrast
            {
                dCVal = Convert.ToDouble(context.Request.QueryString["XwjRGm"]);
            }
            else
            {
                throw new ArgumentException("No image contrast specified");
            }

            if (context.Request.QueryString["WkYTCe"] != null)  // path
            {
                string obscuredPath   = Convert.ToString(context.Request.QueryString["WkYTCe"]);
                string unobscuredPath = "";

                // old obfuscation
                //for (int z = 0; z < obscuredPath.Length; z++)
                //{
                //    int add = Constant.ceasarOdd;

                //    if (z % 2 == 0)
                //    {
                //        add =  Constant.ceasarEven;
                //    }
                //    char c = (char)(obscuredPath[z] - add);
                //    unobscuredPath += c.ToString();

                //}

                // new obfuscation
                string allowedChars = Constant.allowedCharacters;

                for (int p = 0; p < obscuredPath.Length; p++)
                {
                    for (int c = 0; c < allowedChars.Length; c++)
                    {
                        if (obscuredPath[p] == allowedChars[c])
                        { // character is allowed
                            int add = Constant.ceasarOdd;
                            if (p % 2 == 0)
                            {
                                add = Constant.ceasarEven;
                            }

                            // remove unneccessary loops
                            add = add % (allowedChars.Length - 1);

                            int shift = c - add;

                            if (shift > (allowedChars.Length - 1))
                            {
                                shift = shift - (allowedChars.Length - 1);
                            }
                            else if ((shift) < 0)
                            {
                                shift = shift + (allowedChars.Length - 1);
                            }

                            char character = allowedChars[shift];


                            unobscuredPath += character.ToString();

                            break;
                        }
                    }
                }



                //Debug.Print("deobfuscation\t\t" + obscuredPath + "  ->  " + unobscuredPath);

                sPath = unobscuredPath;
            }
            else
            {
                sPath = "";
            }

            if (context.Request.QueryString["Hsfke2"] != null)  // rotate
            {
                iRot = Convert.ToInt32(context.Request.QueryString["Hsfke2"]);
            }
            else
            {
                iRot = 0;
            }

            if (context.Request.QueryString["yAR8st"] != null)  // length
            {
                iNoFiles = Convert.ToInt32(context.Request.QueryString["yAR8st"]);
            }
            else
            {
                iNoFiles = 1;
            }

            // load image in byte array "bmVal"
            //var bOld = false;
            byte[] bmVal;
            int    iWidth;
            int    iHeight;
            int    iDepth;

            itk.simple.Image itkImage;

            if (!File.Exists(sPath))
            {
                // file was not found
            }

            try
            {
                itkImage = SimpleITK.ReadImage(sPath, PixelIDValueEnum.sitkFloat32);
            }
            catch (System.StackOverflowException)
            {
                itk.simple.ImageFileReader reader = new itk.simple.ImageFileReader();
                reader.SetFileName(sPath);
                itkImage = reader.Execute();
            }

            // get image direction
            var iDir = itkImage.GetDirection();

            // get spacing
            VectorDouble dSpacing = itkImage.GetSpacing();

            // get size and number of dimension
            VectorUInt32 iSize = itkImage.GetSize();
            int          len   = 1;

            for (int iDim = 0; iDim < itkImage.GetDimension(); iDim++)
            {
                len *= (int)iSize[iDim];
            }
            iWidth  = unchecked ((int)iSize[0]);
            iHeight = unchecked ((int)iSize[1]);
            iDepth  = unchecked ((int)iSize[2]);

            // convert mm->dpi
            float fResolutionX = System.Convert.ToSingle(System.Convert.ToDouble(iWidth) * 25.4 / dSpacing[0]);
            float fResolutionY = System.Convert.ToSingle(System.Convert.ToDouble(iHeight) * 25.4 / dSpacing[1]);

            // 2D image size
            int iLength = iWidth * iHeight;

            // copy buffer to new array
            IntPtr ipBuffer = itkImage.GetBufferAsFloat();

            float[] fArray = new float[iLength];

            // no negative indices
            if (iID < 0)
            {
                iID = 0;
            }

            // multiple DICOM files
            int iOffset = 0;

            if (iNoFiles > 1)
            {
                if (iID >= (iNoFiles - 1))
                {
                    iID = iNoFiles - 1;
                }
                iOffset = 0;
            }

            else if (iNoFiles == 1)
            {
                // one DICOM file
                if (iDepth == 1)
                {
                    iID     = 1;
                    iOffset = 0;
                }

                // one 3D MHD file
                else if (iDepth > 1)
                {
                    if (iID > (iDepth - 1))
                    {
                        iID = iDepth - 1;
                    }
                    iOffset = (iID - 1) * iLength;
                }
            }

            // new pointer to data (due to offset)
            Marshal.Copy(new IntPtr(ipBuffer.ToInt64() + sizeof(float) * iOffset), fArray, 0, iLength);

            // convert floating point to 8 bit integer values - range:0 - 255
            float fMax = fArray.Max();
            float fMin = fArray.Min();

            bmVal = new byte[iWidth * iHeight];
            for (int iI = 0; iI < iLength; iI++)
            {
                var tmp = (float)(((fArray[iI] - fMin) / (fMax - fMin) * 255) + iBVal) * (float)dCVal;
                if (tmp > 255)
                {
                    tmp = 255;
                }
                if (tmp < 0)
                {
                    tmp = 0;
                }
                bmVal[iI] = (byte)tmp;
            }
            Bitmap bmOutput = fCreateBitmap(bmVal, new int[] { iWidth, iHeight }, new float[] { fResolutionX, fResolutionY });

            // rotate image and flip in X direction due to different image orientation convention

            // corrects *.mhd orientation

            List <String> lsExtensions = new List <String> {
                ".mhd", ".MHD"
            };

            foreach (var ext in lsExtensions)
            {
                if (sPath.EndsWith(ext))
                {                                                // *.mhd files have a different orientation (compared to *.ima)
                    bmOutput.RotateFlip(RotateFlipType.Rotate90FlipNone);
                }
            }

            switch (iRot)
            {
            case 0:
                bmOutput.RotateFlip(RotateFlipType.RotateNoneFlipX);
                break;

            case 90:
                bmOutput.RotateFlip(RotateFlipType.Rotate90FlipX);
                break;

            case 180:
                bmOutput.RotateFlip(RotateFlipType.Rotate180FlipX);
                break;

            case 270:
                bmOutput.RotateFlip(RotateFlipType.Rotate270FlipX);
                break;

            default:
                break;
            }

            // save new image to response stream
            bmOutput.Save(context.Response.OutputStream, ImageFormat.Png);
            bmOutput.Dispose();
        }
예제 #20
0
        /// <summary>Main entry point.</summary>
        public static int Main(string[] args)
        {
            int success = ExitSuccess;

            try {
                Image image  = new Image(100, 100, PixelId.sitkInt8);
                Image image2 = new Image(100, 100, PixelId.sitkInt8);


                image += 10;
                image -= 1;
                CheckHash(image, "1cda91cc1bf474a25d6365f7fa7ef1fc75b3c7c9", ref success);
                image *= 2;
                image /= 3;
                CheckHash(image, "856f68940ff670209aa9d60f38fc4cca1880f647", ref success);


                // image with just one 7 reset zero
                image *= 0;
                VectorUInt32 idx = new VectorUInt32();
                idx.Add(0);
                idx.Add(0);
                image.SetPixelAsInt8(idx, 7);

                // Unary operators
                CheckHash(-image, "fe7e0c8ac8252189cf5766a352397bc62dd42e4d", ref success);
                CheckHash(+image, "6cccaa2d5c958e79ebd5ca4a0b00bee747797c8d", ref success);
                CheckHash(!image, "f4695dbf5bc9ea2796b2e4f360ea4b5ecbf70c37", ref success);
                CheckHash(~image, "746470f03126f653cc23265e0b1c1fe16a952745", ref success);
                CheckHash(image, "6cccaa2d5c958e79ebd5ca4a0b00bee747797c8d", ref success);


                // Comparison operators
                CheckHash(image < 7, "f4695dbf5bc9ea2796b2e4f360ea4b5ecbf70c37", ref success);
                CheckHash(image > 7, "f907b7bf318b79fd6b9da589646f8b1dac77d0c8", ref success);
                CheckHash(image <= 7, "cef864600fc947062ac359fe9a7cc049c7273b8e", ref success);
                CheckHash(image >= 7, "52f583bfeb07a6c4c5a26b28f8ae180bf8e0079b", ref success);

                CheckHash(image < image2, "f907b7bf318b79fd6b9da589646f8b1dac77d0c8", ref success);
                CheckHash(image > image2, "52f583bfeb07a6c4c5a26b28f8ae180bf8e0079b", ref success);
                CheckHash(image <= image2, "f4695dbf5bc9ea2796b2e4f360ea4b5ecbf70c37", ref success);
                CheckHash(image >= image2, "cef864600fc947062ac359fe9a7cc049c7273b8e", ref success);

                // Binary bitwise operators
                image &= 5;;
                image |= 7;
                image ^= 8;
                CheckHash(image, "0c26e6610c876b83cf681688eb8e80b952a394ce", ref success);

                image &= image;
                image ^= image;
                image |= image;
                CheckHash(image, "f907b7bf318b79fd6b9da589646f8b1dac77d0c8", ref success);   // just zeros


                // image of 1s
                image *= 0;
                image += 1;

                image += image;
                image -= image;
                image *= image;
                image /= image;
                CheckHash(image, "287046eafd10b9984977f6888ea50ea50fe846b5", ref success);
            } catch (Exception ex) {
                success = ExitFailure;
                Console.WriteLine(ex);
            }
            return(success);
        }
예제 #21
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);
        }
예제 #22
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: SimpleGaussian <input>");
                return;
            }

            // Read input image
            itk.simple.Image input = SimpleITK.ReadImage(args[0]);

            // Cast to 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();

            // Note: C# also has a GetConstBufferAs... methods which do not
            // implicitly call MakeUnique.

            // 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);
        }
        public static string getListOfPackageImage(int index)

        {
            Class.manageImg managerView = HttpContext.Current.Session["managerView"] as Class.manageImg;
            managerView.currentPageIndex = index;
            HttpContext.Current.Session["managerView"] = managerView;

            ViewImage_ that = HttpContext.Current.Session["viewImage"] as ViewImage_;

            that.updateReference(index);

            // set default values
            managerView.allImages[index][0].getUnlabelled = new int[] { -1, -1 };
            managerView.allImages[index][0].getPercentage = "-";


            if (managerView.tc.ActiveLearning) // when active learning is enabled, check if threshold is reached
            {
                if (DataAccess.DataAccessTestCase.checkThreshold(managerView))
                {
                    return("alert('Active learning procedure has been executed, page index will be reset');  setTimeout(function(){ Reset=true; }, 3000);");
                }
            }


            if (index >= 0 && index <= managerView.iNGroups)
            {
                managerView.sCurrentImageFolder = new List <String>(managerView.allImages[index].Count);
                for (var i = 0; i < managerView.allImages[index].Count; i++)
                {
                    managerView.sCurrentImageFolder.Add(null);
                    managerView.sCurrentImageFolder[i] = managerView.tc.dbPath + "\\" + managerView.allImages[index][i].Path.Replace('/', '\\'); //- Martin
                }


                // get the labelscales
                for (int i = 0; i < managerView.allImages[index].Count; i++)
                {
                    if (managerView.tc.DiskreteScale)
                    {
                        managerView.allImages[index][i].LableDiscrete = DataAccessTestCase.GetDiscreteLabel(managerView.IDUser, managerView.allImages[index][i].IdGroupImage);//pcw
                    }
                    else
                    {
                        managerView.allImages[index][i].LableContinuous = DataAccessTestCase.GetLableContinuous(managerView.allImages[index][i].IdGroupImage, managerView.IDUser, managerView.allImages[index][i].TypeScaleContinuous);//pcw
                    }
                }



                List <String> sPath = managerView.sCurrentImageFolder;
                if (sPath == null)
                {
                    throw new ArgumentException("path variable in manageImg is not specified!");
                }
                else
                {
                    // get paths and dimension of every individual image
                    for (int i = 0; i < managerView.allImages[index].Count; i++)
                    {
                        managerView.allImages[index][i].imagePaths = (System.IO.Directory.EnumerateFiles(sPath[i], "*.*", SearchOption.AllDirectories).Where(s => Constant.lsExtensions.Any(e => s.EndsWith(e)))).ToArray();
                        Array.Sort(managerView.allImages[index][i].imagePaths);
                        int[]            iSize    = new int[] { 0, 0, 0 };
                        string           pfad     = managerView.allImages[index][i].imagePaths[0];
                        itk.simple.Image itkImage = SimpleITK.ReadImage(pfad);              // bei DICOM werden nur die Dimensionen des ersten Bildes ausgelesen, diese sind bei den anderen Schichten identisch

                        VectorUInt32 UInt32Size = itkImage.GetSize();
                        iSize[0] = unchecked ((int)UInt32Size[0]);
                        iSize[1] = unchecked ((int)UInt32Size[1]);

                        if (managerView.allImages[index][i].imagePaths.Length > 1)// for DICOM files
                        {
                            iSize[2] = managerView.allImages[index][i].imagePaths.Length;
                        }
                        else if (managerView.allImages[index][i].imagePaths.Length == 1)//
                        {
                            iSize[2] = unchecked ((int)UInt32Size[2]);
                            iSize[2]--;
                        }
                        managerView.allImages[index][i].imageDimensions = iSize;
                    }
                }



                // get index of the next/previous page with not completely labelled images
                try {
                    managerView.allImages[index][0].getNumOfPages = managerView.allImages.Count();
                    managerView.allImages[index][0].getUnlabelled = getUnlabelled(index);
                    managerView.allImages[index][0].getPercentage = getCurrPercentage();
                }catch (ArgumentOutOfRangeException ex) {
                    return("alert('An error occurred while trying to load the image package, please contact the administrator');");
                }

                //Obfuscate image paths

                for (int c = 0; c < managerView.allImages[index].Count; c++)
                {
                    for (int z = 0; z < managerView.allImages[index][c].imagePaths.Length; z++)
                    {
                        managerView.allImages[index][c].imagePaths[z] = obfuscate(managerView.allImages[index][c].imagePaths[z]);
                    }
                }

                // put the array in the JSON format
                var json = new JavaScriptSerializer().Serialize(managerView.allImages[index]);


                return(json);
                //return managerView.allImages[index];
            }
            else
            {
                return(null);
            }
        }