Example #1
0
        /// <summary>
        /// Crops the images.
        /// </summary>
        /// <param name="pathAnnotationsIn">The path annotations in.</param>
        /// <param name="pathImagesIn">The path images in.</param>
        /// <param name="pathOut">The path out.</param>
        /// <exception cref="ArgumentException">
        /// Amount of annotation not equal to amount of images.Check train folder
        /// or
        /// There is no coordinates in annotation file
        /// </exception>
        public void CropImages(string pathAnnotationsIn, string pathImagesIn, string pathOut)
        {
            var annotations = Directory.GetFiles(pathAnnotationsIn);
            var images      = Directory.GetFiles(pathImagesIn);

            if (annotations.Length != images.Length)
            {
                throw new ArgumentException("Amount of annotation not equal to amount of images.Check train folder");
            }

            var coords = new List <int>();

            Directory.CreateDirectory(Constants.PRE_FOLDER_CROPPED);
            int counter = 0;

            for (int i = 0; i < annotations.Length; i++)
            {
                var annotationContent = File.ReadAllText(annotations[i]);
                var image             = new BitmapImage(new Uri(images[i], UriKind.RelativeOrAbsolute));

                Regex regex = new Regex(Constants.PATERN_FOR_CROPPING);

                foreach (Match match in regex.Matches(annotationContent))
                {
                    coords.Clear();
                    var   stringWithValues = match.Value;
                    Regex regexForDigit    = new Regex(@"\d+");

                    foreach (Match digitMatch in regexForDigit.Matches(stringWithValues))
                    {
                        coords.Add(int.Parse(digitMatch.Value));
                    }

                    if (coords.Count < 4)
                    {
                        throw new ArgumentException("There is no coordinates in annotation file");
                    }

                    var frame        = new Int32Rect(coords[0], coords[1], coords[2] - coords[0], coords[3] - coords[1]);
                    var croppedImage = CropImage(image, frame);

                    croppedImage.SaveImage($"{pathOut}\\{counter}.png");
                    counter++;

                    var reflectedImage = new TransformedBitmap(croppedImage, new ScaleTransform {
                        ScaleX = -1
                    });
                    reflectedImage.SaveImage($"{pathOut}\\{counter}.png");
                    counter++;
                }
            }
        }