private sitk.VectorOfParameterMap InvertTransformParameters(string parameterFilename)
        {
            sitk.Image fixedImage           = ReadWriteUtils.ReadITKImageFromFile(registrationParameters.FixedImageFilename, sitk.PixelIDValueEnum.sitkFloat32);
            sitk.ElastixImageFilter elastix = null;
            try
            {
                // elastix manual 6.1.6: DisplacementMagnitudePenalty
                elastix = new sitk.ElastixImageFilter();
                elastix.SetInitialTransformParameterFileName(parameterFilename);
                elastix.SetParameterMap(sitk.SimpleITK.GetDefaultParameterMap("rigid"));
                elastix.SetFixedImage(fixedImage);
                elastix.SetMovingImage(fixedImage);
                elastix.SetParameter("HowToCombineTransforms", "Compose");
                elastix.SetParameter("Metric", "DisplacementMagnitudePenalty");
                elastix.SetParameter("NumberOfResolutions", "1");
                elastix.Execute();
                return(elastix.GetTransformParameterMap());

                /*sitk.TransformixImageFilter transformix = new sitk.TransformixImageFilter();
                 * transformix.SetTransformParameterMap(elastix.GetTransformParameterMap());
                 * transformix.SetTransformParameter("InitialTransformParametersFileName", "NoInitialTransform");
                 * transformix.Execute();*/
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(null);
            } finally
            {
                elastix.Dispose();
                fixedImage.Dispose();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Start transformation process.
        /// </summary>
        public void StartTransformation()
        {
            sitk.VectorOfParameterMap parameterMaps = PrepareTransformationParameters();

            foreach (string imageFilename in TransformImages)
            {
                using (sitk.Image img = ReadWriteUtils.ReadITKImageFromFile(imageFilename))
                {
                    List <sitk.Image> channels            = TransformationUtils.SplitColorChannels(img);
                    List <sitk.Image> transformedChannels = new List <sitk.Image>();
                    foreach (sitk.Image channel in channels)
                    {
                        transformedChannels.Add(ExecuteTransform(parameterMaps, channel));
                        channel.Dispose();
                    }

                    sitk.VectorOfImage vectorImages = new sitk.VectorOfImage();
                    foreach (sitk.Image tChannel in transformedChannels)
                    {
                        vectorImages.Add(TransformationUtils.InterpolateImage(tChannel, GetInterpolatorEnum(), sitk.PixelIDValueEnum.sitkUInt8));
                    }
                    sitk.ComposeImageFilter composeImageFilter = new sitk.ComposeImageFilter();
                    sitk.Image composedImage = composeImageFilter.Execute(vectorImages);

                    TransformationUtils.WriteTransformedImage(composedImage, ApplicationContext.OutputPath + "\\" + Path.GetFileNameWithoutExtension(imageFilename) + "_transformed.png");
                }
            }
        }
        /// <summary>
        /// Get the coefficient map of inner structures of tissue for the transform rigidity penalty term.
        /// </summary>
        /// <param name="filename">image filename</param>
        /// <returns>return coefficient map filename</returns>
        private string GetInnerStructureSegmentationsAsCoefficientMap(string filename)
        {
            InnerTissueSegmentation innerSegImage = GetInnerStructureSegmentation(filename);

            string filenameCoefficientMap = ReadWriteUtils.GetOutputDirectory(_parameters, _parameters.Iteration) + Constants.cCoefficientFilename;

            ReadWriteUtils.WriteUMatToFile(filenameCoefficientMap, innerSegImage.GetOutput().FirstOrDefault());
            innerSegImage.Dispose();

            // rescale image
            sitk.Image           img        = ReadWriteUtils.ReadITKImageFromFile(filenameCoefficientMap);
            sitk.CastImageFilter castFilter = new sitk.CastImageFilter();
            castFilter.SetOutputPixelType(sitk.PixelIDValueEnum.sitkFloat32);
            img = castFilter.Execute(img);
            sitk.RescaleIntensityImageFilter filter = new sitk.RescaleIntensityImageFilter();
            filter.SetOutputMinimum(0.0);
            filter.SetOutputMaximum(1.0);
            sitk.Image coefficientMap = filter.Execute(img);

            // save as mhd
            filenameCoefficientMap = ReadWriteUtils.GetOutputDirectory(_parameters, _parameters.Iteration) + Constants.cCoefficientFilename;
            ReadWriteUtils.WriteSitkImage(coefficientMap, filenameCoefficientMap);
            coefficientMap.Dispose();
            return(filenameCoefficientMap);
        }
        /// <summary>
        /// Write transformed image and deformation field to disk
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="transformparams"></param>
        private void WriteTransform(string filename, List <sitk.VectorOfParameterMap> transformparams)
        {
            string resultFilename = ReadWriteUtils.GetOutputDirectory(_parameters) + "\\" + Path.GetFileNameWithoutExtension(filename) + ".png";

            // add transform parameter map to registration parameters
            if (_parameters.TransformationParameterMap.ContainsKey(resultFilename))
            {
                _parameters.TransformationParameterMap.Remove(resultFilename);
            }
            _parameters.TransformationParameterMap.Add(resultFilename, transformparams);

            // read moving image from file
            sitk.Image movingImageToTransform = ReadWriteUtils.ReadITKImageFromFile(filename, sitk.PixelIDValueEnum.sitkVectorUInt8);
            // initialize transform instance
            TransformRGB trans = new TransformRGB(movingImageToTransform, transformparams, _parameters);

            if (_parameters.IsBinaryTransform)
            {
                // for binary reg set interpolation order to zero
                trans.SetInterpolationOrder(0);
            }

            trans.Execute();
            trans.WriteTransformedImage(resultFilename);

            // write deformation field
            sitk.Image deformationField         = trans.GetDeformationField();
            string     filenameDeformationField = ReadWriteUtils.GetOutputDirectory(_parameters, _parameters.Iteration) + "\\deformationField.mhd";

            ReadWriteUtils.WriteSitkImage(deformationField, filenameDeformationField);
            trans.Dispose();
            movingImageToTransform.Dispose();
        }
 /// <summary>
 /// Retrieve mask for a given filename.
 /// </summary>
 /// <param name="filename">filename</param>
 /// <returns>mask of given image</returns>
 private sitk.Image GetMask(string filename, bool isFixed)
 {
     if (isFixed && _parameters.UseFixedMaskFromDisk)
     {
         sitk.Image img = ReadWriteUtils.ReadITKImageFromFile(_parameters.FixedMaskFromDisk);
         return(img);
     }
     else if (!isFixed && _parameters.UseMovingMasksFromDisk)
     {
         sitk.Image img = ReadWriteUtils.ReadITKImageFromFile(_parameters.MovingMasksFromDisk.FirstOrDefault());
         return(img);
     }
     else
     {
         if (_parameters.UseInnerStructuresSegmentation)
         {
             // segmentation of the inner structures of the particle
             return(GetInnerStructureMask(filename));
         }
         else
         {
             // segmentation of the whole particle
             return(GetWholeParticleMask(filename));
         }
     }
 }
        public static List <sitk.VectorOfParameterMap> PerformMultipleRigidRegistrationForComponents(
            string fixedSegmentedMask,
            string movingSegmentedMask,
            int numberOfComposedTransformations,
            RegistrationParameters parameters)
        {
            // created corresponding masks
            Image <Gray, byte> fixedSegments  = new Image <Gray, byte>(fixedSegmentedMask);
            Image <Gray, byte> movingSegments = new Image <Gray, byte>(movingSegmentedMask);

            VectorOfVectorOfPoint contoursFixed  = new VectorOfVectorOfPoint();
            VectorOfVectorOfPoint contoursMoving = new VectorOfVectorOfPoint();

            CvInvoke.FindContours(fixedSegments, contoursFixed, null, Emgu.CV.CvEnum.RetrType.Ccomp, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            CvInvoke.FindContours(movingSegments, contoursMoving, null, Emgu.CV.CvEnum.RetrType.Ccomp, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);

            // retireve dict with contour index and area size ordered by size
            Dictionary <int, double> contoursFixedDict  = GetContourAreaDict(ref contoursFixed);
            Dictionary <int, double> contoursMovingDict = GetContourAreaDict(ref contoursMoving);

            List <Tuple <string, string> > filenameOfMaskComponents = new List <Tuple <string, string> >();

            for (int i = 0; i <= numberOfComposedTransformations; i++)
            {
                var contourFixed  = contoursFixed[contoursFixedDict.ElementAt(i).Key];
                var contourMoving = contoursMoving[contoursMovingDict.ElementAt(i).Key];

                Image <Gray, byte> maskFixed  = new Image <Gray, byte>(fixedSegments.Width, fixedSegments.Height, new Gray(0.0));
                Image <Gray, byte> maskMoving = new Image <Gray, byte>(movingSegments.Width, movingSegments.Height, new Gray(0.0));
                CvInvoke.DrawContours(maskFixed, contourFixed, -1, new MCvScalar(255.0), thickness: -1);
                CvInvoke.DrawContours(maskMoving, contourMoving, -1, new MCvScalar(255.0), thickness: -1);

                string filenameFixed  = Path.GetTempPath() + "\\fixed_0" + i + ".png";
                string filenameMoving = Path.GetTempPath() + "\\moving_0" + i + ".png";
                maskFixed.Save(filenameFixed);
                maskMoving.Save(filenameMoving);
                Tuple <string, string> temp = new Tuple <string, string>(filenameFixed, filenameMoving);
                filenameOfMaskComponents.Add(temp);
            }

            sitk.ParameterMap map = GetDefaultParameterMap(parameters.RegistrationDefaultParams);

            List <sitk.VectorOfParameterMap> list = new List <sitk.VectorOfParameterMap>();

            foreach (Tuple <string, string> tuple in filenameOfMaskComponents)
            {
                sitk.Image img01 = ReadWriteUtils.ReadITKImageFromFile(tuple.Item1);
                sitk.Image img02 = ReadWriteUtils.ReadITKImageFromFile(tuple.Item2);
                parameters.ParamMapToUse = map;
                RigidRegistration reg = new RigidRegistration(img01, img02, parameters);
                reg.Execute();
                sitk.VectorOfParameterMap toAdd = new sitk.VectorOfParameterMap(reg.GetTransformationParameterMap());
                list.Add(toAdd);
                reg.Dispose();
            }
            return(list);
        }
        /// <summary>
        /// Componentwise rigid registration.
        /// Each corresponding masked components will be registrated discretly.
        /// Transformation parameters will be composed befor image is transformed.
        /// </summary>
        /// <param name="fixedMask">reference mask</param>
        /// <param name="movingMask">template mask</param>
        /// <param name="v">number of corresponding components</param>
        /// <param name="filename">moving image filename</param>
        /// <returns></returns>
        private List <sitk.VectorOfParameterMap> ComponentWiseRigidRegistration(sitk.Image fixedMask, sitk.Image movingMask, int v, string filename)
        {
            // convert from sitk to opencv
            var fixedImage  = ReadWriteUtils.ConvertSitkImageToOpenCv <Gray, byte>(fixedMask);
            var movingImage = ReadWriteUtils.ConvertSitkImageToOpenCv <Gray, byte>(movingMask);

            // find contours
            VectorOfVectorOfPoint contoursFixed  = new VectorOfVectorOfPoint();
            VectorOfVectorOfPoint contoursMoving = new VectorOfVectorOfPoint();

            CvInvoke.FindContours(fixedImage, contoursFixed, null, Emgu.CV.CvEnum.RetrType.Ccomp, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            CvInvoke.FindContours(movingImage, contoursMoving, null, Emgu.CV.CvEnum.RetrType.Ccomp, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);

            // retireve dict with contour index and area size ordered by size
            var contoursFixedDict  = RegistrationUtils.GetContourAreaDict(ref contoursFixed).OrderByDescending(it => it.Value);
            var contoursMovingDict = RegistrationUtils.GetContourAreaDict(ref contoursMoving).OrderByDescending(it => it.Value);

            List <Tuple <string, string> > filenameOfMaskComponents = new List <Tuple <string, string> >();

            for (int i = 1; i < v; i++)
            {
                var contourFixed  = contoursFixed[contoursFixedDict.ElementAt(i).Key].ToArray();
                var contourMoving = contoursMoving[contoursMovingDict.ElementAt(i).Key].ToArray();

                Image <Gray, byte> maskFixed  = new Image <Gray, byte>(fixedImage.Width, fixedImage.Height, new Gray(0.0));
                Image <Gray, byte> maskMoving = new Image <Gray, byte>(movingImage.Width, movingImage.Height, new Gray(0.0));
                maskFixed.Draw(contourFixed, new Gray(255.0), -1);
                maskMoving.Draw(contourMoving, new Gray(255.0), -1);
                //CvInvoke.DrawContours(maskFixed, contourFixed, -1, new MCvScalar(255.0), thickness: -1);
                //CvInvoke.DrawContours(maskMoving, contourMoving, -1, new MCvScalar(255.0), thickness: -1);

                string filenameFixed  = Path.GetTempPath() + "\\fixed_0" + i + ".png";
                string filenameMoving = Path.GetTempPath() + "\\moving_0" + i + ".png";
                maskFixed.Save(filenameFixed);
                maskMoving.Save(filenameMoving);
                Tuple <string, string> temp = new Tuple <string, string>(filenameFixed, filenameMoving);
                filenameOfMaskComponents.Add(temp);
            }

            sitk.ParameterMap map = RegistrationUtils.GetDefaultParameterMap(_parameters.RegistrationDefaultParams);

            List <sitk.VectorOfParameterMap> list = new List <sitk.VectorOfParameterMap>();

            foreach (Tuple <string, string> tuple in filenameOfMaskComponents)
            {
                sitk.Image img01 = ReadWriteUtils.ReadITKImageFromFile(tuple.Item1, sitk.PixelIDValueEnum.sitkUInt8);
                sitk.Image img02 = ReadWriteUtils.ReadITKImageFromFile(tuple.Item2, sitk.PixelIDValueEnum.sitkUInt8);
                _parameters.ParamMapToUse = map;
                RigidRegistration reg = new RigidRegistration(img01, img02, _parameters);
                reg.Execute();
                sitk.VectorOfParameterMap toAdd = new sitk.VectorOfParameterMap(reg.GetTransformationParameterMap());
                list.Add(toAdd);
                reg.Dispose();
            }
            return(list);
        }
 private static sitk.LabelOverlapMeasuresImageFilter GetOverlapImageFilter(string mask01iFn, string mask02iFn)
 {
     sitk.LabelOverlapMeasuresImageFilter overlapFilter;
     sitk.Image sImg01 = ReadWriteUtils.ReadITKImageFromFile(mask01iFn);
     sitk.Image sImg02 = ReadWriteUtils.ReadITKImageFromFile(mask02iFn);
     overlapFilter = VisualizationEvaluationUtils.GetOverlapImageFilter(sImg01, sImg02);
     sImg01.Dispose();
     sImg02.Dispose();
     return(overlapFilter);
 }
        /// <summary>
        /// Get image of the inner structures mask of an image.
        /// </summary>
        /// <param name="filename">filename of the image</param>
        /// <returns>masked image</returns>
        private sitk.Image GetInnerStructureMask(string filename)
        {
            string outputFilename       = ReadWriteUtils.GetOutputDirectory(_parameters, _parameters.Iteration) + "\\mask_" + Path.GetFileName(filename);
            InnerTissueSegmentation seg = GetInnerStructureSegmentation(filename);

            seg.GetOutput()[1].Save(outputFilename);
            seg.Dispose();
            sitk.Image mask = ReadWriteUtils.ReadITKImageFromFile(outputFilename);

            return(mask);
        }
        /// <summary>
        /// Retrieves the mask of the whole tissue.
        /// </summary>
        /// <param name="filename">filename of the image</param>
        /// <returns>masked image</returns>
        private sitk.Image GetWholeParticleMask(string filename)
        {
            string            outputFilename = ReadWriteUtils.GetOutputDirectory(_parameters, _parameters.Iteration) + "\\mask_" + Path.GetFileName(filename);
            Image <Bgr, byte> image          = ReadWriteUtils.ReadOpenCVImageFromFile <Bgr, byte>(filename);

            WholeTissueSegmentation segImage = new WholeTissueSegmentation(image, _parameters.WholeTissueSegParams);

            segImage.Execute();
            segImage.GetOutput().Save(outputFilename);
            segImage.Dispose();
            image.Dispose();
            sitk.Image mask = ReadWriteUtils.ReadITKImageFromFile(outputFilename);

            return(mask);
        }
        private void buttonDiffImage_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;

            string fixedImageFilename  = registrationParameters.FixedImageFilename;
            string movingImageFilename = comboBoxMovingImage.SelectedValue.ToString();

            // read images
            var img01      = ReadWriteUtils.ReadITKImageFromFile(fixedImageFilename);
            var img02      = ReadWriteUtils.ReadITKImageFromFile(movingImageFilename);
            var difference = VisualizationEvaluationUtils.GetTotalDifferenceImage(img01, img02);

            ReadWriteUtils.WriteSitkImage(difference, registrationParameters.OutputDirectory + "\\difference.png");
            img01.Dispose();
            img02.Dispose();
            difference.Dispose();

            Cursor.Current = Cursors.Default;
        }
        /// <summary>
        /// Load and resize image depending on the width and height of the largest image in stack.
        /// </summary>
        /// <param name="filename">filename of the image to load</param>
        /// <param name="writeFilename">output filename if image should be written back to disk</param>
        /// <returns>simpleitk image</returns>
        private sitk.Image LoadAndResizeImage(string filename, string writeFilename = null)
        {
            sitk.Image refImage = ReadWriteUtils.ReadITKImageFromFile(filename, sitk.PixelIDValueEnum.sitkVectorUInt8);

            if (refImage.GetWidth() == _parameters.LargestImageWidth && refImage.GetHeight() == _parameters.LargestImageHeight)
            {
                return(refImage);
            }
            else
            {
                sitk.Image refResized = ImageUtils.ResizeImage(refImage, _parameters.LargestImageWidth, _parameters.LargestImageHeight);

                // write image if output filename is defined
                if (writeFilename != null)
                {
                    ReadWriteUtils.WriteSitkImage(refResized, Path.Combine(_parameters.OutputDirectory, Path.GetFileName(writeFilename)));
                }

                return(refResized);
            }
        }